Skip to content

Offline gym log for Android. No account, no ads, no internet.

Swap an exercise mid-workout, rest per routine and add to a routine from the exercise page

InlitXe43ff94b57bf
diff --git a/lib/models/live_session.dart b/lib/models/live_session.dart
index 9ac360e..758429b 100644
--- a/lib/models/live_session.dart
+++ b/lib/models/live_session.dart
@@ -39,12 +39,13 @@ class SessionSet {
}
class SessionExercise {
- SessionExercise(this.id, this.name, this.primary, this.sets, {this.linkedNext = false});
+ SessionExercise(this.id, this.name, this.primary, this.sets, {this.linkedNext = false, this.swappedFrom});
final String id;
final String name;
final String primary;
final List<SessionSet> sets;
bool linkedNext;
+ final String? swappedFrom;
bool get hasUndone => sets.any((s) => !s.done);
@@ -54,6 +55,7 @@ class SessionExercise {
'p': primary,
's': sets.map((s) => s.toJson()).toList(),
if (linkedNext) 'l': true,
+ if (swappedFrom != null) 'sw': swappedFrom,
};
factory SessionExercise.fromJson(Map<String, dynamic> j) => SessionExercise(
j['id'] as String,
@@ -61,6 +63,7 @@ class SessionExercise {
j['p'] as String,
(j['s'] as List).map((e) => SessionSet.fromJson((e as Map).cast<String, dynamic>())).toList(),
linkedNext: j['l'] as bool? ?? false,
+ swappedFrom: j['sw'] as String?,
);
}
diff --git a/lib/models/workout.dart b/lib/models/workout.dart
index 57c1cf1..39bfe02 100644
--- a/lib/models/workout.dart
+++ b/lib/models/workout.dart
@@ -178,11 +178,13 @@ class Routine {
{Map<String, int>? sets,
Set<String>? chained,
Map<String, List<PlannedSet>>? plan,
+ Map<String, int>? rest,
this.group = '',
this.color = -1})
: sets = sets ?? {},
chained = chained ?? {},
- plan = plan ?? {};
+ plan = plan ?? {},
+ rest = rest ?? {};
final String id;
String name;
String group;
@@ -191,11 +193,13 @@ class Routine {
final Map<String, int> sets;
final Set<String> chained;
final Map<String, List<PlannedSet>> plan;
+ final Map<String, int> rest;
Map<String, dynamic> toJson() => {
'id': id,
'n': name,
'ex': exerciseIds,
+ if (rest.isNotEmpty) 'r': rest,
if (sets.isNotEmpty) 's': sets,
if (chained.isNotEmpty) 'c': chained.toList(),
if (group.isNotEmpty) 'g': group,
@@ -214,6 +218,8 @@ class Routine {
k as String,
(v as List).map((s) => PlannedSet.fromJson((s as Map).cast<String, dynamic>())).toList(),
)),
+ rest: ((j['r'] as Map?) ?? const {})
+ .map((k, v) => MapEntry(k as String, ((v as num).toInt()).clamp(0, 600))),
group: (j['g'] as String?) ?? '',
color: (j['k'] as num?)?.toInt() ?? -1,
);
diff --git a/lib/screens/exercise_detail_screen.dart b/lib/screens/exercise_detail_screen.dart
index 12e9479..d8358d4 100644
--- a/lib/screens/exercise_detail_screen.dart
+++ b/lib/screens/exercise_detail_screen.dart
@@ -161,6 +161,11 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {
),
Text(exerciseName(ex),
style: AppTheme.f(26, weight: FontWeight.w800, color: gc.text, height: 1.1)),
+ if (ex.aliases.isNotEmpty) ...[
+ const SizedBox(height: 6),
+ Text(t.alsoCalled(ex.aliases.join(', ')),
+ style: AppTheme.f(13, weight: FontWeight.w500, color: gc.textSecondary, height: 1.35)),
+ ],
const SizedBox(height: 18),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -173,33 +178,7 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {
],
),
const SizedBox(height: 18),
- _group(gc, [
- _modeRow(context, gc, ex.id, mode),
- if (mode != 'cardio') _repsOnlyRow(gc, ex.id, repsOnly),
- _restRow(gc, ex.id),
- if (ex.equipment == 'Barbell' || ex.equipment == 'Machine') _barRow(gc, ex),
- _switchRow(
- gc,
- PhosphorIconsRegular.sparkle,
- t.suggestInWorkouts,
- t.suggestInWorkoutsHint,
- fit.suggests(ex.id),
- () => fit.toggleSuggest(ex.id),
- ),
- if (!repsOnly && mode.isEmpty) ...[
- _progressRow(gc, ex.id),
- _switchRow(
- gc,
- PhosphorIconsRegular.fire,
- t.autoWarmup,
- t.autoWarmupHint,
- fit.warmsUp(ex.id),
- () => fit.toggleAutoWarmup(ex.id),
- ),
- ],
- ]),
- const SizedBox(height: 20),
- const StopwatchCard(),
+ _addToRoutineRow(context, gc, ex),
const SizedBox(height: 20),
if (pr != null) ...[
Container(
@@ -300,6 +279,36 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {
if (i < steps.length - 1) const SizedBox(height: 14),
],
],
+ const SizedBox(height: 28),
+ _section(gc, t.exerciseSettings),
+ const SizedBox(height: 12),
+ _group(gc, [
+ _modeRow(context, gc, ex.id, mode),
+ if (mode != 'cardio') _repsOnlyRow(gc, ex.id, repsOnly),
+ _restRow(gc, ex.id),
+ if (ex.equipment == 'Barbell' || ex.equipment == 'Machine') _barRow(gc, ex),
+ _switchRow(
+ gc,
+ PhosphorIconsRegular.sparkle,
+ t.suggestInWorkouts,
+ t.suggestInWorkoutsHint,
+ fit.suggests(ex.id),
+ () => fit.toggleSuggest(ex.id),
+ ),
+ if (!repsOnly && mode.isEmpty) ...[
+ _progressRow(gc, ex.id),
+ _switchRow(
+ gc,
+ PhosphorIconsRegular.fire,
+ t.autoWarmup,
+ t.autoWarmupHint,
+ fit.warmsUp(ex.id),
+ () => fit.toggleAutoWarmup(ex.id),
+ ),
+ ],
+ ]),
+ const SizedBox(height: 20),
+ const StopwatchCard(),
if (fit.alternativesHere(ex, 3).isNotEmpty) ...[
const SizedBox(height: 24),
_notHere(gc, ex),
@@ -478,6 +487,104 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {
);
}
+ Widget _addToRoutineRow(BuildContext context, GymColors gc, Exercise ex) {
+ final n = fit.routinesWith(ex.id);
+ return Semantics(
+ button: true,
+ child: Pressable(
+ onTap: () => _pickRoutine(context, ex),
+ scale: 0.98,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ children: [
+ _rowIcon(gc, PhosphorIconsRegular.listPlus, n > 0),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(t.addToRoutine, style: AppTheme.f(14.5, weight: FontWeight.w500, color: gc.text)),
+ const SizedBox(height: 3),
+ Text(t.inRoutines(n),
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textSecondary)),
+ ],
+ ),
+ ),
+ Icon(PhosphorIconsRegular.plus, size: 16, color: gc.textTertiary),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ void _pickRoutine(BuildContext context, Exercise ex) {
+ final gc = context.gc;
+ final routines = [
+ for (final group in fit.routineGroups) ...fit.routinesInGroup(group),
+ ...fit.routinesInGroup(''),
+ ];
+ void pick(BuildContext sheet, String? id) {
+ Navigator.pop(sheet);
+ fit.addToRoutineAndEdit(id, ex.id);
+ }
+
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (sheet) => Container(
+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.72),
+ padding: sheetPad(sheet),
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 16),
+ SheetTitle(titleCase(t.addToRoutine)),
+ const SizedBox(height: 4),
+ Text(exerciseName(ex),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.center,
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary)),
+ const SizedBox(height: 14),
+ Flexible(
+ child: OptionGroup(
+ scroll: true,
+ [
+ OptionItem(
+ t.newRoutineName,
+ icon: PhosphorIconsRegular.plus,
+ onTap: () => pick(sheet, null),
+ ),
+ for (final r in routines)
+ OptionItem(
+ fit.routineTitle(r),
+ detail: fit.routineHas(r.id, ex.id)
+ ? t.alreadyInRoutine
+ : (r.group.isEmpty ? null : r.group),
+ selected: fit.routineHas(r.id, ex.id),
+ onTap: () => pick(sheet, r.id),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
Widget _similarRow(GymColors gc, Exercise s) {
return GestureDetector(
onTap: () => fit.openExercise(s.id),
@@ -669,7 +776,7 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {
),
const SizedBox(width: 12),
StepperControl(
- value: seconds == 0 ? t.restOff : '${seconds}s',
+ value: seconds == 0 ? t.restOff : clockLabel(seconds),
minWidth: 44,
btnSize: 30,
gap: 3,
diff --git a/lib/screens/routine_edit_screen.dart b/lib/screens/routine_edit_screen.dart
index 1405052..98ab60e 100644
--- a/lib/screens/routine_edit_screen.dart
+++ b/lib/screens/routine_edit_screen.dart
@@ -114,7 +114,7 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {
height: 56,
alignment: Alignment.center,
decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(100)),
- child: Text(t.save, style: AppTheme.f(15.5, weight: FontWeight.w700, color: gc.text)),
+ child: Text(titleCase(t.save), style: AppTheme.f(15.5, weight: FontWeight.w700, color: gc.text)),
),
),
),
@@ -271,15 +271,7 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {
)
else ...[
Text(t.setsPlannedHint, style: AppTheme.f(11, weight: FontWeight.w500, color: gc.textTertiary)),
- const SizedBox(height: 6),
- if (routine.exerciseIds.length > 1) ...[
- Text(t.supersetHint, style: AppTheme.f(11, weight: FontWeight.w500, color: gc.textTertiary)),
- const SizedBox(height: 6),
- ],
- if (routine.exerciseIds.length > 1) ...[
- Text(t.dragToReorder, style: AppTheme.f(11, weight: FontWeight.w500, color: gc.textTertiary)),
- const SizedBox(height: 8),
- ],
+ const SizedBox(height: 8),
ReorderableListView(
shrinkWrap: true,
buildDefaultDragHandles: false,
@@ -601,15 +593,19 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {
style: AppTheme.f(9.5, weight: FontWeight.w700, color: gc.brass, letterSpacing: 1)),
],
const SizedBox(height: 2),
- StepperControl(
- value: t.setCount(fit.routineSets(routine, ex.id)),
- minWidth: 62,
- btnSize: 24,
- gap: 8,
- fontSize: 12,
- btnRadius: 7,
- onDec: () => fit.bumpRoutineSets(_id, ex.id, -1),
- onInc: () => fit.bumpRoutineSets(_id, ex.id, 1),
+ FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: AlignmentDirectional.centerStart,
+ child: StepperControl(
+ value: t.setCount(fit.routineSets(routine, ex.id)),
+ minWidth: 62,
+ btnSize: 24,
+ gap: 8,
+ fontSize: 12,
+ btnRadius: 7,
+ onDec: () => fit.bumpRoutineSets(_id, ex.id, -1),
+ onInc: () => fit.bumpRoutineSets(_id, ex.id, 1),
+ ),
),
if (plan.isNotEmpty) ...[
const SizedBox(height: 3),
@@ -628,7 +624,13 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {
label: t.supersetLink,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
- onTap: () => fit.toggleChain(_id, ex.id),
+ onTap: () {
+ fit.toggleChain(_id, ex.id);
+ if (!routine.chained.contains(ex.id)) return;
+ HapticFeedback.selectionClick();
+ showNotchToast(context, t.superset,
+ subtitle: t.supersetHint, icon: PhosphorIconsFill.link, accent: gc.brass);
+ },
child: SizedBox(
width: 38,
height: 44,
@@ -787,6 +789,8 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {
),
),
const SizedBox(height: 10),
+ _restRow(sheet, gc, routine, ex),
+ const SizedBox(height: 14),
PrimaryButton(label: t.done, onTap: () => Navigator.of(sheet).pop()),
],
),
@@ -797,6 +801,59 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {
);
}
+ Widget _restRow(BuildContext sheet, GymColors gc, Routine routine, Exercise ex) {
+ final own = fit.routineRest(routine.id, ex.id);
+ final seconds = own ?? fit.restFor(ex.id);
+ String label(int s) => s == 0 ? t.restOff : clockLabel(s);
+ return Container(
+ padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(18)),
+ child: Row(children: [
+ Icon(PhosphorIconsRegular.timer, size: 19, color: own != null ? gc.text : gc.textSecondary),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(titleCase(t.restInRoutine), style: AppTheme.f(14, weight: FontWeight.w600, color: gc.text)),
+ const SizedBox(height: 3),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: own != null ? () => fit.setRoutineRest(routine.id, ex.id, null) : null,
+ child: Text(own != null ? t.restInRoutineReset : t.restInRoutineHint,
+ style: AppTheme.f(11.5,
+ weight: FontWeight.w500, color: own != null ? gc.accent : gc.textSecondary, height: 1.3)),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 10),
+ StepperControl(
+ value: label(seconds),
+ minWidth: 48,
+ btnSize: 30,
+ gap: 3,
+ fontSize: 14,
+ btnRadius: 10,
+ onDec: () => fit.setRoutineRest(routine.id, ex.id, seconds - 15),
+ onInc: () => fit.setRoutineRest(routine.id, ex.id, seconds + 15),
+ onEdit: () async {
+ final v = await askRuler(sheet,
+ title: t.restInRoutine,
+ value: seconds.toDouble(),
+ min: 0,
+ max: 600,
+ step: 5,
+ majorEvery: 6,
+ format: (v) => clockLabel(v.round()),
+ tickLabel: (v) => clockLabel(v.round()));
+ if (v != null) fit.setRoutineRest(routine.id, ex.id, v.round());
+ },
+ ),
+ ]),
+ );
+ }
+
Widget _planHeader(GymColors gc, String mode, bool repsOnly) {
final labels = switch (mode) {
'cardio' => [t.distanceCol(fit.distanceUnit.toUpperCase()), t.timeCol],
diff --git a/lib/screens/session_screen.dart b/lib/screens/session_screen.dart
index 406335e..30a9b5a 100644
--- a/lib/screens/session_screen.dart
+++ b/lib/screens/session_screen.dart
@@ -200,11 +200,13 @@ class SessionScreen extends StatelessWidget {
locked,
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
if (ex != null && s.exercises.length > 1) ...[
- _textAction(gc, t.dropExerciseAction,
- () => _confirmDrop(context, exIdx, t.catalogName(ex.id, ex.name))),
+ Flexible(
+ child: _textAction(gc, t.dropExerciseAction,
+ () => _confirmDrop(context, exIdx, t.catalogName(ex.id, ex.name))),
+ ),
Container(width: 1, height: 12, color: gc.border),
],
- _textAction(gc, t.finishSession, fit.finishSession),
+ Flexible(child: _textAction(gc, titleCase(t.finishSession), fit.finishSession)),
]),
),
],
@@ -243,12 +245,37 @@ class SessionScreen extends StatelessWidget {
Text(ex == null ? '' : t.catalogName(ex.id, ex.name),
style: AppTheme.f(26, weight: FontWeight.w700, color: gc.text)),
const SizedBox(height: 8),
- Container(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
- decoration: BoxDecoration(color: gc.emberSoft, borderRadius: BorderRadius.circular(100)),
- child: Text(muscleLabel(ex?.primary ?? ''),
- style: AppTheme.f(12, weight: FontWeight.w600, color: gc.ember)),
- ),
+ Row(children: [
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(color: gc.emberSoft, borderRadius: BorderRadius.circular(100)),
+ child: Text(muscleLabel(ex?.primary ?? ''),
+ style: AppTheme.f(12, weight: FontWeight.w600, color: gc.ember)),
+ ),
+ if (ex != null && !fit.sessionPaused && fit.session?.manual != true) ...[
+ const SizedBox(width: 8),
+ Semantics(
+ button: true,
+ label: t.swapExercise,
+ child: Pressable(
+ scale: 0.94,
+ onTap: () => showSwapExerciseSheet(context, fit.session!.currentIndex),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(100),
+ border: Border.all(color: gc.border),
+ ),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(PhosphorIconsRegular.arrowsLeftRight, size: 12, color: gc.textSecondary),
+ const SizedBox(width: 5),
+ Text(t.swapShort, style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary)),
+ ]),
+ ),
+ ),
+ ),
+ ],
+ ]),
if (ex != null && fit.lastSummaryFor(ex.id) != null) ...[
const SizedBox(height: 10),
GestureDetector(
@@ -383,19 +410,33 @@ class SessionScreen extends StatelessWidget {
style: AppTheme.f(11, weight: FontWeight.w600, color: gc.brass, letterSpacing: 0.4)),
const SizedBox(width: 8),
Expanded(
- child: RichText(
- text: TextSpan(
+ child: LayoutBuilder(builder: (context, box) {
+ final main = TextSpan(
text: fit.nextTargetLabel(id),
style: AppTheme.f(12,
weight: FontWeight.w600, color: target.up ? gc.ember : gc.textSecondary),
+ );
+ if (target.up) return Text.rich(main);
+ final holdStyle = AppTheme.f(11.5, weight: FontWeight.w400, color: gc.textTertiary);
+ final both = TextSpan(children: [main, TextSpan(text: ' · ${t.nextHold}', style: holdStyle)]);
+ final painter = TextPainter(
+ text: both,
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ maxLines: 1,
+ )..layout(maxWidth: box.maxWidth);
+ final fits = !painter.didExceedMaxLines;
+ painter.dispose();
+ if (fits) return Text.rich(both);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if (!target.up)
- TextSpan(
- text: ' · ${t.nextHold}',
- style: AppTheme.f(11.5, weight: FontWeight.w400, color: gc.textTertiary)),
+ Text.rich(main),
+ const SizedBox(height: 2),
+ Text(t.nextHold, style: holdStyle),
],
- ),
- ),
+ );
+ }),
),
],
),
@@ -452,24 +493,30 @@ class SessionScreen extends StatelessWidget {
if (locked)
Flexible(child: _lockedChip(gc))
else
- Row(children: [
- _stepOutButton(gc),
- const SizedBox(width: 10),
- Container(
- width: 8,
- height: 8,
- decoration: BoxDecoration(
- color: fit.sessionPaused ? gc.textTertiary : gc.ember, shape: BoxShape.circle),
- ),
- const SizedBox(width: 8),
- Text(
- fit.sessionPaused ? t.paused : t.inProgress,
- style: AppTheme.f(12,
- weight: FontWeight.w600,
- color: fit.sessionPaused ? gc.textTertiary : gc.ember,
- letterSpacing: 0.4),
- ),
- ]),
+ Flexible(
+ child: Row(children: [
+ _stepOutButton(gc),
+ const SizedBox(width: 10),
+ Container(
+ width: 8,
+ height: 8,
+ decoration: BoxDecoration(
+ color: fit.sessionPaused ? gc.textTertiary : gc.ember, shape: BoxShape.circle),
+ ),
+ const SizedBox(width: 8),
+ Flexible(
+ child: Text(
+ fit.sessionPaused ? t.paused : t.inProgress,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(12,
+ weight: FontWeight.w600,
+ color: fit.sessionPaused ? gc.textTertiary : gc.ember,
+ letterSpacing: 0.4),
+ ),
+ ),
+ ]),
+ ),
Row(children: [
_ticking(() => RollingText(fit.elapsedLabel,
style: AppTheme.f(18,
@@ -1164,6 +1211,7 @@ class SessionScreen extends StatelessWidget {
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
child: Text(label,
+ textAlign: TextAlign.center,
style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textTertiary)),
),
),
@@ -1651,6 +1699,136 @@ void showAddToSessionSheet(BuildContext context) {
);
}
+void showSwapExerciseSheet(BuildContext context, int exIdx) {
+ final gc = context.gc;
+ final from = fit.session?.exercises[exIdx];
+ if (from == null) return;
+ final search = TextEditingController();
+ final started = from.sets.any((st) => st.done);
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: gc.bgRaised,
+ shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(24))),
+ builder: (sheetCtx) => Padding(
+ padding: EdgeInsets.only(bottom: MediaQuery.of(sheetCtx).viewInsets.bottom),
+ child: StatefulBuilder(
+ builder: (sheetCtx, setSheet) {
+ final q = search.text.trim();
+ final list = q.isEmpty
+ ? fit.swapOptions(from.id)
+ : fit.trainSearchResults(q).where((e) => !fit.inSession(e.id)).toList();
+ void pick(Exercise ex) {
+ Navigator.pop(sheetCtx);
+ fit.swapSessionExercise(exIdx, ex.id);
+ }
+
+ return SafeArea(
+ child: ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: MediaQuery.of(sheetCtx).size.height * 0.82),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 18, 20, 0),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(titleCase(t.swapExercise),
+ style: AppTheme.f(19, weight: FontWeight.w800, color: gc.text)),
+ const SizedBox(height: 4),
+ Text(started ? t.swapKeepsDone : t.swapHint(t.catalogName(from.id, from.name)),
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),
+ const SizedBox(height: 14),
+ SearchField(
+ controller: search,
+ hint: t.searchExercises,
+ 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),
+ shrinkWrap: true,
+ children: [
+ if (list.isEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 18),
+ child: Text(t.noMatches,
+ style: AppTheme.f(13, weight: FontWeight.w500, color: gc.textSecondary)),
+ ),
+ for (final ex in list) _swapRow(sheetCtx, gc, ex, () => pick(ex)),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ );
+}
+
+Widget _swapRow(BuildContext sheetCtx, GymColors gc, Exercise ex, VoidCallback onTap) {
+ final away = !fit.fitsHere(ex);
+ final detail = [
+ t.equipment(ex.equipment),
+ if (fit.lastSetsFor(ex.id).isNotEmpty) t.swapDoneBefore,
+ ].join(' · ');
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 10),
+ child: Pressable(
+ scale: 0.98,
+ onTap: onTap,
+ onLongPress: () => showExercisePreview(sheetCtx, ex),
+ child: Opacity(
+ opacity: away ? 0.55 : 1,
+ child: Container(
+ padding: const EdgeInsets.all(10),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(14)),
+ child: Row(children: [
+ GestureDetector(
+ onTap: () => showExercisePreview(sheetCtx, ex),
+ child: SizedBox(width: 44, child: ExerciseMedia(ex: ex, height: 44, radius: 10)),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(exerciseName(ex),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(13.5, weight: FontWeight.w600, color: gc.text)),
+ const SizedBox(height: 2),
+ Text(detail,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(11, weight: FontWeight.w500, color: gc.textSecondary)),
+ ],
+ ),
+ ),
+ if (fit.favorites[ex.id] == true) ...[
+ Icon(PhosphorIconsFill.star, size: 13, color: gc.accent),
+ const SizedBox(width: 8),
+ ],
+ Icon(PhosphorIconsRegular.arrowsLeftRight, size: 15, color: gc.textSecondary),
+ ]),
+ ),
+ ),
+ ),
+ );
+}
+
Widget _addRow(BuildContext sheetCtx, GymColors gc, Exercise ex) {
final already = fit.inSession(ex.id);
return Padding(
@@ -1735,8 +1913,7 @@ class _ExerciseStageState extends State<_ExerciseStage> {
subtitle: where,
icon: fit.inSuperset ? PhosphorIconsBold.link : PhosphorIconsBold.arrowRight,
accent: fit.inSuperset ? gc.brass : gc.ember,
- duration: const Duration(milliseconds: 1900),
- sound: false);
+ duration: const Duration(milliseconds: 1900));
}
@override
@@ -1983,7 +2160,6 @@ void _showLockHint(BuildContext context) {
subtitle: t.lockedHint,
icon: PhosphorIconsFill.fingerprint,
accent: context.gc.accent,
- sound: false,
);
}
diff --git a/lib/state/fit_state.dart b/lib/state/fit_state.dart
index e1d1974..9483dcb 100644
--- a/lib/state/fit_state.dart
+++ b/lib/state/fit_state.dart
@@ -197,6 +197,8 @@ class FitState extends FitCore
showFocus = data['showFocus'] as bool? ?? true;
showRecommended = data['showRecs'] as bool? ?? true;
levelHints = data['levelHints'] as bool? ?? true;
+ toastSound = data['toastSound'] as bool? ?? true;
+ Beeper.instance.chimeOn = toastSound;
heatmapLabels = data['heatLabels'] as bool? ?? true;
multiPlan = data['multiPlan'] as bool? ?? false;
final weekStart = data['weekStart'];
@@ -267,7 +269,7 @@ class FitState extends FitCore
exerciseRest.clear();
((data['exRest'] as Map?) ?? const {}).forEach((k, v) {
final n = (v as num?)?.toInt();
- if (k is String && n != null) exerciseRest[k] = n.clamp(15, 600);
+ if (k is String && n != null) exerciseRest[k] = n <= 0 ? 0 : n.clamp(15, 600);
});
}
@@ -368,6 +370,7 @@ class FitState extends FitCore
'showFocus': showFocus,
'showRecs': showRecommended,
'levelHints': levelHints,
+ 'toastSound': toastSound,
'heatLabels': heatmapLabels,
'weekStart': weekStartDay,
'autoAdvance': autoAdvance,
@@ -479,6 +482,8 @@ class FitState extends FitCore
showFocus = true;
showRecommended = true;
levelHints = true;
+ toastSound = true;
+ Beeper.instance.chimeOn = true;
heatmapLabels = true;
weekStartDay = DateTime.monday;
autoAdvance = true;
@@ -528,6 +533,7 @@ class FitState extends FitCore
_applyLanguage(map['language'] as String? ?? language);
restSeconds = (map['rest'] as num?)?.toInt() ?? restSeconds;
bgPattern = map['bg'] as String? ?? bgPattern;
+ heatTone = map['heatTone'] as String? ?? heatTone;
_loadToggles(map);
onboarded = map['onboarded'] as bool? ?? onboarded;
favorites
@@ -572,6 +578,8 @@ class FitState extends FitCore
_seedCalculatorsFromProfile();
_loading = false;
_persist();
+ syncTrainReminder();
+ syncPhotoReminder();
_refreshWidgets();
notifyListeners();
}
@@ -809,7 +817,7 @@ class FitState extends FitCore
}
if (item.superset) toggleChain(id, ex.id);
final rest = item.restSec;
- if (rest != null && !hasCustomRest(ex.id)) setExerciseRest(ex.id, rest);
+ if (rest != null) setRoutineRest(id, ex.id, rest);
}
made++;
added += picked.length;
@@ -882,7 +890,7 @@ class FitState extends FitCore
},
],
if (chainsToNext(r, id)) 'superset': true,
- if (hasCustomRest(id)) 'rest': restFor(id),
+ 'rest': ?(routineRest(r.id, id) ?? (hasCustomRest(id) ? restFor(id) : null)),
if (isCustom(id))
'custom': {
'muscle': ex.primary,
diff --git a/lib/state/routines_state.dart b/lib/state/routines_state.dart
index 9f83450..8e1f4c9 100644
--- a/lib/state/routines_state.dart
+++ b/lib/state/routines_state.dart
@@ -5,6 +5,7 @@ const int kDefaultRoutineSets = 3;
mixin RoutinesState on FitCore, LibraryState {
String? activeRoutineId;
int _routineSeq = 0;
+ bool _editFromExercise = false;
void goRoutines() => pushRoute('routines');
@@ -135,6 +136,7 @@ mixin RoutinesState on FitCore, LibraryState {
made.sets.addAll(source.sets);
made.chained.addAll(source.chained);
made.plan.addAll({for (final e in source.plan.entries) e.key: [...e.value]});
+ made.rest.addAll(source.rest);
made.group = source.group;
made.color = source.color;
_persist();
@@ -187,6 +189,7 @@ mixin RoutinesState on FitCore, LibraryState {
if (r.exerciseIds.remove(exId)) {
r.sets.remove(exId);
r.plan.remove(exId);
+ r.rest.remove(exId);
r.chained.remove(exId);
} else {
r.exerciseIds.add(exId);
@@ -205,6 +208,8 @@ mixin RoutinesState on FitCore, LibraryState {
if (sets != null) r.sets[to] = sets;
final plan = r.plan.remove(from);
if (plan != null) r.plan[to] = [for (final p in plan) PlannedSet(kind: p.kind)];
+ final rest = r.rest.remove(from);
+ if (rest != null) r.rest[to] = rest;
if (r.chained.remove(from)) r.chained.add(to);
_persist();
notifyListeners();
@@ -217,6 +222,7 @@ mixin RoutinesState on FitCore, LibraryState {
if (at < 0) return null;
final sets = r.sets[exId];
final plan = r.plan[exId];
+ final rest = r.rest[exId];
final chained = r.chained.contains(exId);
toggleRoutineExercise(routineId, exId);
return () {
@@ -225,6 +231,7 @@ mixin RoutinesState on FitCore, LibraryState {
back.exerciseIds.insert(at.clamp(0, back.exerciseIds.length), exId);
if (sets != null) back.sets[exId] = sets;
if (plan != null) back.plan[exId] = plan;
+ if (rest != null) back.rest[exId] = rest;
if (chained) back.chained.add(exId);
_persist();
notifyListeners();
@@ -242,6 +249,21 @@ mixin RoutinesState on FitCore, LibraryState {
List<PlannedSet> plannedSets(Routine r, String exId) => r.plan[exId] ?? const [];
+ int? routineRest(String? routineId, String exId) =>
+ routineId == null ? null : _routine(routineId)?.rest[exId];
+
+ void setRoutineRest(String routineId, String exId, int? seconds) {
+ final r = _routine(routineId);
+ if (r == null || !r.exerciseIds.contains(exId)) return;
+ if (seconds == null) {
+ r.rest.remove(exId);
+ } else {
+ r.rest[exId] = seconds <= 0 ? 0 : seconds.clamp(15, 600);
+ }
+ _persist();
+ notifyListeners();
+ }
+
void setRoutineSetCount(String routineId, String exId, int n) {
final r = _routine(routineId);
if (r == null || !r.exerciseIds.contains(exId)) return;
@@ -329,14 +351,29 @@ mixin RoutinesState on FitCore, LibraryState {
}
void openRoutine(String id) {
+ if (route != 'routine-edit') _editFromExercise = false;
activeRoutineId = id;
route = 'routine-edit';
notifyListeners();
}
+ void addToRoutineAndEdit(String? routineId, String exId) {
+ final id = routineId ?? createRoutine();
+ if (!routineHas(id, exId)) toggleRoutineExercise(id, exId);
+ activeRoutineId = id;
+ _editFromExercise = true;
+ pushRoute('routine-edit');
+ }
+
+ int routinesWith(String exId) => routines.where((r) => r.exerciseIds.contains(exId)).length;
+
String routineTitle(Routine r) => r.name.isEmpty ? t.newRoutineName : r.name;
void closeRoutineEdit() {
+ if (_editFromExercise) {
+ _editFromExercise = false;
+ return popRoute(fallback: 'routines');
+ }
route = 'routines';
notifyListeners();
}
diff --git a/lib/state/workout_state.dart b/lib/state/workout_state.dart
index 50a9c08..589462f 100644
--- a/lib/state/workout_state.dart
+++ b/lib/state/workout_state.dart
@@ -616,9 +616,10 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt
if (sessionPaused || session?.manual == true) return;
_restTimer?.cancel();
RestAlarm.instance.stopSound();
- final seconds = restFor(session!.exercises.isEmpty
+ final exId = session!.exercises.isEmpty
? ''
- : session!.exercises[session!.currentIndex.clamp(0, session!.exercises.length - 1)].id);
+ : session!.exercises[session!.currentIndex.clamp(0, session!.exercises.length - 1)].id;
+ final seconds = routineRest(session!.routineId, exId) ?? restFor(exId);
if (seconds <= 0) {
session!.clearRest();
notifyListeners();
@@ -1044,6 +1045,55 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt
notifyListeners();
}
+ List<Exercise> swapOptions(String exId, {int n = 15}) {
+ final from = exerciseById(exId);
+ if (from == null) return const [];
+ final cardio = modeOf(exId) == 'cardio';
+ final pool = allExercises
+ .where((e) =>
+ e.id != exId &&
+ e.primary == from.primary &&
+ !inSession(e.id) &&
+ !isArchived(e.id) &&
+ (modeOf(e.id) == 'cardio') == cardio)
+ .toList();
+ final shared = from.secondary.toSet();
+ int score(Exercise e) =>
+ (fitsHere(e) ? 8 : 0) +
+ (favorites[e.id] == true ? 4 : 0) +
+ (lastSetsFor(e.id).isNotEmpty ? 3 : 0) +
+ (e.secondary.where(shared.contains).isNotEmpty ? 1 : 0);
+ final ranked = [
+ for (var i = 0; i < pool.length; i++) (ex: pool[i], score: score(pool[i]), seat: i),
+ ]..sort((a, b) => a.score == b.score ? a.seat.compareTo(b.seat) : b.score.compareTo(a.score));
+ return [for (final r in ranked.take(n)) r.ex];
+ }
+
+ void swapSessionExercise(int exIdx, String toId) {
+ final s = session;
+ final to = exerciseById(toId);
+ if (s == null || to == null || exIdx < 0 || exIdx >= s.exercises.length || inSession(toId)) return;
+ final from = s.exercises[exIdx];
+ final left = from.sets.where((st) => !st.done && st.counts).length;
+ final started = from.sets.any((st) => st.done);
+ final count = left > 0 ? left : null;
+ final next = SessionExercise(to.id, to.name, to.primary,
+ started ? _workingOpeners(toId, count: count) : _openingSets(toId, count: count),
+ linkedNext: from.linkedNext,
+ swappedFrom: from.swappedFrom ?? from.id);
+ if (started) {
+ from.sets.removeWhere((st) => !st.done);
+ from.linkedNext = false;
+ s.exercises.insert(exIdx + 1, next);
+ s.currentIndex = exIdx + 1;
+ } else {
+ s.exercises[exIdx] = next;
+ s.currentIndex = exIdx;
+ }
+ persistNow();
+ notifyListeners();
+ }
+
List<Exercise> sessionSuggestions() {
final inSession = session?.exercises.map((e) => e.id).toSet() ?? <String>{};
final ids = <String>[];
@@ -1134,6 +1184,22 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt
List<SessionExercise> get _savable =>
[for (final e in session?.exercises ?? const <SessionExercise>[]) if (exerciseById(e.id) != null) e];
+ Map<String, String> get _swaps {
+ final r = sessionRoutine;
+ if (r == null) return const {};
+ final 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;
+ }
+ return out;
+ }
+
+ List<SessionExercise> get _savableForRoutine {
+ final swaps = _swaps;
+ return [for (final e in _savable) if (!swaps.containsKey(e.id)) e];
+ }
+
void _planFromSession(String routineId, SessionExercise ex) {
if (ex.sets.isEmpty) return;
setPlannedSets(routineId, ex.id, [
@@ -1156,13 +1222,13 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt
bool get sessionEditedRoutine {
final r = sessionRoutine;
return r != null &&
- _savable.map((e) => e.id).join('|') != routineExercises(r).map((e) => e.id).join('|');
+ _savableForRoutine.map((e) => e.id).join('|') != routineExercises(r).map((e) => e.id).join('|');
}
({List<Exercise> added, List<Exercise> removed, bool reordered}) get sessionRoutineChanges {
final r = sessionRoutine;
final before = r == null ? const <Exercise>[] : routineExercises(r);
- final after = [for (final e in _savable) exerciseById(e.id)!];
+ final after = [for (final e in _savableForRoutine) exerciseById(e.id)!];
final was = {for (final e in before) e.id};
final now = {for (final e in after) e.id};
return (
@@ -1190,7 +1256,11 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt
void saveSessionIntoRoutine() {
final r = sessionRoutine;
if (r == null) return;
- final exs = _savable;
+ final swaps = _swaps;
+ final exs = [for (final e in _savable) if (!swaps.containsKey(e.id)) e];
+ 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);
diff --git a/test/backup_complete_test.dart b/test/backup_complete_test.dart
index d5aa725..d4fb495 100644
--- a/test/backup_complete_test.dart
+++ b/test/backup_complete_test.dart
@@ -272,4 +272,53 @@ void main() {
expect(place.bar, 15);
expect(fit.activePlaceId, place.id);
});
+
+ test('vuelve también lo de la 1.4 y el descanso a cero no se pierde al reabrir', () async {
+ await seedTwoYears();
+ final routine = fit.routines.single;
+ fit.setRoutineRest(routine.id, bench.id, 75);
+ fit.setExerciseRest(squat.id, 0);
+ fit.setHeatTone('green');
+ fit.setAlarmStyle('vibrate');
+ fit.setEffortMode('rir');
+ fit.setWeekStart(DateTime.sunday);
+ fit.setDemoSize('small');
+ fit.toggleArchived(pushUp.id);
+ fit.setExerciseMode(squat.id, 'time');
+ fit.setExerciseBar(bench.id, 15);
+ fit.setExerciseGoal(bench.id, 120, DateTime(2027, 1, 1));
+ fit.toggleMultiPlan();
+ final custom = fit.customExercises.single;
+ fit.updateCustomExercise(custom.id,
+ name: custom.name,
+ primary: custom.primary,
+ equipment: custom.equipment,
+ difficulty: custom.difficulty,
+ steps: const [],
+ mode: '',
+ aliases: const ['Bulgarian split squat']);
+
+ final zip = await buildBackupZip();
+ fit.resetAllData();
+ expect(await restoreBackupZip(zip), isTrue);
+
+ expect(fit.routineRest(fit.routines.single.id, bench.id), 75);
+ expect(fit.restFor(squat.id), 0);
+ expect(fit.heatTone, 'green');
+ expect(fit.alarmStyle, 'vibrate');
+ expect(fit.usesRir, isTrue);
+ expect(fit.weekStartDay, DateTime.sunday);
+ expect(fit.demoSize, 'small');
+ expect(fit.isArchived(pushUp.id), isTrue);
+ expect(fit.modeOf(squat.id), 'time');
+ expect(fit.hasOwnBar(bench.id), isTrue);
+ expect(fit.exerciseGoals[bench.id]?.target, 120);
+ expect(fit.multiPlan, isTrue);
+ expect(fit.customExercises.single.aliases, ['Bulgarian split squat']);
+
+ fit.persistNow();
+ fit.loadFromStore();
+ expect(fit.restFor(squat.id), 0);
+ expect(fit.heatTone, 'green');
+ });
}
diff --git a/test/routine_rest_test.dart b/test/routine_rest_test.dart
new file mode 100644
index 0000000..6fdf9d2
--- /dev/null
+++ b/test/routine_rest_test.dart
@@ -0,0 +1,63 @@
+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();
+
+ late String ex;
+ late String r;
+
+ setUp(() async {
+ SharedPreferences.setMockInitialValues({});
+ await Store.instance.init();
+ fit.resetAllData();
+ ex = fit.allExercises.firstWhere((e) => fit.modeOf(e.id).isEmpty).id;
+ r = fit.createRoutine('Fuerza');
+ fit.toggleRoutineExercise(r, ex);
+ });
+
+ test('sin ajuste usa el del ejercicio, y con ajuste manda la rutina', () {
+ fit.setExerciseRest(ex, 90);
+ expect(fit.routineRest(r, ex), isNull);
+ fit.setRoutineRest(r, ex, 180);
+ expect(fit.routineRest(r, ex), 180);
+ expect(fit.restFor(ex), 90);
+ fit.setRoutineRest(r, ex, null);
+ expect(fit.routineRest(r, ex), isNull);
+ });
+
+ test('el descanso arranca con el de la rutina del entreno', () {
+ fit.setRestSeconds(90);
+ fit.setRoutineRest(r, ex, 240);
+ fit.startRoutine(fit.routines.single);
+ fit.startRest();
+ expect(fit.restTotal, 240);
+ });
+
+ test('se guarda en la copia y las copias viejas cargan sin él', () {
+ fit.setRoutineRest(r, ex, 150);
+ final back = Routine.fromJson(fit.routines.single.toJson());
+ expect(back.rest[ex], 150);
+ expect(Routine.fromJson({'id': 'x', 'n': 'Old', 'ex': [ex]}).rest, isEmpty);
+ });
+
+ test('viaja al duplicar, se va al quitar y vuelve al deshacer', () {
+ fit.setRoutineRest(r, ex, 120);
+ final copy = fit.duplicateRoutine(r);
+ expect(fit.routineRest(copy, ex), 120);
+ final undo = fit.removeRoutineExercise(r, ex)!;
+ expect(fit.routineRest(r, ex), isNull);
+ undo();
+ expect(fit.routineRest(r, ex), 120);
+ });
+
+ test('apagado en la rutina es cero y no se recorta a 15', () {
+ fit.setRoutineRest(r, ex, 0);
+ expect(fit.routineRest(r, ex), 0);
+ fit.setRoutineRest(r, ex, 5);
+ expect(fit.routineRest(r, ex), 15);
+ });
+}
diff --git a/test/swap_exercise_test.dart b/test/swap_exercise_test.dart
new file mode 100644
index 0000000..093570c
--- /dev/null
+++ b/test/swap_exercise_test.dart
@@ -0,0 +1,93 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:gymmane/models/live_session.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();
+
+ late String bench;
+ late String other;
+ late String legs;
+ late String r;
+
+ setUp(() async {
+ SharedPreferences.setMockInitialValues({});
+ await Store.instance.init();
+ fit.resetAllData();
+ bench = 'EIeI8Vf';
+ legs = fit.allExercises.firstWhere((e) => e.primary == 'quads' && fit.modeOf(e.id).isEmpty).id;
+ r = fit.createRoutine('Torso');
+ fit.toggleRoutineExercise(r, bench);
+ fit.toggleRoutineExercise(r, legs);
+ other = fit.swapOptions(bench).first.id;
+ });
+
+ tearDown(fit.saveAndExit);
+
+ test('las opciones son del mismo músculo y no repiten lo que ya está en el entreno', () {
+ fit.startRoutine(fit.routines.single);
+ final options = fit.swapOptions(bench);
+ final primary = fit.exerciseById(bench)!.primary;
+ expect(options, isNotEmpty);
+ expect(options.every((e) => e.primary == primary), isTrue);
+ expect(options.map((e) => e.id), isNot(contains(bench)));
+ });
+
+ test('los favoritos y los ya hechos salen antes', () {
+ final pool = fit.swapOptions(bench, n: 100);
+ final fav = pool.last.id;
+ fit.toggleFavorite(fav);
+ expect(fit.swapOptions(bench).first.id, fav);
+ });
+
+ test('sin series hechas lo sustituye en su sitio', () {
+ fit.startRoutine(fit.routines.single);
+ fit.swapSessionExercise(0, other);
+ final s = fit.session!;
+ expect(s.exercises.map((e) => e.id), [other, legs]);
+ expect(s.exercises.first.swappedFrom, bench);
+ expect(s.currentIndex, 0);
+ });
+
+ test('con series hechas, las hechas se quedan y el nuevo sigue con las que faltan', () {
+ fit.startRoutine(fit.routines.single);
+ final s = fit.session!;
+ final working = s.exercises.first.sets.where((st) => st.counts).length;
+ final firstWorking = s.exercises.first.sets.indexWhere((st) => st.counts);
+ fit.toggleSet(0, firstWorking);
+ fit.swapSessionExercise(0, other);
+ expect(s.exercises.map((e) => e.id), [bench, other, legs]);
+ expect(s.exercises.first.sets.every((st) => st.done), isTrue);
+ expect(s.exercises[1].sets.length, working - 1);
+ expect(s.exercises[1].sets.any((st) => !st.counts), isFalse);
+ expect(s.currentIndex, 1);
+ });
+
+ test('guardar en la rutina pone el nuevo en el sitio del viejo', () {
+ fit.startRoutine(fit.routines.single);
+ fit.swapSessionExercise(0, other);
+ expect(fit.sessionEditedRoutine, isTrue);
+ final changes = fit.sessionRoutineChanges;
+ expect(changes.added.map((e) => e.id), [other]);
+ expect(changes.removed.map((e) => e.id), [bench]);
+ fit.saveSessionIntoRoutine();
+ expect(fit.routines.single.exerciseIds, [other, legs]);
+ });
+
+ test('también si ya había series hechas del viejo', () {
+ fit.startRoutine(fit.routines.single);
+ fit.toggleSet(0, fit.session!.exercises.first.sets.indexWhere((st) => st.counts));
+ fit.swapSessionExercise(0, other);
+ fit.saveSessionIntoRoutine();
+ expect(fit.routines.single.exerciseIds, [other, legs]);
+ });
+
+ test('el cambio sobrevive a cerrar la app a mitad', () {
+ fit.startRoutine(fit.routines.single);
+ fit.swapSessionExercise(0, other);
+ final back = SessionExercise.fromJson(fit.session!.exercises.first.toJson());
+ expect(back.swappedFrom, bench);
+ });
+}