Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Notes on each set, check-in and live workout stats
InlitXc7c1ae61e3bc
diff --git a/lib/models/live_session.dart b/lib/models/live_session.dartindex 193d7c1..ad51d65 100644--- a/lib/models/live_session.dart+++ b/lib/models/live_session.dart@@ -2,8 +2,10 @@ import 'workout.dart';class SessionSet {SessionSet(this.reps, this.weight, this.done,- {this.kind = SetKind.normal, this.rpe, this.sec, this.km});+ {this.kind = SetKind.normal, this.rpe, this.sec, this.km, this.rest, this.note = ''});int reps;+ String note;+ int? rest;double weight;bool done;SetKind kind;@@ -13,7 +15,7 @@ class SessionSet {bool get counts => kind != SetKind.warmup;- LoggedSet get logged => LoggedSet(reps, weight, kind: kind, rpe: rpe, sec: sec, km: km);+ LoggedSet get logged => LoggedSet(reps, weight, kind: kind, rpe: rpe, sec: sec, km: km, note: note.trim());SessionSet copy({bool done = false}) =>SessionSet(reps, weight, done, kind: kind, rpe: rpe, sec: sec, km: km);@@ -26,6 +28,8 @@ class SessionSet {if (rpe != null) 'e': rpe,if (sec != null) 't': sec,if (km != null) 'km': km,+ if (rest != null) 'rs': rest,+ if (note.isNotEmpty) 'n': note,};factory SessionSet.fromJson(Map<String, dynamic> j) => SessionSet((j['r'] as num).toInt(),@@ -35,6 +39,8 @@ class SessionSet {rpe: (j['e'] as num?)?.toDouble(),sec: (j['t'] as num?)?.toInt(),km: (j['km'] as num?)?.toDouble(),+ rest: (j['rs'] as num?)?.toInt().clamp(0, 3600),+ note: j['n'] as String? ?? '',);}diff --git a/lib/models/workout.dart b/lib/models/workout.dartindex 10a6dcd..5e66fc4 100644--- a/lib/models/workout.dart+++ b/lib/models/workout.dart@@ -17,8 +17,9 @@ double? rpePercent(int reps, double? rpe) {}class LoggedSet {- LoggedSet(this.reps, this.weight, {this.kind = SetKind.normal, this.rpe, this.sec, this.km});+ LoggedSet(this.reps, this.weight, {this.kind = SetKind.normal, this.rpe, this.sec, this.km, this.note = ''});final int reps;+ final String note;final double weight;final SetKind kind;final double? rpe;@@ -41,6 +42,7 @@ class LoggedSet {if (rpe != null) 'e': rpe,if (sec != null) 't': sec,if (km != null) 'km': km,+ if (note.isNotEmpty) 'n': note,};factory LoggedSet.fromJson(Map<String, dynamic> j) => LoggedSet((j['r'] as num).toInt(),@@ -49,6 +51,7 @@ class LoggedSet {rpe: (j['e'] as num?)?.toDouble(),sec: (j['t'] as num?)?.toInt(),km: (j['km'] as num?)?.toDouble(),+ note: j['n'] as String? ?? '',);}@@ -109,12 +112,16 @@ class LoggedExercise {}class LoggedSession {- LoggedSession(this.date, this.durationSec, this.exercises, {this.routineId, this.name});+ LoggedSession(this.date, this.durationSec, this.exercises, {this.routineId, this.name, this.hrAvg, this.hrMax, this.sleep, this.energy});final DateTime date;int durationSec;final List<LoggedExercise> exercises;final String? routineId;String? name;+ int? hrAvg;+ int? hrMax;+ int? sleep;+ int? energy;DateTime get day => date.subtract(Duration(seconds: durationSec));double get volume => exercises.fold(0.0, (s, e) => s + e.volume);@@ -126,6 +133,10 @@ class LoggedSession {'ex': exercises.map((e) => e.toJson()).toList(),if (routineId != null) 'r': routineId,if (name != null) 'n': name,+ if (hrAvg != null) 'hra': hrAvg,+ if (hrMax != null) 'hrm': hrMax,+ if (sleep != null) 'sl': sleep,+ if (energy != null) 'en': energy,};factory LoggedSession.fromJson(Map<String, dynamic> j) => LoggedSession(DateTime.parse(j['d'] as String),@@ -133,6 +144,10 @@ class LoggedSession {(j['ex'] as List).map((e) => LoggedExercise.fromJson(e as Map<String, dynamic>)).toList(),routineId: j['r'] as String?,name: j['n'] as String?,+ hrAvg: (j['hra'] as num?)?.toInt(),+ hrMax: (j['hrm'] as num?)?.toInt(),+ sleep: (j['sl'] as num?)?.toInt().clamp(1, 5),+ energy: (j['en'] as num?)?.toInt().clamp(1, 5),);}diff --git a/lib/state/stats_state.dart b/lib/state/stats_state.dartindex 5dfbe63..d1640ea 100644--- a/lib/state/stats_state.dart+++ b/lib/state/stats_state.dart@@ -3,7 +3,7 @@ part of 'fit_state.dart';mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineState {List<Exercise> recommendedExercises(int n) {final muscles = suggestedFocus.muscles;- final pool = kExercises.where((e) => !noSuggest.contains(e.id) && !isArchived(e.id) && fitsHere(e));+ final pool = kExercises.where((e) => e.kind != 'sport' && !noSuggest.contains(e.id) && !isArchived(e.id) && fitsHere(e));final picks = [for (final m in muscles) ...pool.where((e) => e.primary == m).take(1),];@@ -359,7 +359,8 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStfinal named = sessionTitle(s);if (named != null && named.trim().isNotEmpty) return named;final count = <String, int>{};- for (final e in s.exercises) {+ final lifts = s.exercises.where((e) => countsForMuscles(e.id));+ for (final e in lifts.isEmpty ? s.exercises : lifts) {final g = muscleGroup(e.primary);count[g] = (count[g] ?? 0) + e.workingSets.length;}@@ -405,6 +406,7 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStvoid deleteSession(LoggedSession s) {sessions.remove(s);+ healthForget(s);_releaseLevel(s, s.exercises.map((e) => e.id));persistNow();_refreshWidgets();@@ -414,13 +416,19 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStvoid setSessionDuration(LoggedSession s, int seconds) {if (!sessions.contains(s) || seconds < 0 || seconds == s.durationSec) return;s.durationSec = seconds;+ healthSave(s);persistNow();notifyListeners();}void deleteLoggedExercise(LoggedSession s, LoggedExercise e) {s.exercises.remove(e);- if (s.exercises.isEmpty) sessions.remove(s);+ if (s.exercises.isEmpty) {+ sessions.remove(s);+ healthForget(s);+ } else {+ healthSave(s);+ }_releaseLevel(s, [e.id]);persistNow();notifyListeners();@@ -436,6 +444,7 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStrpe: old.rpe,sec: sec ?? old.sec,km: km ?? old.km,+ note: old.note,);persistNow();_refreshWidgets();@@ -827,6 +836,14 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStdouble muscleTargetFor(int days) => weeklySetTarget * days / 7;+ @override+ bool countsForMuscles(String id) {+ final ex = exerciseById(id);+ if (ex == null) return !isCardio(id);+ final kind = kindOf(ex);+ return kind != 'cardio' && kind != 'sport';+ }+Map<String, double> muscleSetsOver(int days) {final today = _dayKey(DateTime.now());return Map.of(_remember(('setsOver', days), () => _muscleSetsFrom(shiftDays(today, -(days - 1))), today));@@ -838,7 +855,7 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStif (_dayKey(s.day).isBefore(start)) continue;for (final e in s.exercises) {final n = e.workingSets.length.toDouble();- if (n <= 0) continue;+ if (n <= 0 || !countsForMuscles(e.id)) continue;out[e.primary] = (out[e.primary] ?? 0) + n;for (final m in exerciseById(e.id)?.secondary ?? const <String>[]) {out[m] = (out[m] ?? 0) + n / 2;@@ -897,7 +914,7 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStif (d.isBefore(a) || d.isAfter(b)) continue;for (final e in s.exercises) {final n = e.workingSets.length.toDouble();- if (n <= 0) continue;+ if (n <= 0 || !countsForMuscles(e.id)) continue;out[e.primary] = (out[e.primary] ?? 0) + n;for (final m in exerciseById(e.id)?.secondary ?? const <String>[]) {out[m] = (out[m] ?? 0) + n / 2;@@ -982,6 +999,13 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStreturn (r.values.reduce((a, b) => a + b) / r.length * 100).round();}+ int? hoursUntilRecovery(String muscle, double target, {DateTime? now}) {+ final fatigue = muscleFatigue(now: now)[muscle] ?? 0;+ final limit = _fullFatigue * (1 - target.clamp(0.0, 0.99));+ if (fatigue <= limit) return null;+ return (_tau(muscle) * math.log(fatigue / limit)).ceil();+ }+int? hoursUntilRecovered(String muscle, {DateTime? now}) {final fatigue = muscleFatigue(now: now)[muscle] ?? 0;final limit = _fullFatigue * 0.2;@@ -1096,6 +1120,115 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineSt'eZyBC3j': ([0.6, 0.85, 1.15, 1.5], [0.4, 0.6, 0.8, 1.05]),};+ static const balanceLifts = <(String, double, List<String>)>[+ ('qXTaZnJ', 1.0, ['qXTaZnJ']),+ ('ila4NZS', 1.2, ['ila4NZS']),+ ('EIeI8Vf', 0.75, ['EIeI8Vf']),+ ('eZyBC3j', 0.52, ['eZyBC3j']),+ ('Kyd9Rz5', 0.45, ['Kyd9Rz5', 'kTbSH9h']),+ ];++ ({List<({String id, double kg, double target, double score})> lifts, String? behind})? get structuralBalance =>+ _remember('balance', _structuralBalance, _dayKey(DateTime.now()));++ ({List<({String id, double kg, double target, double score})> lifts, String? behind})? _structuralBalance() {+ final since = DateTime.now().subtract(const Duration(days: 120));+ final found = <(String, double, double)>[];+ for (final (id, ratio, ids) in balanceLifts) {+ var best = 0.0;+ for (final any in ids) {+ for (final h in exerciseHistory(any)) {+ if (h.date.isBefore(since)) break;+ if (h.ex.bestOneRm > best) best = h.ex.bestOneRm;+ }+ }+ if (best > 0) found.add((id, ratio, best));+ }+ if (found.length < 3) return null;+ final implied = [for (final f in found) f.$3 / f.$2]..sort();+ final mid = implied.length.isOdd+ ? implied[implied.length ~/ 2]+ : (implied[implied.length ~/ 2 - 1] + implied[implied.length ~/ 2]) / 2;+ final lifts = [+ for (final (id, ratio, kg) in found) (id: id, kg: kg, target: mid * ratio, score: kg / (mid * ratio)),+ ];+ final low = lifts.reduce((a, b) => a.score <= b.score ? a : b);+ return (lifts: lifts, behind: low.score < 0.9 ? low.id : null);+ }++ void rateSession(LoggedSession s, {required bool sleep, int? value}) {+ if (!sessions.contains(s)) return;+ final v = value?.clamp(1, 5);+ if (sleep) {+ if (s.sleep == v) return;+ s.sleep = v;+ } else {+ if (s.energy == v) return;+ s.energy = v;+ }+ _persist();+ notifyListeners();+ }++ Map<LoggedSession, double> get _sessionForm => _remember('sessionForm', () {+ final out = <LoggedSession, double>{};+ final best = <String, List<(DateTime, double)>>{};+ for (final s in sessions) {+ final ratios = <double>[];+ for (final e in s.exercises) {+ final rm = e.bestOneRm;+ if (rm <= 0) continue;+ final past = best[e.id] ??= [];+ final since = s.date.subtract(const Duration(days: 90));+ past.removeWhere((p) => p.$1.isBefore(since));+ if (past.isNotEmpty) {+ final top = past.map((p) => p.$2).reduce(math.max);+ ratios.add(rm / top);+ }+ past.add((s.date, rm));+ }+ if (ratios.isNotEmpty && (s.sleep != null || s.energy != null)) {+ out[s] = ratios.reduce((a, b) => a + b) / ratios.length;+ }+ }+ return out;+ });++ ({bool sleep, int pct, int low, int high})? _readinessEffect(bool sleep) {+ final low = <double>[], high = <double>[];+ for (final MapEntry(key: s, value: form) in _sessionForm.entries) {+ final v = sleep ? s.sleep : s.energy;+ if (v == null) continue;+ if (v <= 2) low.add(form);+ if (v >= 4) high.add(form);+ }+ if (low.length < 3 || high.length < 3) return null;+ double mean(List<double> l) => l.reduce((a, b) => a + b) / l.length;+ final pct = ((mean(low) / mean(high) - 1) * 100).round();+ return (sleep: sleep, pct: pct, low: low.length, high: high.length);+ }++ ({bool sleep, int pct, int low, int high})? get readinessEffect {+ final a = _readinessEffect(true), b = _readinessEffect(false);+ if (a == null || b == null) return a ?? b;+ return a.pct.abs() >= b.pct.abs() ? a : b;+ }++ ({int rated, double? sleep, double? energy}) get readinessRecent {+ final since = DateTime.now().subtract(const Duration(days: 30));+ final sl = <int>[], en = <int>[];+ var rated = 0;+ for (final s in sessions) {+ if (s.sleep == null && s.energy == null) continue;+ rated++;+ if (s.date.isBefore(since)) continue;+ if (s.sleep != null) sl.add(s.sleep!);+ if (s.energy != null) en.add(s.energy!);+ }+ double? avg(List<int> l) => l.isEmpty ? null : l.reduce((a, b) => a + b) / l.length;+ return (rated: rated, sleep: avg(sl), energy: avg(en));+ }+({double ratio, int level, double toNext})? relativeStrength(String id) {final steps = _ratioSteps[id];final body = latestBodyweight?.kg ?? profile.weightKg;@@ -1162,6 +1295,34 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStreturn h.map((r) => _round1(r.ex.bestOneRm)).toList();}+ bool canShowRelative(String id) =>+ modeOf(id).isEmpty &&+ !isRepsOnly(id) &&+ !isAssisted(id) &&+ exerciseById(id)?.equipment != 'Bodyweight' &&+ (bodyweight.isNotEmpty || profile.weightKg > 0);++ List<({DateTime date, double value})> exerciseTrend(String id, {int days = 0, bool relative = false}) {+ final from = days <= 0 ? null : shiftDays(_dayKey(DateTime.now()), -(days - 1));+ if (relative && !canShowRelative(id)) return const [];+ final reps = isRepsOnly(id), assisted = isAssisted(id);+ final out = <({DateTime date, double value})>[];+ for (final h in exerciseHistory(id).reversed) {+ if (from != null && _dayKey(h.date).isBefore(from)) continue;+ final sets = h.ex.workingSets.where((s) => s.reps > 0);+ if (sets.isEmpty) continue;+ final value = reps+ ? sets.map((s) => s.reps).reduce(math.max).toDouble()+ : assisted+ ? _round1(sets.map((s) => s.weight).reduce(math.min))+ : relative+ ? (h.ex.bestOneRm / _weightOn(h.date) * 100).roundToDouble()+ : _round1(h.ex.bestOneRm);+ if (value > 0 || assisted) out.add((date: h.date, value: value));+ }+ return out;+ }+bool goalFits(String id) => modeOf(id).isEmpty && !isAssisted(id);PrKind goalKind(String id) {diff --git a/lib/state/workout_state.dart b/lib/state/workout_state.dartindex 7448aec..b59ab7e 100644--- a/lib/state/workout_state.dart+++ b/lib/state/workout_state.dart@@ -249,16 +249,33 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStif (planned != null && planned.isNotEmpty) return _fromPlan(id, planned);final sets = _workingOpeners(id, count: count);if (!warmsUp(id) || isRepsOnly(id) || modeOf(id).isNotEmpty) return sets;- return [..._warmupFor(sets), ...sets];+ return [..._warmupFor(sets, id), ...sets];}- List<SessionSet> _modeOpeners(String mode, List<LoggedSet> last) {+ int? nextHoldSeconds(String id) {+ if (modeOf(id) != 'time') return null;+ final step = holdStepFor(id);+ if (step <= 0) return null;+ final secs = [for (final l in lastSetsFor(id)) if (l.counts && (l.sec ?? 0) > 0) l.sec!];+ if (secs.isEmpty) return null;+ final aim = secs.first;+ return secs.every((s) => s >= aim) ? aim + step : aim;+ }++ bool holdGoesUp(String id) {+ final next = nextHoldSeconds(id);+ final last = [for (final l in lastSetsFor(id)) if (l.counts && (l.sec ?? 0) > 0) l.sec!];+ return next != null && last.isNotEmpty && next > last.first;+ }++ List<SessionSet> _modeOpeners(String mode, List<LoggedSet> last, [String? id]) {final cardio = mode == 'cardio';+ final hold = id == null ? null : nextHoldSeconds(id);final fromLast = [for (final l in last)if ((l.sec ?? 0) > 0 || (l.km ?? 0) > 0)SessionSet(0, cardio ? 0 : l.weight, false,- sec: l.sec ?? (cardio ? 1200 : 30), km: cardio ? (l.km ?? 0) : null),+ sec: hold ?? l.sec ?? (cardio ? 1200 : 30), km: cardio ? (l.km ?? 0) : null),];if (fromLast.isNotEmpty) return fromLast;if (cardio) return [SessionSet(0, 0, false, sec: 1200, km: 0)];@@ -270,7 +287,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal mode = modeOf(id);final List<SessionSet> base;if (mode.isNotEmpty) {- base = _modeOpeners(mode, last);+ base = _modeOpeners(mode, last, id);} else if (last.isNotEmpty) {final plan = hasProgress(id) ? _nextPlan(id) : null;base = plan?.sets ?? last.map((l) => SessionSet(l.reps, l.weight, false)).toList();@@ -327,6 +344,12 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStdouble deloadWeight(String id, double from) {final step = progressStep[id] ?? fromDisplayWeight(weightStep);+ if (stackFor(id) != null) {+ if (isAssisted(id)) return snapToStack(id, from, dir: 1);+ final aim = from * (100 - progressRule(id).deloadPct) / 100;+ final down = floorToStack(id, aim);+ return down < from - 0.001 ? down : snapToStack(id, from, dir: -1);+ }if (isAssisted(id)) return from + step;final grid = weightStep;final shown = toDisplayWeight(from);@@ -355,7 +378,16 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal step = progressStep[id] ?? fromDisplayWeight(weightStep);final assisted = isAssisted(id);final load = assisted ? last.map((l) => l.weight).reduce(math.min) : last.map((l) => l.weight).reduce(math.max);- double heavier(double w, [int times = 1]) => assisted ? math.max(0.0, w - step * times) : w + step * times;+ double heavier(double w, [int times = 1]) {+ if (stackFor(id) != null) {+ var v = w;+ for (var i = 0; i < times; i++) {+ v = snapToStack(id, v, dir: assisted ? -1 : 1);+ }+ return v;+ }+ return assisted ? math.max(0.0, w - step * times) : w + step * times;+ }final volume = rule.kind == ProgressKind.volume;List<SessionSet> shaped(int Function(LoggedSet l) repsOf, double Function(double w) weightOf, [int? count]) => [@@ -440,6 +472,8 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}String? nextTargetLabel(String id) {+ final hold = nextHoldSeconds(id);+ if (hold != null) return durationLabel(hold);final target = nextTarget(id);if (target == null) return null;if (isRepsOnly(id)) return '${target.reps} ${t.repsCol.toLowerCase()}';@@ -658,7 +692,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}final sets = session!.exercises[exIdx].sets;final mini = setIdx + 1 < sets.length && const [SetKind.restPause, SetKind.cluster].contains(sets[setIdx + 1].kind);- startRest(mini: mini);+ startRest(mini: mini, seconds: st.rest);if (autoAdvance || sessionLocked) _advanceWhenDone(exIdx);}@@ -715,6 +749,25 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStnotifyListeners();}+ ({Map<String, double> planned, Map<String, double> done}) get sessionMuscleSets {+ final planned = <String, double>{}, done = <String, double>{};+ for (final e in session?.exercises ?? const <SessionExercise>[]) {+ if (!countsForMuscles(e.id)) continue;+ final total = e.sets.where((st) => st.counts).length.toDouble();+ final ticked = e.sets.where((st) => st.counts && st.done).length.toDouble();+ if (total <= 0) continue;+ final secondary = exerciseById(e.id)?.secondary ?? const <String>[];+ void add(Map<String, double> m, String id, double n) => m[id] = (m[id] ?? 0) + n;+ add(planned, e.primary, total);+ if (ticked > 0) add(done, e.primary, ticked);+ for (final m in secondary) {+ add(planned, m, total / 2);+ if (ticked > 0) add(done, m, ticked / 2);+ }+ }+ return (planned: planned, done: done);+ }+double get sessionVolumeKg {var kg = 0.0;for (final e in session?.exercises ?? const <SessionExercise>[]) {@@ -852,14 +905,34 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStreturn _beats(ex.id, target.logged, best);}- void startRest({bool mini = false}) {+ int normalRestAfter(int exIdx, int setIdx) {+ final s = session;+ if (s == null || exIdx < 0 || exIdx >= s.exercises.length) return restSeconds;+ final ex = s.exercises[exIdx];+ final sets = ex.sets;+ final mini = setIdx + 1 < sets.length && const [SetKind.restPause, SetKind.cluster].contains(sets[setIdx + 1].kind);+ if (mini && miniRestSeconds > 0) return miniRestSeconds;+ return routineRest(s.routineId, ex.id) ?? restFor(ex.id);+ }++ void setSetRest(int exIdx, int setIdx, int? seconds) {+ final s = session;+ if (s == null || exIdx < 0 || exIdx >= s.exercises.length) return;+ final sets = s.exercises[exIdx].sets;+ if (setIdx < 0 || setIdx >= sets.length) return;+ sets[setIdx].rest = seconds?.clamp(0, 3600);+ _persist();+ notifyListeners();+ }++ void startRest({bool mini = false, int? seconds}) {if (sessionPaused || session?.manual == true) return;_restTimer?.cancel();RestAlarm.instance.stopSound();final exId = session!.exercises.isEmpty? '': session!.exercises[session!.currentIndex.clamp(0, session!.exercises.length - 1)].id;- final seconds = mini && miniRestSeconds > 0+ seconds ??= mini && miniRestSeconds > 0? miniRestSeconds: routineRest(session!.routineId, exId) ?? restFor(exId);if (seconds <= 0) {@@ -1247,6 +1320,10 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStvoid bumpSessionWeight(int exIdx, int setIdx, int dir) {final id = session!.exercises[exIdx].id;+ if (stackFor(id) != null) {+ setSessionWeight(exIdx, setIdx, snapToStack(id, session!.exercises[exIdx].sets[setIdx].weight, dir: dir));+ return;+ }final current = toShownFor(id, session!.exercises[exIdx].sets[setIdx].weight);final step = weightStepFor(id);final next = _roundTo(current, step) + dir * step;@@ -1255,7 +1332,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStstatic const _warmupSpec = [(0.4, 10), (0.6, 5), (0.8, 3)];- List<SessionSet> _warmupFor(List<SessionSet> sets) {+ List<SessionSet> _warmupFor(List<SessionSet> sets, [String? id]) {if (sets.isEmpty) return const [];final target = sets.map((st) => st.weight).reduce(math.max);if (target <= 0) {@@ -1266,7 +1343,9 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfor (final spec in _warmupSpec)SessionSet(spec.$2,- fromDisplayWeight(_roundTo(toDisplayWeight(target * spec.$1), plateStep)),+ id != null && stackFor(id) != null+ ? snapToStack(id, target * spec.$1)+ : fromDisplayWeight(_roundTo(toDisplayWeight(target * spec.$1), plateStep)),false,kind: SetKind.warmup,),@@ -1285,7 +1364,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStif (modeOf(s.exercises[exIdx].id).isNotEmpty) return;final sets = s.exercises[exIdx].sets;if (hasWarmup(exIdx)) return;- final warm = _warmupFor(sets);+ final warm = _warmupFor(sets, s.exercises[exIdx].id);if (warm.isEmpty) return;sets.insertAll(0, warm);_persist();@@ -1305,6 +1384,26 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}}+ void setSetNote(int exIdx, int setIdx, String note) {+ final s = session;+ if (s == null || exIdx < 0 || exIdx >= s.exercises.length) return;+ final sets = s.exercises[exIdx].sets;+ if (setIdx < 0 || setIdx >= sets.length) return;+ final clean = note.length > 280 ? note.substring(0, 280) : note;+ if (sets[setIdx].note == clean) return;+ sets[setIdx].note = clean;+ _persist();+ notifyListeners();+ }++ List<(int, String)> lastSetNotes(String exId) {+ final last = lastSetsFor(exId);+ return [+ for (var i = 0; i < last.length; i++)+ if (last[i].note.isNotEmpty) (i + 1, last[i].note),+ ];+ }+void setSetKind(int exIdx, int setIdx, SetKind kind) {final s = session;if (s == null || exIdx >= s.exercises.length) return;@@ -1504,6 +1603,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt_photosFrom = null;_computeSummaryHighlights(entry);_offerLevelUp(entry);+ healthSave(entry);} else {_filed = null;summaryPrs = 0;@@ -1634,6 +1734,52 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStnotifyListeners();}+ List<SessionExercise> get sessionExtras {+ final r = sessionRoutine;+ if (r == null) return const [];+ final 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,+ ];+ }++ bool addExtraToRoutine(String exId) {+ final r = sessionRoutine;+ final s = session;+ if (r == null || s == null || r.exerciseIds.contains(exId)) return false;+ final i = s.exercises.indexWhere((e) => e.id == exId);+ if (i < 0) return false;+ final ex = s.exercises[i];+ var at = 0;+ for (var j = i - 1; j >= 0; j--) {+ final k = r.exerciseIds.indexOf(s.exercises[j].swappedFrom ?? s.exercises[j].id);+ final m = k >= 0 ? k : r.exerciseIds.indexOf(s.exercises[j].id);+ if (m >= 0) {+ at = m + 1;+ break;+ }+ }+ r.exerciseIds.insert(at.clamp(0, r.exerciseIds.length), exId);+ final done = ex.sets.where((st) => st.done).toList();+ final timed = modeOf(exId).isNotEmpty;+ if (done.isNotEmpty) {+ setPlannedSets(r.id, exId, [+ for (final st in done)+ PlannedSet(+ reps: timed ? null : st.reps,+ weightKg: st.weight > 0 ? st.weight : null,+ kind: st.kind,+ sec: st.sec,+ km: st.km,+ ),+ ]);+ }+ persistNow();+ notifyListeners();+ return true;+ }+double get summaryVolumeKg => (session?.summaryVolume ?? 0).toDouble();int summaryPrs = 0;@@ -1841,7 +1987,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSte.primary,e.sets.map((x) => SessionSet(x.reps, x.weight, true,- kind: x.kind, rpe: x.rpe, sec: x.sec, km: x.km))+ kind: x.kind, rpe: x.rpe, sec: x.sec, km: x.km, note: x.note)).toList())).toList();_restTimer?.cancel();diff --git a/lib/widgets/check_in.dart b/lib/widgets/check_in.dartnew file mode 100644index 0000000..d5a0f74--- /dev/null+++ b/lib/widgets/check_in.dart@@ -0,0 +1,119 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';++import '../l10n/l10n.dart';+import '../models/workout.dart';+import '../state/fit_state.dart';+import '../theme/app_colors.dart';+import '../theme/app_theme.dart';+import 'ui_kit.dart';++String checkInWord(int v) => switch (v) {+ 1 => t.checkInLevel1,+ 2 => t.checkInLevel2,+ 3 => t.checkInLevel3,+ 4 => t.checkInLevel4,+ _ => t.checkInLevel5,+ };++class CheckInCard extends StatelessWidget {+ const CheckInCard(this.session, {super.key, this.flat = false});+ final LoggedSession session;+ final bool flat;++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final body = Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Text(t.checkInTitle.toUpperCase(),+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),+ const SizedBox(height: 12),+ CheckInRow(+ icon: PhosphorIconsRegular.moon,+ label: t.checkInSleep,+ value: session.sleep,+ color: gc.sage,+ onPick: (v) => fit.rateSession(session, sleep: true, value: v),+ ),+ const SizedBox(height: 12),+ CheckInRow(+ icon: PhosphorIconsRegular.lightning,+ label: t.checkInEnergy,+ value: session.energy,+ color: gc.brass,+ onPick: (v) => fit.rateSession(session, sleep: false, value: v),+ ),+ ]);+ if (flat) return body;+ return SoftCard(radius: 22, padding: const EdgeInsets.fromLTRB(16, 16, 16, 16), child: body);+ }+}++class CheckInRow extends StatelessWidget {+ const CheckInRow({+ super.key,+ required this.icon,+ required this.label,+ required this.value,+ required this.color,+ required this.onPick,+ });+ final IconData icon;+ final String label;+ final int? value;+ final Color color;+ final ValueChanged<int?> onPick;++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final v = value;+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Row(children: [+ Icon(icon, size: 15, color: v == null ? gc.textSecondary : color),+ const SizedBox(width: 7),+ Text(label, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.text)),+ const Spacer(),+ AnimatedSwitcher(+ duration: const Duration(milliseconds: 180),+ child: Text(v == null ? t.checkInSkip : checkInWord(v),+ key: ValueKey(v),+ style: AppTheme.f(12, weight: FontWeight.w600, color: v == null ? gc.textTertiary : color)),+ ),+ ]),+ const SizedBox(height: 8),+ Row(children: [+ for (var i = 1; i <= 5; i++) ...[+ if (i > 1) const SizedBox(width: 6),+ Expanded(+ child: Semantics(+ button: true,+ selected: v == i,+ label: '$label ${checkInWord(i)}',+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.selectionClick();+ onPick(v == i ? null : i);+ },+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 6),+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 200),+ curve: Curves.easeOutCubic,+ height: 10,+ decoration: BoxDecoration(+ color: v != null && i <= v ? color : gc.bgRaised2,+ borderRadius: BorderRadius.circular(5),+ ),+ ),+ ),+ ),+ ),+ ),+ ],+ ]),+ ]);+ }+}diff --git a/lib/widgets/exercise_history_sheet.dart b/lib/widgets/exercise_history_sheet.dartnew file mode 100644index 0000000..67a308f--- /dev/null+++ b/lib/widgets/exercise_history_sheet.dart@@ -0,0 +1,253 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';++import '../l10n/l10n.dart';+import '../models/exercise.dart';+import '../models/workout.dart';+import '../state/fit_state.dart';+import '../theme/app_colors.dart';+import '../theme/app_theme.dart';+import 'charts.dart';+import 'glass.dart';+import 'ui_kit.dart';++void showExerciseHistorySheet(BuildContext context, String exerciseId) {+ showAppSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: Colors.transparent,+ builder: (_) => ExerciseHistorySheet(exerciseId: exerciseId),+ );+}++class ExerciseHistorySheet extends StatefulWidget {+ const ExerciseHistorySheet({super.key, required this.exerciseId});++ final String exerciseId;++ @override+ State<ExerciseHistorySheet> createState() => _ExerciseHistorySheetState();+}++class _ExerciseHistorySheetState extends State<ExerciseHistorySheet> {+ static const _page = 12;+ static const _ranges = [30, 90, 365, 0];++ String get _id => widget.exerciseId;+ late final _history = fit.exerciseHistory(_id);+ late final bool _charted = fit.modeOf(_id).isEmpty && fit.exerciseTrend(_id).length > 1;+ late int _range = _pickRange();+ bool _relative = false;+ int _shown = _page;++ int _pickRange() {+ for (final r in _ranges) {+ if (fit.exerciseTrend(_id, days: r).length >= 3) return r;+ }+ return 0;+ }++ String _rangeLabel(int r) => switch (r) {+ 30 => t.days30,+ 90 => t.days90,+ 365 => t.days365,+ _ => t.daysAll,+ };++ bool get _plain => fit.isRepsOnly(_id) || _relative;++ String _value(double v) => _plain ? '${v.round()}' : fit.weightValueFor(_id, v);++ String get _unit => _relative ? '%' : fit.isRepsOnly(_id) ? t.repsCol.toLowerCase() : fit.unitsFor(_id);++ String _summary(List<LoggedSet> sets) => sets+ .map((s) => s.rpe == null+ ? fit.loggedSetLabel(s, id: _id)+ : '${fit.loggedSetLabel(s, id: _id)} ${fit.effortTag(s.rpe!)}')+ .join(' · ');++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final ex = fit.exerciseById(_id);+ final rows = _history.take(_shown).toList();+ return Container(+ padding: sheetPad(context),+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.86),+ decoration: sheetDecoration(gc),+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const SheetHandle(),+ const SizedBox(height: 18),+ Text(ex == null ? '' : exerciseName(ex), style: AppTheme.f(19, weight: FontWeight.w800, color: gc.text)),+ const SizedBox(height: 4),+ Text('${titleCase(t.history)} · ${t.sessionCount(_history.length)}',+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary)),+ if (_charted) ...[+ const SizedBox(height: 18),+ _trend(gc),+ ],+ const SizedBox(height: 14),+ if (_history.isEmpty)+ Text(t.noHistory, style: AppTheme.f(13, weight: FontWeight.w500, color: gc.textSecondary)),+ AnimatedSize(+ duration: const Duration(milliseconds: 280),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ for (var i = 0; i < rows.length; i++)+ Container(+ padding: const EdgeInsets.symmetric(vertical: 12),+ decoration: BoxDecoration(+ border: i < rows.length - 1+ ? Border(bottom: BorderSide(color: gc.border.withValues(alpha: 0.55)))+ : null,+ ),+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [+ SizedBox(+ width: 92,+ child: Text(t.shortDate(rows[i].date),+ style: AppTheme.f(13, weight: FontWeight.w600, color: gc.text)),+ ),+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(_summary(rows[i].ex.sets),+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),+ for (var k = 0; k < rows[i].ex.sets.length; k++)+ if (rows[i].ex.sets[k].note.isNotEmpty) ...[+ const SizedBox(height: 3),+ Text(t.setNoteLine(k + 1, rows[i].ex.sets[k].note),+ style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textTertiary, height: 1.35)),+ ],+ ]),+ ),+ ]),+ ),+ ]),+ ),+ if (_history.length > _shown) ...[+ const SizedBox(height: 10),+ Center(+ child: Pressable(+ scale: 0.95,+ onTap: () {+ HapticFeedback.selectionClick();+ setState(() => _shown += _page);+ },+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 9),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(100)),+ child: Text(t.historyMore((_history.length - _shown).clamp(0, _page)),+ style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.text)),+ ),+ ),+ ),+ ],+ ],+ ),+ ),+ );+ }++ Widget _trend(GymColors gc) {+ final points = fit.exerciseTrend(_id, days: _range, relative: _relative);+ final values = [+ for (final p in points) _plain ? p.value : fit.toShownFor(_id, p.value),+ ];+ final last = points.isEmpty ? null : points.last.value;+ final delta = points.length < 2 ? 0.0 : points.last.value - points.first.value;+ final lowerIsBetter = fit.isAssisted(_id);+ final up = lowerIsBetter ? delta <= 0 : delta >= 0;+ final shownDelta = _plain ? delta.round().toDouble() : fit.toShownFor(_id, delta);+ final caption = _relative ? t.ofBodyweight : fit.isRepsOnly(_id) || lowerIsBetter ? null : t.estOneRm;+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Center(+ child: SegToggle([+ for (final r in _ranges)+ SegOption(_rangeLabel(r), r == _range, () {+ HapticFeedback.selectionClick();+ setState(() => _range = r);+ }),+ ]),+ ),+ if (fit.canShowRelative(_id)) ...[+ const SizedBox(height: 10),+ Center(+ child: SegToggle([+ SegOption(fit.unitsFor(_id), !_relative, () {+ HapticFeedback.selectionClick();+ setState(() => _relative = false);+ }),+ SegOption(t.pctBodyweight, _relative, () {+ HapticFeedback.selectionClick();+ setState(() => _relative = true);+ }),+ ], fontSize: 11.5, vPad: 5),+ ),+ ],+ const SizedBox(height: 16),+ AnimatedSwitcher(+ duration: const Duration(milliseconds: 260),+ switchInCurve: Curves.easeOutCubic,+ switchOutCurve: const Interval(0.6, 1),+ child: KeyedSubtree(+ key: ValueKey((_range, _relative)),+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Row(crossAxisAlignment: CrossAxisAlignment.end, children: [+ if (last != null)+ RichText(+ text: TextSpan(+ text: _value(last),+ style: AppTheme.d(30, weight: FontWeight.w800, color: gc.text),+ children: [+ TextSpan(text: ' $_unit', style: AppTheme.d(14, weight: FontWeight.w700, color: gc.textSecondary)),+ ],+ ),+ ),+ if (caption != null) ...[+ const SizedBox(width: 8),+ Padding(+ padding: const EdgeInsets.only(bottom: 5),+ child: Text(caption, style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textTertiary)),+ ),+ ],+ const Spacer(),+ if (shownDelta.abs() >= 0.1)+ Padding(+ padding: const EdgeInsets.only(bottom: 5),+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),+ decoration: BoxDecoration(+ color: up ? gc.sageSoft : gc.accentSoft, borderRadius: BorderRadius.circular(100)),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(delta >= 0 ? PhosphorIconsBold.trendUp : PhosphorIconsBold.trendDown,+ size: 12, color: up ? gc.sage : gc.accent),+ const SizedBox(width: 4),+ Text('${delta >= 0 ? '+' : ''}${fmt((shownDelta * 10).round() / 10)}${_relative ? ' %' : ''}',+ style: AppTheme.s(11.5, weight: FontWeight.w700, color: up ? gc.sage : gc.accent)),+ ]),+ ),+ ),+ ]),+ const SizedBox(height: 12),+ if (values.length >= 2)+ TrendChart(values: values, height: 120, scale: (v) => _plain ? '${v.round()}' : fmt(v))+ else+ SizedBox(+ height: 120,+ child: Center(+ child: Text(t.noHistory,+ textAlign: TextAlign.center,+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textTertiary)),+ ),+ ),+ ]),+ ),+ ),+ ]);+ }+}diff --git a/lib/widgets/set_kind.dart b/lib/widgets/set_kind.dartindex 7aedc68..e3f912a 100644--- a/lib/widgets/set_kind.dart+++ b/lib/widgets/set_kind.dart@@ -109,10 +109,7 @@ Future<SetKind?> askSetKind(BuildContext context, SetKind current) {isScrollControlled: true,builder: (sheet) => Container(padding: sheetPad(sheet),- decoration: BoxDecoration(- color: gc.bgRaised,- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),- ),+ decoration: sheetDecoration(gc),child: SingleChildScrollView(child: Column(mainAxisSize: MainAxisSize.min,diff --git a/lib/widgets/weight_stack_sheet.dart b/lib/widgets/weight_stack_sheet.dartnew file mode 100644index 0000000..6b517aa--- /dev/null+++ b/lib/widgets/weight_stack_sheet.dart@@ -0,0 +1,190 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';++import '../l10n/l10n.dart';+import '../state/fit_state.dart';+import '../theme/app_colors.dart';+import '../theme/app_theme.dart';+import 'dialogs.dart';+import 'glass.dart';+import 'ui_kit.dart';++Future<void> showWeightStackSheet(BuildContext context, String exerciseId) => showAppSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: Colors.transparent,+ builder: (_) => _WeightStackSheet(id: exerciseId),+ );++class _WeightStackSheet extends StatefulWidget {+ const _WeightStackSheet({required this.id});++ final String id;++ @override+ State<_WeightStackSheet> createState() => _WeightStackSheetState();+}++class _WeightStackSheetState extends State<_WeightStackSheet> {+ late List<double> _kg = [...?fit.stackFor(widget.id)];+ late final _from = TextEditingController(text: _kg.isEmpty ? _seed(5) : _shown(_kg.first));+ late final _to = TextEditingController(text: _kg.isEmpty ? _seed(100) : _shown(_kg.last));+ late final _step = TextEditingController(text: _kg.length < 2 ? _seed(5) : _shown(_kg[1] - _kg[0]));++ String get _unit => fit.unitsFor(widget.id);++ String _seed(double kg) => fit.isLbFor(widget.id) ? fmt((kg * 2.2).roundToDouble()) : fmt(kg);++ String _shown(double kg) => fit.weightValueFor(widget.id, kg);++ double? _read(TextEditingController c) {+ final v = double.tryParse(c.text.trim().replaceAll(',', '.'));+ return v == null || v <= 0 ? null : fit.fromShownFor(widget.id, v);+ }++ @override+ void dispose() {+ _from.dispose();+ _to.dispose();+ _step.dispose();+ super.dispose();+ }++ void _save(List<double> next) {+ fit.setWeightStack(widget.id, next);+ setState(() => _kg = [...?fit.stackFor(widget.id)]);+ }++ void _fill() {+ final a = _read(_from), b = _read(_to), step = _read(_step);+ if (a == null || b == null || step == null || b <= a || (b - a) / step > 59) {+ HapticFeedback.heavyImpact();+ return;+ }+ HapticFeedback.mediumImpact();+ _save([for (var v = a; v <= b + 0.001; v += step) v]);+ }++ Future<void> _add() async {+ final v = await askNumber(context, title: '${t.stackAddWeight} ($_unit)', initial: '', decimal: true);+ if (v == null || v <= 0) return;+ _save([..._kg, fit.fromShownFor(widget.id, v)]);+ }++ Future<void> _edit(int i) async {+ final v = await askNumber(context, title: '${t.stackEditWeight} ($_unit)', initial: _shown(_kg[i]), decimal: true);+ if (v == null) return;+ final next = [..._kg]..removeAt(i);+ if (v > 0) next.add(fit.fromShownFor(widget.id, v));+ _save(next);+ }++ Widget _field(GymColors gc, String label, TextEditingController c) => Expanded(+ child: Container(+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 4),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(14)),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(label.toUpperCase(),+ style: AppTheme.f(9.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.1)),+ TextField(+ controller: c,+ keyboardType: const TextInputType.numberWithOptions(decimal: true),+ cursorColor: gc.accent,+ style: AppTheme.f(16, weight: FontWeight.w800, color: gc.text),+ decoration: InputDecoration(+ isDense: true,+ border: InputBorder.none,+ suffixText: _unit,+ suffixStyle: AppTheme.f(12, weight: FontWeight.w600, color: gc.textTertiary),+ ),+ ),+ ]),+ ),+ );++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ return Container(+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.9),+ padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),+ decoration: sheetDecoration(gc),+ child: SingleChildScrollView(+ padding: sheetPad(context),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const SheetHandle(),+ const SizedBox(height: 16),+ SheetTitle(t.weightStack, subtitle: t.weightStackHint),+ const SizedBox(height: 18),+ Row(children: [+ _field(gc, t.stackFrom, _from),+ const SizedBox(width: 8),+ _field(gc, t.stackTo, _to),+ const SizedBox(width: 8),+ _field(gc, t.stackEvery, _step),+ ]),+ const SizedBox(height: 10),+ GhostButton(label: t.stackFill, icon: PhosphorIconsRegular.stack, onTap: _fill),+ const SizedBox(height: 18),+ if (_kg.isNotEmpty) ...[+ Text(t.stackTapToFix,+ style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textSecondary, height: 1.35)),+ const SizedBox(height: 10),+ ],+ AnimatedSize(+ duration: const Duration(milliseconds: 240),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: Wrap(spacing: 8, runSpacing: 8, children: [+ for (var i = 0; i < _kg.length; i++)+ Pressable(+ scale: 0.92,+ onTap: () => _edit(i),+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(100)),+ child: Text(_shown(_kg[i]),+ style: AppTheme.f(13, weight: FontWeight.w700, color: gc.text)+ .copyWith(fontFeatures: const [FontFeature.tabularFigures()])),+ ),+ ),+ Pressable(+ scale: 0.92,+ onTap: _add,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),+ decoration: BoxDecoration(+ color: gc.accentSoft,+ borderRadius: BorderRadius.circular(100),+ ),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(PhosphorIconsBold.plus, size: 12, color: gc.accent),+ const SizedBox(width: 4),+ Text(t.addShort, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.accent)),+ ]),+ ),+ ),+ ]),+ ),+ const SizedBox(height: 22),+ PrimaryButton(label: t.done, onTap: () => Navigator.of(context).pop()),+ if (_kg.isNotEmpty)+ Center(+ child: TextButton(+ onPressed: () {+ HapticFeedback.selectionClick();+ _save(const []);+ },+ child: Text(t.stackClear, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.danger)),+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/lib/widgets/workout_notes.dart b/lib/widgets/workout_notes.dartindex 4996166..de40b68 100644--- a/lib/widgets/workout_notes.dart+++ b/lib/widgets/workout_notes.dart@@ -68,10 +68,7 @@ Widget _sheetBox(BuildContext context, List<Widget> children) {child: Container(constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.85),padding: sheetPad(context),- decoration: BoxDecoration(- color: gc.bgRaised,- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),- ),+ decoration: sheetDecoration(gc),child: SingleChildScrollView(child: Column(mainAxisSize: MainAxisSize.min,@@ -295,3 +292,107 @@ class _WorkoutNoteEditorState extends State<_WorkoutNoteEditor> {]);}}++class LastSetNotes extends StatelessWidget {+ const LastSetNotes({super.key, required this.exerciseId});++ final String exerciseId;++ @override+ Widget build(BuildContext context) {+ final notes = fit.lastSetNotes(exerciseId);+ if (notes.isEmpty) return const SizedBox.shrink();+ final gc = context.gc;+ return Container(+ width: double.infinity,+ padding: const EdgeInsets.fromLTRB(10, 8, 12, 8),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(12)),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Row(children: [+ Icon(PhosphorIconsRegular.clockCounterClockwise, size: 13, color: gc.textTertiary),+ const SizedBox(width: 8),+ Text(t.lastTimeNotes.toUpperCase(),+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),+ ]),+ for (final (n, note) in notes) ...[+ const SizedBox(height: 5),+ Padding(+ padding: const EdgeInsetsDirectional.only(start: 21),+ child: Text(t.setNoteLine(n, note.replaceAll(RegExp(r'\s*\n\s*'), ' ')),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.textSecondary, height: 1.3)),+ ),+ ],+ ]),+ );+ }+}++class SetNoteField extends StatefulWidget {+ const SetNoteField({super.key, required this.initial, required this.onChanged, this.last});++ final String initial;+ final String? last;+ final ValueChanged<String> onChanged;++ @override+ State<SetNoteField> createState() => _SetNoteFieldState();+}++class _SetNoteFieldState extends State<SetNoteField> {+ late final TextEditingController _text = TextEditingController(text: widget.initial);++ @override+ void dispose() {+ _text.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final last = widget.last;+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Text(t.setNote,+ style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary, letterSpacing: 0.4)),+ const SizedBox(height: 8),+ Container(+ padding: const EdgeInsets.fromLTRB(14, 2, 14, 2),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),+ child: TextField(+ controller: _text,+ minLines: 1,+ maxLines: 4,+ maxLength: 280,+ textCapitalization: TextCapitalization.sentences,+ cursorColor: gc.accent,+ onChanged: widget.onChanged,+ style: AppTheme.f(14.5, weight: FontWeight.w500, color: gc.text, height: 1.4),+ decoration: InputDecoration(+ border: InputBorder.none,+ hintText: t.setNoteHint,+ hintStyle: AppTheme.f(14.5, weight: FontWeight.w500, color: gc.textTertiary),+ counterText: '',+ ),+ ),+ ),+ if (last != null && last.isNotEmpty) ...[+ const SizedBox(height: 8),+ Row(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Padding(+ padding: const EdgeInsets.only(top: 1.5),+ child: Icon(PhosphorIconsRegular.clockCounterClockwise, size: 13, color: gc.textTertiary),+ ),+ const SizedBox(width: 6),+ Expanded(+ child: Text(t.setNoteLast(last),+ maxLines: 3,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textTertiary, height: 1.3)),+ ),+ ]),+ ],+ ]);+ }+}diff --git a/test/exercise_kind_test.dart b/test/exercise_kind_test.dartindex 3c7ad27..63c473e 100644--- a/test/exercise_kind_test.dart+++ b/test/exercise_kind_test.dart@@ -46,4 +46,13 @@ void main() {final plain = fit.addCustomExercise(name: 'Row', primary: 'back', equipment: 'Cable');expect(kindOfId(plain), 'strength');});++ test('los deportes son su propio tipo y no suman series por músculo', () {+ expect(kindOfId('football'), 'sport');+ expect(kindOfId('padel'), 'sport');+ expect(fit.isCardio('badminton'), true, reason: 'se apuntan por tiempo');+ expect(fit.countsForMuscles('volleyball'), false);+ expect(fit.countsForMuscles('EIeI8Vf'), true);+ expect(fit.recommendedExercises(30).any((e) => e.kind == 'sport'), false);+ });}diff --git a/test/history_test.dart b/test/history_test.dartindex d716ea2..64f0ec6 100644--- a/test/history_test.dart+++ b/test/history_test.dart@@ -5,6 +5,9 @@ import 'package:gymmane/l10n/l10n.dart';import 'package:gymmane/models/workout.dart';import 'package:gymmane/services/local_store.dart';import 'package:gymmane/state/fit_state.dart';+import 'package:gymmane/theme/app_theme.dart';+import 'package:gymmane/widgets/charts.dart';+import 'package:gymmane/widgets/exercise_history_sheet.dart';import 'package:shared_preferences/shared_preferences.dart';void main() {@@ -19,7 +22,8 @@ void main() {});test('se corrige y se guarda', () {- final s = LoggedSession(DateTime.now(), 108 * 60, [+ final n = DateTime.now();+ final s = LoggedSession(DateTime(n.year, n.month, n.day, 12), 108 * 60, [LoggedExercise('x', 'x', 'chest', [LoggedSet(8, 60)]),]);fit.sessions.add(s);@@ -312,4 +316,91 @@ void main() {expect(s.date, DateTime(day.year, day.month, day.day, 19, 15));});});++ group('#297 historial y gráfica del ejercicio en la sesión', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ void logDays(List<(int, double)> list) {+ final n = DateTime.now();+ for (final (ago, kg) in list) {+ fit.sessions.add(LoggedSession(DateTime(n.year, n.month, n.day - ago, 18), 3600, [+ LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(5, kg)]),+ ]));+ }+ }++ test('la tendencia va de la más antigua a la última y respeta el rango', () {+ logDays([(200, 60), (60, 70), (10, 80), (2, 85)]);+ final all = fit.exerciseTrend(bench());+ expect(all.length, 4);+ expect(all.first.value, lessThan(all.last.value));+ expect(fit.exerciseTrend(bench(), days: 30).length, 2);+ expect(fit.exerciseTrend(bench(), days: 90).length, 3);+ });++ test('en % del peso usa lo que pesabas ese día', () {+ final n = DateTime.now();+ fit.bodyweight+ ..add(BodyweightEntry(DateTime(n.year, n.month, n.day - 40), 100))+ ..add(BodyweightEntry(DateTime(n.year, n.month, n.day - 5), 80));+ logDays([(30, 100), (2, 100)]);+ expect(fit.canShowRelative(bench()), isTrue);+ final rel = fit.exerciseTrend(bench(), relative: true);+ final kg = fit.exerciseTrend(bench());+ expect(rel.first.value, (kg.first.value / 100 * 100).roundToDouble());+ expect(rel.last.value, (kg.last.value / 80 * 100).roundToDouble());+ expect(rel.last.value, greaterThan(rel.first.value));+ expect(fit.canShowRelative(fit.matchExerciseByName('Pull Up')!.id), isFalse);+ });++ test('el total levantado suma todo lo que has hecho', () {+ logDays([(3, 100), (1, 50)]);+ expect(fit.totalVolumeKg, 5 * 100 + 5 * 50);+ expect(fit.liftedSpanOf(fit.totalVolumeKg), ('750', 'kg'));+ });++ testWidgets('enseña la gráfica y carga más sesiones al pedirlo', (tester) async {+ logDays([for (var i = 0; i < 20; i++) (i * 3, 60.0 + i)]);+ await tester.pumpWidget(MaterialApp(+ theme: AppTheme.dark,+ home: Scaffold(body: Builder(builder: (context) {+ return Center(+ child: TextButton(+ onPressed: () => showExerciseHistorySheet(context, bench()),+ child: const Text('open'),+ ),+ );+ })),+ ));+ await tester.tap(find.text('open'));+ for (var i = 0; i < 12; i++) {+ await tester.pump(const Duration(milliseconds: 60));+ }+ expect(find.byType(TrendChart), findsOneWidget);+ expect(find.text(t.historyMore(8)), findsOneWidget);+ await tester.ensureVisible(find.text(t.historyMore(8)));+ await tester.pump(const Duration(milliseconds: 100));+ await tester.tap(find.text(t.historyMore(8)));+ for (var i = 0; i < 8; i++) {+ await tester.pump(const Duration(milliseconds: 60));+ }+ expect(find.text(t.historyMore(8)), findsNothing);+ await tester.ensureVisible(find.text(t.daysAll));+ await tester.pump(const Duration(milliseconds: 100));+ await tester.tap(find.text(t.daysAll));+ for (var i = 0; i < 8; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(find.byType(TrendChart), findsOneWidget);+ });+ });}diff --git a/test/muscles_test.dart b/test/muscles_test.dartindex 9eb71ae..199425e 100644--- a/test/muscles_test.dart+++ b/test/muscles_test.dart@@ -60,7 +60,7 @@ void main() {test('cuenta los días desde la última serie del músculo principal', () {final now = DateTime.now();- fit.sessions.add(LoggedSession(now.subtract(const Duration(days: 9)), 600, [+ fit.sessions.add(LoggedSession(DateTime(now.year, now.month, now.day - 9, 12), 600, [LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(8, 60)]),]));final days = fit.daysSinceTrained();@@ -69,6 +69,24 @@ void main() {expect(fit.untrainedLongest(), isNot(contains('chest')));expect(fit.untrainedLongest().length, 3);});++ test('#300 el cardio no suma series al músculo aunque lleve uno', () {+ final run = fit.addCustomExercise(name: 'Escaladora', primary: 'quads', equipment: 'Machine', mode: 'cardio');+ final walk = fit.addCustomExercise(name: 'Cinta', primary: 'quads', equipment: 'Machine', kind: 'cardio');+ final now = DateTime.now();+ fit.sessions.add(LoggedSession(now, 1800, [+ LoggedExercise(run, 'Escaladora', 'quads', [LoggedSet(1, 0, sec: 1200)]),+ LoggedExercise(walk, 'Cinta', 'quads', [LoggedSet(1, 0, sec: 900)]),+ LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(8, 60), LoggedSet(8, 60)]),+ ]));+ final sets = fit.muscleSetsOver(7);+ expect(sets['quads'], isNull);+ expect(sets['chest'], 2);+ expect(fit.countsForMuscles(bench()), isTrue);+ expect(fit.countsForMuscles(run), isFalse);+ final treadmill = fit.allExercises.firstWhere((e) => fit.kindOf(e) == 'cardio');+ expect(fit.countsForMuscles(treadmill.id), isFalse);+ });});group('recovery', () {@@ -104,6 +122,21 @@ void main() {expect(later['chest'], greaterThan(0.8));expect(fit.stillRecovering(now: now), contains('chest'));});++ test('dice cuándo pasa a recuperando y cuándo a listo', () {+ final now = DateTime(2026, 9, 18, 18);+ fit.sessions.add(LoggedSession(now.subtract(const Duration(hours: 1)), 3600, [+ LoggedExercise(idOf('Barbell Bench Press'), 'Bench', 'chest',+ [for (var i = 0; i < 8; i++) LoggedSet(8, 80, rpe: 9)]),+ ]));+ final mid = fit.hoursUntilRecovery('chest', 0.5, now: now)!;+ final ready = fit.hoursUntilRecovery('chest', 0.8, now: now)!;+ expect(ready, greaterThan(mid));+ expect(ready, fit.hoursUntilRecovered('chest', now: now));+ expect(fit.muscleRecovery(now: now.add(Duration(hours: mid)))['chest'], greaterThanOrEqualTo(0.5));+ expect(fit.muscleRecovery(now: now.add(Duration(hours: ready)))['chest'], greaterThanOrEqualTo(0.8));+ expect(fit.hoursUntilRecovery('quads', 0.8, now: now), isNull);+ });});group('músculos de la prensa', () {diff --git a/test/readiness_test.dart b/test/readiness_test.dartnew file mode 100644index 0000000..b581efb--- /dev/null+++ b/test/readiness_test.dart@@ -0,0 +1,68 @@+import 'package:flutter_test/flutter_test.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';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ LoggedSession bench(int daysAgo, double kg) {+ final s = LoggedSession(+ DateTime.now().subtract(Duration(days: daysAgo)),+ 3600,+ [LoggedExercise('EIeI8Vf', 'Barbell Bench Press', 'chest', [LoggedSet(5, kg)])],+ );+ fit.sessions.add(s);+ fit.sessions.sort((a, b) => a.date.compareTo(b.date));+ return s;+ }++ test('sueño y energía se guardan con el entreno y vuelven al cargar', () {+ final s = bench(1, 100);+ fit.rateSession(s, sleep: true, value: 2);+ fit.rateSession(s, sleep: false, value: 9);+ expect(s.sleep, 2);+ expect(s.energy, 5, reason: 'la escala acaba en 5');+ final back = LoggedSession.fromJson(s.toJson());+ expect(back.sleep, 2);+ expect(back.energy, 5);+ fit.rateSession(s, sleep: true, value: null);+ expect(LoggedSession.fromJson(s.toJson()).sleep, isNull);+ });++ test('sin días buenos y malos suficientes no se inventa nada', () {+ final s = bench(1, 100);+ fit.rateSession(s, sleep: true, value: 1);+ expect(fit.readinessEffect, isNull);+ expect(fit.readinessRecent.rated, 1);+ expect(fit.readinessRecent.sleep, 1);+ });++ test('dormir mal se ve en las marcas', () {+ bench(20, 100);+ for (var i = 0; i < 6; i++) {+ final good = i.isEven;+ final s = bench(18 - i * 2, good ? 100 : 90);+ fit.rateSession(s, sleep: true, value: good ? 5 : 1);+ }+ final effect = fit.readinessEffect!;+ expect(effect.sleep, true);+ expect(effect.pct, -10);+ expect(effect.low, 3);+ expect(effect.high, 3);+ });++ test('se puede no preguntar al acabar', () {+ expect(fit.askCheckIn, true);+ fit.toggleAskCheckIn();+ expect(fit.askCheckIn, false);+ });+}diff --git a/test/rest_timer_test.dart b/test/rest_timer_test.dartindex 80bb1c7..ce35e66 100644--- a/test/rest_timer_test.dart+++ b/test/rest_timer_test.dart@@ -32,6 +32,28 @@ void main() {expect(fit.session!.restRemaining, isNotNull);}+ test('una serie puede llevar su propio descanso solo hoy', () {+ final bench = fit.matchExerciseByName('Bench Press')!.id;+ fit.startRoutine(routineOf([bench]));+ fit.endCountdown();+ final normal = fit.normalRestAfter(0, 0);+ fit.setSetRest(0, 0, 240);+ fit.toggleSet(0, 0);+ expect(fit.restTotal, 240);+ fit.skipRest();+ fit.setSetRest(0, 1, 0);+ fit.toggleSet(0, 1);+ expect(fit.session!.restRemaining, isNull);+ fit.setSetRest(0, 2, 30);+ fit.setSetRest(0, 2, null);+ fit.toggleSet(0, 2);+ expect(fit.restTotal, normal);+ fit.skipRest();+ final saved = fit.session!.toJson();+ expect(((saved['ex'] as List).first['s'] as List).first['rs'], 240);+ fit.saveAndExit();+ });+test('fija el descanso al tiempo elegido', () {rest();fit.setRest(200);diff --git a/test/routine_session_edit_test.dart b/test/routine_session_edit_test.dartindex 4b357fe..1236605 100644--- a/test/routine_session_edit_test.dart+++ b/test/routine_session_edit_test.dart@@ -199,4 +199,43 @@ void main() {expect(fit.onboarded, false);});});++ group('nuevo en este entreno', () {+ test('un ejercicio metido de más se puede añadir solo y en su sitio, con sus series', () {+ final r = fit.createRoutine('Test');+ fit.toggleRoutineExercise(r, a);+ fit.toggleRoutineExercise(r, c);+ fit.startRoutine(fit.routines.single);+ fit.addExerciseToSession(b);+ final s = fit.session!;+ for (var i = 0; i < s.exercises.length; i++) {+ fit.toggleSet(i, 0);+ }+ s.exercises[1].sets.first+ ..reps = 12+ ..weight = 30;+ fit.finishSession();+ expect(s.exercises.map((e) => e.id), [a, b, c]);+ expect(fit.sessionExtras.map((e) => e.id), [b]);+ expect(fit.addExtraToRoutine(b), isTrue);+ expect(fit.routines.single.exerciseIds, [a, b, c]);+ final plan = fit.plannedSets(fit.routines.single, b);+ expect(plan.length, 1);+ expect((plan.single.reps, plan.single.weightKg), (12, 30.0));+ expect(fit.sessionExtras, isEmpty);+ expect(fit.addExtraToRoutine(b), isFalse);+ fit.saveAndExit();+ });++ test('sin series hechas o sin rutina no hay nada que ofrecer', () {+ final r = fit.createRoutine('Test');+ fit.toggleRoutineExercise(r, a);+ fit.startRoutine(fit.routines.single);+ fit.addExerciseToSession(b);+ fit.toggleSet(0, 0);+ fit.finishSession();+ expect(fit.sessionExtras, isEmpty);+ fit.saveAndExit();+ });+ });}diff --git a/test/rpe_test.dart b/test/rpe_test.dartindex 559e3fb..ccf3dd4 100644--- a/test/rpe_test.dart+++ b/test/rpe_test.dart@@ -73,9 +73,9 @@ void main() {]),]);final rows = csv.trim().split('\n');- expect(rows.first, endsWith(',rpe'));- expect(rows[1], endsWith(',8.5'));- expect(rows[2], endsWith(','));+ expect(rows.first, endsWith(',rpe,note'));+ expect(rows[1], endsWith(',8.5,'));+ expect(rows[2], endsWith(',,'));final back = parseImport(csv);final sets = back.sessions.single.exercises.single.sets;@@ -83,6 +83,20 @@ void main() {expect(sets.last.rpe, isNull);});+ test('la nota de la serie sale en el CSV y vuelve al importarlo', () {+ final csv = Store.instance.exportCsv([+ LoggedSession(DateTime(2026, 11, 2, 18), 3000, [+ LoggedExercise('bench', 'Bench Press', 'chest', [+ LoggedSet(5, 100, note: 'agarre, más cerrado'),+ LoggedSet(5, 100),+ ]),+ ]),+ ]);+ final sets = parseImport(csv).sessions.single.exercises.single.sets;+ expect(sets.first.note, 'agarre, más cerrado');+ expect(sets.last.note, isEmpty);+ });+test('Hevy trae su RPE y una columna RIR se convierte', () {const hevy = '"title","start_time","end_time","description","exercise_title","superset_id",''"exercise_notes","set_index","set_type","weight_kg","reps","distance_km","duration_seconds","rpe"\n'diff --git a/test/set_kinds_test.dart b/test/set_kinds_test.dartindex 6177392..da1a206 100644--- a/test/set_kinds_test.dart+++ b/test/set_kinds_test.dart@@ -208,4 +208,36 @@ void main() {fit.skipRest();});});++ test('a set note is saved with the workout and comes back next time', () {+ startChestSession();+ final id = fit.session!.exercises.first.id;+ fit.setSessionReps(0, 0, 8);+ fit.setSessionWeight(0, 0, 60);+ fit.setSetNote(0, 0, 'Grip slipped');+ fit.toggleSet(0, 0);+ fit.finishSession();++ final logged = fit.sessions.single.exercises.single;+ expect(logged.sets.first.note, 'Grip slipped');+ expect(fit.lastSetNotes(id), [(1, 'Grip slipped')]);+ expect(fit.previousSet(id, 0)?.note, 'Grip slipped');+ });++ test('a blank note is not kept and a long one is cut', () {+ startChestSession();+ fit.setSetNote(0, 0, ' ');+ fit.toggleSet(0, 0);+ fit.setSetNote(0, 0, 'x' * 400);+ expect(fit.session!.exercises.first.sets.first.note.length, 280);+ fit.setSetNote(0, 0, ' ');+ fit.finishSession();+ expect(fit.sessions.single.exercises.single.sets.first.note, isEmpty);+ });++ test('the note of a set survives saving and loading', () {+ final set = LoggedSet(8, 60, note: 'agarre cerrado');+ expect(LoggedSet.fromJson(set.toJson()).note, 'agarre cerrado');+ expect(LoggedSet.fromJson(LoggedSet(8, 60).toJson()).note, isEmpty);+ });}diff --git a/test/strength_calculators_test.dart b/test/strength_calculators_test.dartindex 63d848f..df9acb7 100644--- a/test/strength_calculators_test.dart+++ b/test/strength_calculators_test.dart@@ -75,4 +75,42 @@ void main() {expect(fit.dotsSquat, closeTo(140, 0.1));fit.closeTool();});++ group('equilibrio de fuerza', () {+ void lift(String id, double kg) {+ final n = DateTime.now();+ fit.sessions.add(LoggedSession(DateTime(n.year, n.month, n.day - 3, 18), 3600, [+ LoggedExercise(id, id, 'chest', [LoggedSet(1, kg)]),+ ]));+ }++ test('con menos de tres básicos no dice nada', () {+ fit.sessions.clear();+ lift('qXTaZnJ', 100);+ lift('EIeI8Vf', 75);+ expect(fit.structuralBalance, isNull);+ });++ test('señala el que va atrasado y cuánto le falta', () {+ fit.sessions.clear();+ lift('qXTaZnJ', 100);+ lift('ila4NZS', 120);+ lift('EIeI8Vf', 75);+ lift('kTbSH9h', 30);+ final b = fit.structuralBalance!;+ expect(b.behind, 'Kyd9Rz5');+ final ohp = b.lifts.firstWhere((l) => l.id == 'Kyd9Rz5');+ final squat = b.lifts.firstWhere((l) => l.id == 'qXTaZnJ');+ expect(ohp.target, closeTo(squat.kg * 0.45, 0.01));+ expect(b.lifts.firstWhere((l) => l.id == 'qXTaZnJ').score, closeTo(1, 0.01));+ });++ test('todo en proporción no marca a nadie', () {+ fit.sessions.clear();+ lift('qXTaZnJ', 100);+ lift('ila4NZS', 118);+ lift('EIeI8Vf', 76);+ expect(fit.structuralBalance!.behind, isNull);+ });+ });}diff --git a/test/timed_and_cardio_test.dart b/test/timed_and_cardio_test.dartindex 39867d9..def6de6 100644--- a/test/timed_and_cardio_test.dart+++ b/test/timed_and_cardio_test.dart@@ -450,4 +450,57 @@ void main() {expect(fit.holding, isFalse);});});++ group('progresión por tiempo', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String plank() {+ final id = fit.matchExerciseByName('Plank')!.id;+ fit.setExerciseMode(id, 'time');+ return id;+ }++ void held(List<int> secs) {+ final n = DateTime.now();+ fit.sessions.add(LoggedSession(DateTime(n.year, n.month, n.day - 1, 18), 600, [+ LoggedExercise(plank(), 'Plank', 'abdomen', [for (final s in secs) LoggedSet(0, 0, sec: s)]),+ ]));+ }++ test('si aguantas todas las series sube los segundos; si no, repite', () {+ expect(fit.modeOf(plank()), 'time');+ held([45, 45, 45]);+ expect(fit.nextHoldSeconds(plank()), isNull);+ fit.cycleHoldStep(plank(), 1);+ expect(fit.holdStepFor(plank()), 5);+ expect(fit.nextHoldSeconds(plank()), 50);+ expect(fit.holdGoesUp(plank()), isTrue);+ expect(fit.nextTargetLabel(plank()), isNotNull);+ fit.sessions.clear();+ held([45, 40, 45]);+ expect(fit.nextHoldSeconds(plank()), 45);+ expect(fit.holdGoesUp(plank()), isFalse);+ });++ test('la sesión abre con los segundos nuevos y el ajuste se guarda', () {+ held([30, 30]);+ fit.cycleHoldStep(plank(), 1);+ fit.cycleHoldStep(plank(), 1);+ final r = fit.createRoutine('Core');+ fit.toggleRoutineExercise(r, plank());+ fit.startRoutine(fit.routines.firstWhere((x) => x.id == r));+ expect(fit.session!.exercises.single.sets.map((s) => s.sec), everyElement(40));+ fit.saveAndExit();+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.holdStepFor(plank()), 10);+ fit.cycleHoldStep(plank(), -5);+ expect(fit.holdStepFor(plank()), 0);+ });+ });}diff --git a/test/weights_test.dart b/test/weights_test.dartindex b8b075a..3ba7761 100644--- a/test/weights_test.dart+++ b/test/weights_test.dart@@ -176,4 +176,51 @@ void main() {expect(fit.defaultBar, 15);});});++ group('pila de pesos de máquina', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String machine() => fit.allExercises.firstWhere((e) => e.equipment == 'Machine').id;++ test('los botones saltan solo entre los pesos de la pila', () {+ final id = machine();+ fit.setWeightStack(id, [5, 11.3, 18.1, 25, 11.3, -3]);+ expect(fit.stackFor(id), [5, 11.3, 18.1, 25]);+ fit.sessionPicks+ ..clear()+ ..add(id);+ fit.startSession();+ fit.setSessionWeight(0, 0, 11.3);+ fit.bumpSessionWeight(0, 0, 1);+ expect(fit.session!.exercises[0].sets[0].weight, 18.1);+ fit.bumpSessionWeight(0, 0, 1);+ fit.bumpSessionWeight(0, 0, 1);+ expect(fit.session!.exercises[0].sets[0].weight, 25, reason: 'arriba del todo se queda');+ fit.setSessionWeight(0, 0, 14);+ fit.bumpSessionWeight(0, 0, -1);+ expect(fit.session!.exercises[0].sets[0].weight, 11.3);+ });++ test('la progresión y la descarga caen en la pila', () {+ final id = machine();+ fit.setWeightStack(id, [20, 27.5, 34, 41, 48]);+ expect(fit.snapToStack(id, 34, dir: 1), 41);+ expect(fit.deloadWeight(id, 41), 34);+ expect(fit.floorToStack(id, 30), 27.5);+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.stackFor(id), [20, 27.5, 34, 41, 48]);+ fit.setWeightStack(id, const []);+ expect(fit.stackFor(id), isNull);+ });+ });}