Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Rework the live workout: timed sets, an RPE column, carry-over and auto finish
InlitXe25ae2dd15d9
diff --git a/lib/models/workout.dart b/lib/models/workout.dartindex ea5610c..f8c1a7f 100644--- a/lib/models/workout.dart+++ b/lib/models/workout.dart@@ -1,33 +1,54 @@-enum SetKind { normal, warmup, drop, failure }+enum SetKind { normal, warmup, drop, failure, restPause }SetKind setKindFrom(Object? raw) {final i = (raw as num?)?.toInt() ?? 0;return SetKind.values[i.clamp(0, SetKind.values.length - 1)];}+const _rpeTable = [+ 1.0, .978, .955, .939, .922, .907, .892, .878, .863, .85, .837, .824, .811, .799, .786, .774,+ .762, .751, .739, .723, .707, .694, .68, .667, .653, .64, .626, .613, .599, .586, .574,+];++double? rpePercent(int reps, double? rpe) {+ if (rpe == null || rpe < 6 || rpe > 10 || reps < 1 || reps > 12) return null;+ final i = (reps - 1) * 2 + ((10 - rpe) * 2).round();+ return i < _rpeTable.length ? _rpeTable[i] : null;+}+class LoggedSet {- LoggedSet(this.reps, this.weight, {this.kind = SetKind.normal, this.rpe});+ LoggedSet(this.reps, this.weight, {this.kind = SetKind.normal, this.rpe, this.sec, this.km});final int reps;final double weight;final SetKind kind;final double? rpe;+ final int? sec;+ final double? km;bool get counts => kind != SetKind.warmup;double get volume => reps * weight;- double get oneRm => weight * (1 + reps / 30);+ double get oneRm {+ if (reps <= 0) return 0;+ final pct = rpePercent(reps, rpe);+ return pct == null ? weight * (1 + reps / 30) : weight / pct;+ }Map<String, dynamic> toJson() => {'r': reps,'w': weight,if (kind != SetKind.normal) 'k': kind.index,if (rpe != null) 'e': rpe,+ if (sec != null) 't': sec,+ if (km != null) 'km': km,};factory LoggedSet.fromJson(Map<String, dynamic> j) => LoggedSet((j['r'] as num).toInt(),(j['w'] as num).toDouble(),kind: setKindFrom(j['k']),rpe: (j['e'] as num?)?.toDouble(),+ sec: (j['t'] as num?)?.toInt(),+ km: (j['km'] as num?)?.toDouble(),);}@@ -96,17 +117,64 @@ class BodyweightEntry {BodyweightEntry(DateTime.parse(j['d'] as String), (j['kg'] as num).toDouble());}+class PlannedSet {+ const PlannedSet({this.reps, this.weightKg, this.kind = SetKind.normal, this.sec, this.km});+ final int? reps;+ final double? weightKg;+ final SetKind kind;+ final int? sec;+ final double? km;++ PlannedSet copyWith({+ int? reps,+ double? weightKg,+ SetKind? kind,+ int? sec,+ double? km,+ bool autoWeight = false,+ }) =>+ PlannedSet(+ reps: reps ?? this.reps,+ weightKg: autoWeight ? null : (weightKg ?? this.weightKg),+ kind: kind ?? this.kind,+ sec: sec ?? this.sec,+ km: km ?? this.km,+ );++ Map<String, dynamic> toJson() => {+ if (reps != null) 'r': reps,+ if (weightKg != null) 'w': weightKg,+ if (kind != SetKind.normal) 'k': kind.index,+ if (sec != null) 't': sec,+ if (km != null) 'km': km,+ };+ factory PlannedSet.fromJson(Map<String, dynamic> j) => PlannedSet(+ reps: (j['r'] as num?)?.toInt(),+ weightKg: (j['w'] as num?)?.toDouble(),+ kind: setKindFrom(j['k']),+ sec: (j['t'] as num?)?.toInt(),+ km: (j['km'] as num?)?.toDouble(),+ );+}+class Routine {Routine(this.id, this.name, this.exerciseIds,- {Map<String, int>? sets, Set<String>? chained, this.group = ''})+ {Map<String, int>? sets,+ Set<String>? chained,+ Map<String, List<PlannedSet>>? plan,+ this.group = '',+ this.color = -1}): sets = sets ?? {},- chained = chained ?? {};+ chained = chained ?? {},+ plan = plan ?? {};final String id;String name;String group;+ int color;final List<String> exerciseIds;final Map<String, int> sets;final Set<String> chained;+ final Map<String, List<PlannedSet>> plan;Map<String, dynamic> toJson() => {'id': id,@@ -115,6 +183,9 @@ class Routine {if (sets.isNotEmpty) 's': sets,if (chained.isNotEmpty) 'c': chained.toList(),if (group.isNotEmpty) 'g': group,+ if (color >= 0) 'k': color,+ if (plan.isNotEmpty)+ 'p': plan.map((k, v) => MapEntry(k, v.map((s) => s.toJson()).toList())),};factory Routine.fromJson(Map<String, dynamic> j) => Routine(j['id'] as String,@@ -123,6 +194,11 @@ class Routine {sets: ((j['s'] as Map?) ?? const {}).map((k, v) => MapEntry(k as String, (v as num).toInt())),chained: ((j['c'] as List?) ?? const []).cast<String>().toSet(),+ plan: ((j['p'] as Map?) ?? const {}).map((k, v) => MapEntry(+ k as String,+ (v as List).map((s) => PlannedSet.fromJson((s as Map).cast<String, dynamic>())).toList(),+ )),group: (j['g'] as String?) ?? '',+ color: (j['k'] as num?)?.toInt() ?? -1,);}diff --git a/lib/screens/session_screen.dart b/lib/screens/session_screen.dartindex 93bf9df..c1ec42d 100644--- a/lib/screens/session_screen.dart+++ b/lib/screens/session_screen.dart@@ -1,4 +1,5 @@import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';import '../l10n/l10n.dart';@@ -8,14 +9,23 @@ import '../models/workout.dart';import '../state/fit_state.dart';import '../theme/app_colors.dart';import '../theme/app_theme.dart';+import '../widgets/celebration.dart';import '../widgets/dialogs.dart';+import '../widgets/entrance.dart';import '../widgets/exercise_media.dart';+import '../widgets/glass.dart';+import '../widgets/liquid_notch.dart';+import '../widgets/set_kind.dart';import '../widgets/share_cards.dart';+import '../widgets/rolling_text.dart';+import '../widgets/ruler_picker.dart';import '../widgets/svg_icon.dart';+import '../widgets/timer_panel.dart';import '../widgets/ui_kit.dart';import 'exercises_screen.dart';import 'tool_detail_screen.dart';import 'share_sheet.dart';+import 'sticker_screen.dart';class SessionScreen extends StatelessWidget {const SessionScreen({super.key});@@ -26,6 +36,7 @@ class SessionScreen extends StatelessWidget {return SafeArea(bottom: false,child: SingleChildScrollView(+ clipBehavior: Clip.none,padding: const EdgeInsets.fromLTRB(20, 12, 20, 32),child: fit.isSessionComplete ? _complete(context, gc) : _active(context, gc),),@@ -38,135 +49,99 @@ class SessionScreen extends StatelessWidget {final exIdx = s.currentIndex;final def = fit.exerciseById(ex?.id ?? '') ?? fit.allExercises.first;final repsOnly = ex != null && fit.isRepsOnly(ex.id);+ final locked = fit.sessionLocked && !s.manual;+ final demo = ex == null ? 'off' : fit.demoSize;+ final mode = ex == null ? '' : fit.modeOf(ex.id);+ final second = _secondAction(gc, ex, exIdx, mode, repsOnly);return Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- s.manual ? _manualBar(gc, s) : _liveBar(gc),- const SizedBox(height: 18),- Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Row(children: [- Text(fit.sessionProgressLabel,- style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary, letterSpacing: 0.4)),- if (fit.inSuperset) ...[- const SizedBox(width: 8),- Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),- decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(100)),- child: Row(mainAxisSize: MainAxisSize.min, children: [- Icon(PhosphorIconsRegular.link, size: 11, color: gc.brass),- const SizedBox(width: 5),- Text(t.superset,- style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.brass, letterSpacing: 0.5)),- ]),- ),+ s.manual ? _manualBar(gc, s) : _liveBar(gc, locked),+ const SizedBox(height: 14),+ _progressStrip(context, gc, s, locked),+ const SizedBox(height: 16),+ _ExerciseStage(+ index: exIdx,+ haptic: true,+ autoMoves: fit.autoMoves,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (demo == 'small')+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(child: _exerciseHeader(context, gc, ex)),+ const SizedBox(width: 14),+ SizedBox(+ width: 104,+ child: _guard(locked, ExerciseMedia(ex: def, height: 104, radius: 18, live: true)),+ ),+ ],+ )+ else+ _exerciseHeader(context, gc, ex),+ if (demo == 'large') ...[+ const SizedBox(height: 14),+ _guard(locked, ExerciseMedia(ex: def, height: 170, live: true)),],- ]),- const SizedBox(height: 4),- 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)),- ),- if (ex != null && fit.lastSummaryFor(ex.id) != null) ...[- const SizedBox(height: 10),- Row(children: [- Text(t.last,- style: AppTheme.f(11, weight: FontWeight.w600, color: gc.textTertiary, letterSpacing: 0.4)),- const SizedBox(width: 8),- Expanded(- child: Text(fit.lastSummaryFor(ex.id)!,- style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary)),- ),- ]),- if (fit.nextTargetLabel(ex.id) != null) _nextRow(gc, ex.id),],- ],+ ),),- const SizedBox(height: 14),- if (ex != null) ExerciseMedia(ex: def, height: 170, live: true),const SizedBox(height: 18),- if (s.restRemaining != null) ...[- Container(- padding: const EdgeInsets.fromLTRB(10, 10, 12, 10),+ AnimatedSize(+ duration: const Duration(milliseconds: 320),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: fit.holding && fit.holdEx == exIdx+ ? Padding(padding: const EdgeInsets.only(bottom: 16), child: _holdCard(gc))+ : s.restRemaining != null+ ? Padding(padding: const EdgeInsets.only(bottom: 16), child: _restCard(gc, s))+ : const SizedBox(width: double.infinity),+ ),+ _ExerciseStage(+ index: exIdx,+ child: Container(+ padding: const EdgeInsets.fromLTRB(_cardPad, 16, _cardPad, 16),decoration: BoxDecoration(color: gc.bgRaised,- borderRadius: BorderRadius.circular(22),+ borderRadius: BorderRadius.circular(20),),- child: Row(+ child: Column(children: [- _restNudge(gc, '−15', t.decrease, () => fit.nudgeRest(-15)),- Expanded(- child: Column(- children: [- Text(t.rest.toUpperCase(),- style: AppTheme.f(9.5,- weight: FontWeight.w700,- color: gc.textTertiary,- letterSpacing: 1.5)),- const SizedBox(height: 3),- Text('${s.restRemaining}s',- style: AppTheme.f(30, weight: FontWeight.w800, color: gc.text)),- ],- ),+ Padding(+ padding: const EdgeInsets.fromLTRB(_rowPad, 0, _rowPad, 10),+ child: _setsHeader(gc, mode, repsOnly),),- _restNudge(gc, '+15', t.increase, () => fit.nudgeRest(15)),- const SizedBox(width: 4),- GestureDetector(- behavior: HitTestBehavior.opaque,- onTap: fit.skipRest,- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 11),- decoration:- BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(100)),- child: Text(titleCase(t.skip),- style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.text)),+ for (int j = 0; j < (ex?.sets.length ?? 0); j++) ...[+ _swipeToDelete(context, gc, exIdx, j, ex!.sets[j], locked,+ _setRow(gc, exIdx, j, ex.sets[j], repsOnly, locked)),+ ],+ if (!repsOnly && mode.isEmpty && ex != null) _guard(locked, _plateRow(context, gc, ex)),+ const SizedBox(height: 10),+ _guard(+ locked,+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: _rowPad),+ child: Row(+ children: [+ Expanded(child: _dashedAction(gc, t.addSet, () => fit.addSet(exIdx))),+ if (second != null) ...[+ const SizedBox(width: 8),+ Expanded(child: second),+ ],+ ],+ ),),),],),),- const SizedBox(height: 16),- ],- Container(- padding: const EdgeInsets.fromLTRB(_cardPad, 16, _cardPad, 16),- decoration: BoxDecoration(- color: gc.bgRaised,- borderRadius: BorderRadius.circular(20),- ),- child: Column(- children: [- Padding(- padding: const EdgeInsets.fromLTRB(_rowPad, 0, _rowPad, 10),- child: _setsHeader(gc, repsOnly),- ),- for (int j = 0; j < (ex?.sets.length ?? 0); j++)- _setRow(gc, exIdx, j, ex!.sets[j], repsOnly),- if (!repsOnly && ex != null) _plateRow(context, gc, ex),- const SizedBox(height: 10),- Padding(- padding: const EdgeInsets.symmetric(horizontal: _rowPad),- child: Row(- children: [- Expanded(child: _dashedAction(gc, t.addSet, () => fit.addSet(exIdx))),- if (!repsOnly && !fit.hasWarmup(exIdx)) ...[- const SizedBox(width: 8),- Expanded(- child: _dashedAction(- gc, t.addWarmup, () => fit.addWarmupSets(exIdx))),- ],- ],- ),- ),- ],- ),),const SizedBox(height: 22),- Row(+ _guard(+ locked,+ Row(children: [Expanded(child: GhostButton(@@ -194,29 +169,194 @@ class SessionScreen extends StatelessWidget {),),],+ ),),const SizedBox(height: 16),Row(children: [- _circleBtn(gc, Ic.chevronLeft, fit.prevExercise, enabled: exIdx > 0),+ _circleBtn(gc, Ic.chevronLeft, fit.prevExercise, enabled: !locked && exIdx > 0),const SizedBox(width: 10),- Expanded(child: _mainAction(gc, ex, exIdx, s.exercises.length)),+ Expanded(child: _mainAction(gc, ex, exIdx, s.exercises.length, locked)),const SizedBox(width: 10),- _circleBtn(gc, Ic.chevronRightBold, () => _goNext(context, ex),- enabled: exIdx < s.exercises.length - 1),+ _circleBtn(gc, Ic.chevronRightBold, fit.nextExercise,+ enabled: !locked && exIdx < s.exercises.length - 1),]),const SizedBox(height: 10),- 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))),- Container(width: 1, height: 12, color: gc.border),- ],- _textAction(gc, t.finishSession, fit.finishSession),- ]),+ _guard(+ 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))),+ Container(width: 1, height: 12, color: gc.border),+ ],+ _textAction(gc, t.finishSession, fit.finishSession),+ ]),+ ),],);}+ Widget? _secondAction(GymColors gc, SessionExercise? ex, int exIdx, String mode, bool repsOnly) {+ if (mode == 'cardio') return null;+ if (ex != null && repsOnly) {+ return _dashedAction(gc, t.addWeightAction.toUpperCase(), () => fit.toggleRepsOnly(ex.id));+ }+ if (mode.isNotEmpty) return null;+ if (fit.hasWarmup(exIdx)) {+ return _dashedAction(gc, t.removeWarmup.toUpperCase(), () => fit.removeWarmupSets(exIdx));+ }+ return _dashedAction(gc, t.addWarmup, () => fit.addWarmupSets(exIdx));+ }++ Widget _exerciseHeader(BuildContext context, GymColors gc, SessionExercise? ex) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (fit.inSuperset) ...[+ Container(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(100)),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(PhosphorIconsRegular.link, size: 11, color: gc.brass),+ const SizedBox(width: 5),+ Text(t.superset,+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.brass, letterSpacing: 0.5)),+ ]),+ ),+ const SizedBox(height: 8),+ ],+ 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)),+ ),+ if (ex != null && fit.lastSummaryFor(ex.id) != null) ...[+ const SizedBox(height: 10),+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () => showExerciseHistorySheet(context, ex.id),+ child: Row(children: [+ Text(t.last,+ style: AppTheme.f(11, weight: FontWeight.w600, color: gc.textTertiary, letterSpacing: 0.4)),+ const SizedBox(width: 8),+ Flexible(+ child: Text(fit.lastSummaryFor(ex.id)!,+ style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary)),+ ),+ const SizedBox(width: 4),+ Icon(PhosphorIconsRegular.caretRight, size: 11, color: gc.textTertiary),+ ]),+ ),+ if (fit.nextTargetLabel(ex.id) != null) _nextRow(gc, ex.id),+ ],+ ],+ );+ }++ Widget _progressStrip(BuildContext context, GymColors gc, WorkoutSession s, bool locked) {+ final n = s.exercises.length;+ return Semantics(+ button: true,+ label: t.workoutOverview,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: locked ? null : () => showSessionOverview(context),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(children: [+ Expanded(+ child: Text(fit.sessionProgressLabel,+ style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary, letterSpacing: 0.4)),+ ),+ if (!locked)+ Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(PhosphorIconsRegular.listBullets, size: 14, color: gc.textSecondary),+ const SizedBox(width: 5),+ Text(t.allExercisesShort,+ style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textSecondary)),+ ]),+ ]),+ const SizedBox(height: 9),+ Row(children: [+ for (var i = 0; i < n; i++) ...[+ if (i > 0) SizedBox(width: n > 12 ? 2 : 4),+ Expanded(+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 320),+ curve: Curves.easeOutCubic,+ height: i == s.currentIndex ? 6 : 4,+ decoration: BoxDecoration(+ color: _stripColor(gc, s, i),+ borderRadius: BorderRadius.circular(3),+ ),+ ),+ ),+ ],+ ]),+ ],+ ),+ ),+ );+ }++ Color _stripColor(GymColors gc, WorkoutSession s, int i) {+ final sets = s.exercises[i].sets;+ final done = sets.isNotEmpty && sets.every((st) => st.done);+ if (i == s.currentIndex) return done ? gc.sage : gc.ember;+ if (done) return gc.sage;+ if (sets.any((st) => st.done)) return Color.lerp(gc.bgRaised2, gc.sage, 0.45)!;+ return gc.bgRaised2;+ }++ Widget _swipeToDelete(BuildContext context, GymColors gc, int exIdx, int j, SessionSet st,+ bool locked, Widget child) {+ if (locked) return child;+ return Dismissible(+ key: ObjectKey(st),+ direction: DismissDirection.endToStart,+ background: Container(+ margin: const EdgeInsets.only(bottom: 2),+ padding: const EdgeInsets.only(right: 18),+ alignment: Alignment.centerRight,+ decoration: BoxDecoration(+ color: gc.danger.withValues(alpha: 0.16),+ borderRadius: BorderRadius.circular(14),+ ),+ child: Icon(PhosphorIconsRegular.trash, size: 18, color: gc.danger),+ ),+ onDismissed: (_) => _deleteSet(context, exIdx, j),+ child: child,+ );+ }++ void _deleteSet(BuildContext context, int exIdx, int j) {+ final gone = fit.removeSet(exIdx, j);+ if (gone == null) return;+ HapticFeedback.mediumImpact();+ showNotchToast(+ context,+ t.setDeleted,+ icon: PhosphorIconsFill.trash,+ accent: context.gc.danger,+ action: t.undo,+ onTap: () => fit.insertSet(exIdx, j, gone),+ duration: const Duration(milliseconds: 3200),+ );+ }++ Widget _guard(bool locked, Widget child) => _LockGuard(locked: locked, child: child);++ void _setLock(bool on) {+ if (fit.sessionLocked == on) return;+ HapticFeedback.mediumImpact();+ fit.toggleSessionLock();+ }+Widget _nextRow(GymColors gc, String id) {final target = fit.nextTarget(id)!;return Padding(@@ -247,28 +387,6 @@ class SessionScreen extends StatelessWidget {);}- Widget _restNudge(GymColors gc, String glyph, String semantic, VoidCallback onTap) {- return Semantics(- button: true,- label: semantic,- child: GestureDetector(- behavior: HitTestBehavior.opaque,- onTap: onTap,- child: SizedBox(- width: 48,- height: 48,- child: Center(- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),- decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(8)),- child: Text(glyph, style: AppTheme.f(12, weight: FontWeight.w600, color: gc.text)),- ),- ),- ),- ),- );- }-Future<void> _confirmDrop(BuildContext context, int exIdx, String name) async {final ok = await askConfirm(context,@@ -282,10 +400,12 @@ class SessionScreen extends StatelessWidget {static const _numCol = 26.0;static const _checkCol = 40.0;static const _gap = 10.0;+ static const _tightGap = 6.0;+ static const _effortCol = 36.0;static const _cardPad = 8.0;static const _rowPad = 14.0;- Widget _setsHeader(GymColors gc, bool repsOnly) {+ Widget _setsHeader(GymColors gc, String mode, bool repsOnly) {final s = AppTheme.f(11, weight: FontWeight.w600, color: gc.textSecondary, letterSpacing: 0.4);Widget label(String t) => FittedBox(@@ -293,45 +413,80 @@ class SessionScreen extends StatelessWidget {alignment: Alignment.center,child: Text(t, maxLines: 1, softWrap: false, style: s),);+ final effort = _showsEffort(mode);+ final gap = effort ? _tightGap : _gap;return Row(children: [SizedBox(width: _numCol, child: label(t.setCol)),- const SizedBox(width: _gap),- Expanded(child: label(t.repsCol)),- if (!repsOnly) ...[- const SizedBox(width: _gap),- Expanded(child: label(t.weightCol(fit.units.toUpperCase()))),+ for (final h in _headers(mode, repsOnly)) ...[+ SizedBox(width: gap),+ Expanded(child: label(h)),],- const SizedBox(width: _gap),+ if (effort) ...[+ SizedBox(width: gap),+ SizedBox(width: _effortCol, child: label(fit.usesRir ? 'RIR' : 'RPE')),+ ],+ SizedBox(width: gap),const SizedBox(width: _checkCol),]);}- Widget _liveBar(GymColors gc) {+ Widget _liveBar(GymColors gc, bool locked) {return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [+ if (locked)+ Flexible(child: _lockedChip(gc))+ else+ Row(children: [+ 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),+ ),+ ]),Row(children: [- 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),- ),- ]),- Row(children: [- Text(fit.elapsedLabel,+ RollingText(fit.elapsedLabel,style: AppTheme.f(18,weight: FontWeight.w700, color: fit.sessionPaused ? gc.textSecondary : gc.text)),- const SizedBox(width: 10),- Semantics(+ const SizedBox(width: 2),+ if (!locked)+ Semantics(+ button: true,+ label: t.lockWorkout,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () => _setLock(true),+ child: SizedBox(+ width: 44,+ height: 48,+ child: Center(+ child: Container(+ width: 36,+ height: 36,+ decoration: BoxDecoration(+ color: gc.bgRaised2,+ shape: BoxShape.circle,+ border: Border.all(color: gc.border),+ ),+ child: Icon(PhosphorIconsRegular.fingerprint, size: 17, color: gc.text),+ ),+ ),+ ),+ ),+ ),+ const SizedBox(width: 2),+ _guard(+ locked,+ Semantics(button: true,label: fit.sessionPaused ? t.resumeWorkout : t.pauseWorkout,child: GestureDetector(@@ -359,11 +514,14 @@ class SessionScreen extends StatelessWidget {),),),+ ),]),],);}+ Widget _lockedChip(GymColors gc) => _HoldToUnlock(onUnlock: () => _setLock(false));+Widget _manualBar(GymColors gc, WorkoutSession s) {return Row(children: [Icon(PhosphorIconsRegular.calendarPlus, size: 15, color: gc.brass),@@ -379,7 +537,118 @@ class SessionScreen extends StatelessWidget {]);}- Widget _setRow(GymColors gc, int exIdx, int j, SessionSet st, bool repsOnly) {+ List<Widget> _cells(GymColors gc, int exIdx, int j, SessionSet st, String mode, bool repsOnly) {+ final cardio = mode == 'cardio';+ Widget reps() => _miniStepper(+ gc,+ '${st.reps}',+ () => fit.bumpSessionReps(exIdx, j, -1),+ () => fit.bumpSessionReps(exIdx, j, 1),+ 22,+ onEdit: (context) => _ruler(+ context,+ title: t.repsTitle,+ value: st.reps.toDouble(),+ max: 100,+ step: 1,+ majorEvery: 5,+ onSave: (v) => fit.setSessionReps(exIdx, j, v.round()),+ ),+ );+ Widget weight() => _miniStepper(+ gc,+ fit.weightValue(st.weight),+ () => fit.bumpSessionWeight(exIdx, j, -1),+ () => fit.bumpSessionWeight(exIdx, j, 1),+ 26,+ onEdit: (context) => _ruler(+ context,+ title: t.weightTitle(fit.units.toUpperCase()),+ value: fit.toDisplayWeight(st.weight),+ max: fit.isLb ? 660 : 300,+ step: fit.isLb ? 1 : 0.5,+ majorEvery: 10,+ unit: fit.units,+ onSave: (v) => fit.setSessionWeightShown(exIdx, j, v),+ ),+ );+ Widget time() => _miniStepper(+ gc,+ durationLabel(st.sec ?? 0),+ () => fit.bumpSessionSeconds(exIdx, j, cardio ? -60 : -15),+ () => fit.bumpSessionSeconds(exIdx, j, cardio ? 60 : 15),+ 34,+ onEdit: (context) => cardio+ ? _ruler(+ context,+ title: t.timeMinutesTitle,+ value: ((st.sec ?? 0) / 60).roundToDouble(),+ max: 300,+ step: 1,+ majorEvery: 5,+ unit: 'min',+ onSave: (v) => fit.setSessionSeconds(exIdx, j, (v * 60).round()),+ )+ : _ruler(+ context,+ title: t.timeSecondsTitle,+ value: (st.sec ?? 0).toDouble(),+ max: 900,+ step: 5,+ majorEvery: 6,+ format: (v) => clockLabel(v.round()),+ onSave: (v) => fit.setSessionSeconds(exIdx, j, v.round()),+ ),+ );+ Widget distance() => _miniStepper(+ gc,+ fit.distanceValue(st.km ?? 0),+ () => fit.bumpSessionDistance(exIdx, j, -1),+ () => fit.bumpSessionDistance(exIdx, j, 1),+ 30,+ onEdit: (context) => _ruler(+ context,+ title: t.distanceTitle(fit.distanceUnit),+ value: fit.toDisplayKm(st.km ?? 0),+ max: 100,+ step: 0.1,+ majorEvery: 10,+ unit: fit.distanceUnit,+ onSave: (v) => fit.setSessionDistanceShown(exIdx, j, v),+ ),+ );+ return switch (mode) {+ 'cardio' => [distance(), time()],+ 'time' => [time(), if (!repsOnly) weight()],+ _ => [reps(), if (!repsOnly) weight()],+ };+ }++ List<String> _headers(String mode, bool repsOnly) => switch (mode) {+ 'cardio' => [t.distanceCol(fit.distanceUnit.toUpperCase()), t.timeCol],+ 'time' => [t.timeCol, if (!repsOnly) t.weightCol(fit.units.toUpperCase())],+ _ => [t.repsCol, if (!repsOnly) t.weightCol(fit.units.toUpperCase())],+ };++ Widget _setRow(GymColors gc, int exIdx, int j, SessionSet st, bool repsOnly, bool locked) {+ final mode = fit.modeOf(fit.session?.exercises[exIdx].id ?? '');+ return Builder(+ builder: (ctx) => GestureDetector(+ behavior: HitTestBehavior.translucent,+ onLongPress: locked+ ? null+ : () {+ HapticFeedback.mediumImpact();+ _kindSheet(ctx, exIdx, j, st.kind);+ },+ child: _setRowBody(gc, exIdx, j, st, repsOnly, locked, mode),+ ),+ );+ }++ Widget _setRowBody(GymColors gc, int exIdx, int j, SessionSet st, bool repsOnly, bool locked, String mode) {+ final effort = _showsEffort(mode);+ final gap = effort ? _tightGap : _gap;return Container(margin: const EdgeInsets.only(bottom: 2),padding: const EdgeInsets.symmetric(horizontal: _rowPad, vertical: 10),@@ -396,49 +665,21 @@ class SessionScreen extends StatelessWidget {label: t.setType,child: GestureDetector(behavior: HitTestBehavior.opaque,- onTap: () => _kindSheet(ctx, exIdx, j, st.kind),+ onTap: locked ? null : () => _kindSheet(ctx, exIdx, j, st.kind),child: _setBadge(gc, exIdx, j, st),),),),),- const SizedBox(width: _gap),- Expanded(- child: _miniStepper(- gc,- '${st.reps}',- () => fit.bumpSessionReps(exIdx, j, -1),- () => fit.bumpSessionReps(exIdx, j, 1),- 22,- onEdit: (context) => _editValue(- context,- title: t.repsTitle,- initial: '${st.reps}',- decimal: false,- onSave: (v) => fit.setSessionReps(exIdx, j, v.round()),- ),- ),- ),- if (!repsOnly) ...[- const SizedBox(width: _gap),- Expanded(- child: _miniStepper(- gc,- fit.weightValue(st.weight),- () => fit.bumpSessionWeight(exIdx, j, -1),- () => fit.bumpSessionWeight(exIdx, j, 1),- 26,- onEdit: (context) => _editValue(- context,- title: t.weightTitle(fit.units.toUpperCase()),- initial: fit.weightValue(st.weight),- decimal: true,- onSave: (v) => fit.setSessionWeightShown(exIdx, j, v),- ),- ),- ),+ for (final cell in _cells(gc, exIdx, j, st, mode, repsOnly)) ...[+ SizedBox(width: gap),+ Expanded(child: cell),+ ],+ if (effort) ...[+ SizedBox(width: gap),+ SizedBox(width: _effortCol, child: _effortCell(gc, exIdx, j, st, mode, locked)),],- const SizedBox(width: _gap),+ SizedBox(width: gap),Semantics(button: true,checked: st.done,@@ -470,6 +711,71 @@ class SessionScreen extends StatelessWidget {);}+ bool _asksEffort(SessionExercise ex, int j, String mode) {+ if (!fit.logRpe || mode == 'cardio') return false;+ final st = ex.sets[j];+ return st.done && st.counts && st.rpe == null && ex.sets.lastIndexWhere((x) => x.done) == j;+ }++ bool _showsEffort(String mode) => fit.logRpe && mode != 'cardio';++ Widget _effortCell(GymColors gc, int exIdx, int j, SessionSet st, String mode, bool locked) {+ final ex = fit.session?.exercises[exIdx];+ final waiting = ex != null && _asksEffort(ex, j, mode);+ final rpe = st.rpe;+ return Builder(+ builder: (ctx) => Semantics(+ button: true,+ label: fit.usesRir ? 'RIR' : 'RPE',+ value: rpe == null ? null : fmt(fit.usesRir ? 10 - rpe : rpe),+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: locked ? null : () => _editEffort(ctx, exIdx, j, rpe),+ child: SizedBox(+ height: 44,+ child: Center(+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ height: 30,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: rpe == null ? Colors.transparent : gc.bgRaised2,+ borderRadius: BorderRadius.circular(8),+ border: Border.all(+ color: waiting ? gc.ember : (rpe == null ? gc.border : Colors.transparent),+ width: waiting ? 1.6 : 1,+ ),+ ),+ child: Text(+ rpe == null ? '–' : fmt(fit.usesRir ? 10 - rpe : rpe),+ style: AppTheme.f(14,+ weight: FontWeight.w700, color: rpe == null ? gc.textTertiary : gc.text),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }++ Future<void> _editEffort(BuildContext context, int exIdx, int j, double? rpe) async {+ final rir = fit.usesRir;+ final v = await askRuler(context,+ title: rir ? 'RIR' : 'RPE',+ value: rir ? 10 - (rpe ?? 8) : rpe ?? 8,+ min: rir ? 0 : 1,+ max: rir ? 9 : 10,+ step: 0.5,+ majorEvery: 2,+ format: (v) => fmt(v),+ hint: rir ? t.rirHint : t.rpeHint,+ clearLabel: rpe == null ? null : t.none);+ if (v == null) return;+ fit.setSessionRpe(exIdx, j, v.isNaN ? null : (rir ? 10 - v : v));+ }+Widget _dashedAction(GymColors gc, String label, VoidCallback onTap) => GestureDetector(behavior: HitTestBehavior.opaque,onTap: onTap,@@ -522,19 +828,9 @@ class SessionScreen extends StatelessWidget {);}- Color _kindColor(GymColors gc, SetKind kind) => switch (kind) {- SetKind.warmup => gc.warn,- SetKind.drop => gc.info,- SetKind.failure => gc.danger,- SetKind.normal => gc.text,- };+ Color _kindColor(GymColors gc, SetKind kind) => setKindColor(gc, kind);- String _kindLabel(SetKind kind) => switch (kind) {- SetKind.warmup => t.setTypeWarmup,- SetKind.drop => t.setTypeDrop,- SetKind.failure => t.setTypeFailure,- SetKind.normal => t.setTypeNormal,- };+ String _kindLabel(SetKind kind) => setKindLabel(kind);Widget _setBadge(GymColors gc, int exIdx, int j, SessionSet st) {final sets = fit.session?.exercises[exIdx].sets ?? const <SessionSet>[];@@ -542,14 +838,13 @@ class SessionScreen extends StatelessWidget {for (var i = 0; i <= j && i < sets.length; i++) {if (sets[i].counts) working++;}+ final tag = setKindTag(st.kind);final base = st.kind == SetKind.warmup- ? 'W'- : switch (st.kind) {- SetKind.drop => '$working·D',- SetKind.failure => '$working·F',- _ => '$working',- };- final text = st.rpe == null ? base : '$base@${fmt(st.rpe!)}';+ ? tag+ : tag.isEmpty+ ? '$working'+ : '$working·$tag';+ final text = st.rpe == null || fit.logRpe ? base : '$base${fit.effortTag(st.rpe!)}';return FittedBox(fit: BoxFit.scaleDown,alignment: Alignment.centerLeft,@@ -562,7 +857,7 @@ class SessionScreen extends StatelessWidget {Future<void> _kindSheet(BuildContext context, int exIdx, int j, SetKind current) async {final gc = context.gc;- await showModalBottomSheet<void>(+ await showAppSheet<void>(context: context,backgroundColor: Colors.transparent,isScrollControlled: true,@@ -620,38 +915,25 @@ class SessionScreen extends StatelessWidget {],const SizedBox(height: 14),Text(t.setTypeHint, style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textTertiary, height: 1.4)),- if (fit.logRpe) ...[- const SizedBox(height: 20),- Text(t.rpeTitle,- style: AppTheme.f(12,- weight: FontWeight.w600, color: gc.textSecondary, letterSpacing: 0.4)),- const SizedBox(height: 10),- Wrap(spacing: 8, runSpacing: 8, children: [- Pill(- label: t.none,- bg: live?.rpe == null ? gc.ember : gc.bgRaised2,- fg: live?.rpe == null ? gc.onEmber : gc.textSecondary,- onTap: () => setSheet(() => fit.setSessionRpe(exIdx, j, null)),- hPad: 12,- vPad: 7,- fontSize: 12.5,- ),- for (final value in _rpeSteps)- Pill(- label: fmt(value),- bg: live?.rpe == value ? gc.ember : gc.bgRaised2,- fg: live?.rpe == value ? gc.onEmber : gc.textSecondary,- onTap: () => setSheet(() => fit.setSessionRpe(exIdx, j, value)),- hPad: 12,- vPad: 7,- fontSize: 12.5,- ),- ]),- const SizedBox(height: 10),- Text(t.rpeHint, style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textTertiary, height: 1.4)),- ],const SizedBox(height: 18),PrimaryButton(label: t.done, onTap: () => Navigator.of(sheet).pop()),+ const SizedBox(height: 4),+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ Navigator.of(sheet).pop();+ _deleteSet(context, exIdx, j);+ },+ child: SizedBox(+ height: 48,+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [+ Icon(PhosphorIconsRegular.trash, size: 16, color: gc.danger),+ const SizedBox(width: 8),+ Text(t.deleteSet,+ style: AppTheme.f(14, weight: FontWeight.w600, color: gc.danger)),+ ]),+ ),+ ),],),),@@ -660,9 +942,6 @@ class SessionScreen extends StatelessWidget {),);}-- static const _rpeSteps = [6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0];-Widget _miniStepper(GymColors gc,String value,@@ -707,8 +986,8 @@ class SessionScreen extends StatelessWidget {constraints: BoxConstraints(minWidth: minW),padding: const EdgeInsets.symmetric(vertical: 4),alignment: Alignment.center,- child: Text(value,- style: TextStyle(fontWeight: FontWeight.w600, color: gc.text, fontSize: 14)),+ child: RollingText(value,+ style: AppTheme.f(15, weight: FontWeight.w700, color: gc.text)),),),const SizedBox(width: 3),@@ -719,39 +998,93 @@ class SessionScreen extends StatelessWidget {);}- Future<void> _editValue(+ Future<void> _ruler(BuildContext context, {required String title,- required String initial,- required bool decimal,+ required double value,+ required double max,+ required double step,required void Function(double) onSave,+ int majorEvery = 10,+ String unit = '',+ String Function(double)? format,}) async {- final parsed = await askNumber(context, title: title, initial: initial, decimal: decimal);- if (parsed != null) onSave(parsed);+ final v = await askRuler(context,+ title: title,+ value: value,+ min: 0,+ max: max,+ step: step,+ unit: unit,+ majorEvery: majorEvery,+ format: format,+ tickLabel: format);+ if (v != null) onSave(v);}- Widget _mainAction(GymColors gc, SessionExercise? ex, int exIdx, int total) {+ Widget _holdCard(GymColors gc) {+ final count = fit.sessionSetCount;+ final lead = fit.holdLead;+ return TimerPanel(+ label: lead > 0 ? t.getReady : t.holdLabel,+ remaining: lead > 0 ? lead : fit.holdRemaining ?? 0,+ total: lead > 0 ? WorkoutState.holdLeadIn : fit.holdTotal,+ elapsed: fit.elapsedLabel,+ elapsedLabel: t.elapsedCaps,+ sets: '${count.done}/${count.total}',+ setsLabel: t.setsCaps,+ hint: t.tapToStop,+ color: gc.accent,+ onTap: fit.stopHold,+ );+ }++ Widget _restCard(GymColors gc, WorkoutSession s) {+ final count = fit.sessionSetCount;+ return TimerPanel(+ label: t.liveResting,+ remaining: s.restRemaining ?? 0,+ total: fit.restTotal,+ elapsed: fit.elapsedLabel,+ elapsedLabel: t.elapsedCaps,+ sets: '${count.done}/${count.total}',+ setsLabel: t.setsCaps,+ hint: t.tapToSkip,+ onTap: fit.skipRest,+ onMinus: () => fit.nudgeRest(-15),+ onPlus: () => fit.nudgeRest(15),+ );+ }++ Widget _mainAction(GymColors gc, SessionExercise? ex, int exIdx, int total, bool locked) {final pending = ex == null ? -1 : ex.sets.indexWhere((st) => !st.done);+ if (pending >= 0 && ex != null && fit.isTimed(ex.id)) {+ if (fit.holding && fit.holdEx == exIdx) {+ return PrimaryButton(+ label: '${t.stopLabel} · ${durationLabel(fit.holdRemaining ?? 0)}',+ onTap: fit.stopHold,+ height: 56,+ );+ }+ return PrimaryButton(+ label: t.startHold(durationLabel(ex.sets[pending].sec ?? 30)),+ icon: Ic.play,+ onTap: () => fit.startHold(exIdx, pending),+ height: 56,+ );+ }if (pending >= 0) {return PrimaryButton(label: t.setDone, onTap: () => fit.toggleSet(exIdx, pending), height: 56);}- if (exIdx < total - 1) {- return PrimaryButton(label: t.nextExercise, onTap: fit.nextExercise, height: 56);+ if (fit.pendingAfter(exIdx) != null) {+ return PrimaryButton(label: t.nextExercise, onTap: fit.goNextPending, height: 56);}- return PrimaryButton(label: t.finishSession, onTap: fit.finishSession, height: 56);- }-- Future<void> _goNext(BuildContext context, SessionExercise? ex) async {- if (ex != null && ex.sets.isNotEmpty && !ex.sets.any((st) => st.done)) {- final ok = await askConfirm(- context,- title: t.skipExercise,- body: t.skipExerciseBody(t.catalogName(ex.id, ex.name)),- confirmLabel: t.skip2,- );- if (!ok) return;+ if (exIdx < total - 1) {+ return _guard(+ locked, PrimaryButton(label: t.nextExercise, onTap: fit.nextExercise, height: 56));}- fit.nextExercise();+ return _guard(+ locked, PrimaryButton(label: t.finishSession, onTap: fit.finishSession, height: 56));}Widget _textAction(GymColors gc, String label, VoidCallback onTap) => Semantics(@@ -794,60 +1127,90 @@ class SessionScreen extends StatelessWidget {final goalHit = fit.goalPct >= 100;final vsLast = fit.summaryVsLast;final vol = fit.summaryVolumeKg;+ final sets = fit.session?.summarySets ?? 0;- return Padding(- padding: const EdgeInsets.only(top: 24),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- _finishHero(gc, prs: prs, streak: streak, goalHit: goalHit),- const SizedBox(height: 18),- Row(children: [- Expanded(child: _sumCard(gc, t.duration, fit.summaryDurationLabel)),- const SizedBox(width: 10),- Expanded(child: _sumCard(gc, t.setsCaps, '${fit.session?.summarySets ?? 0}')),- const SizedBox(width: 10),- Expanded(child: _sumCard(gc, t.volume, fit.volumeLabel(vol))),- ]),- const SizedBox(height: 10),- if (vsLast != null && vsLast > 0) _vsLastCard(gc, vol, vsLast) else _firstTimeCard(gc),- const SizedBox(height: 18),- Row(children: [- Expanded(child: PrimaryButton(label: t.saveAndExit, onTap: fit.saveAndExit)),- const SizedBox(width: 10),- Semantics(- button: true,- label: t.share,- child: GestureDetector(- onTap: () => showShareSheet(context, initial: ShareKind.streak),- child: Container(- width: 56,- height: 56,- decoration: BoxDecoration(- color: gc.bgRaised,- shape: BoxShape.circle,+ return _Celebrate(+ active: sets > 0,+ child: Padding(+ padding: const EdgeInsets.only(top: 24),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Rise(index: 0, child: _finishHero(gc, prs: prs, streak: streak, goalHit: goalHit)),+ const SizedBox(height: 18),+ Rise(+ index: 1,+ child: Row(children: [+ Expanded(child: _sumCard(gc, t.duration, fit.summaryDurationLabel)),+ const SizedBox(width: 10),+ Expanded(child: _countUp(sets.toDouble(), (v) => _sumCard(gc, t.setsCaps, '${v.round()}'))),+ const SizedBox(width: 10),+ Expanded(child: _countUp(vol, (v) => _sumCard(gc, t.volume, fit.volumeLabel(v)))),+ ]),+ ),+ const SizedBox(height: 10),+ Rise(+ index: 2,+ child: vsLast != null && vsLast > 0 ? _vsLastCard(gc, vol, vsLast) : _firstTimeCard(gc),+ ),+ const SizedBox(height: 18),+ Rise(+ index: 3,+ child: Row(children: [+ Expanded(child: PrimaryButton(label: t.saveAndExit, onTap: fit.saveAndExit)),+ const SizedBox(width: 10),+ Semantics(+ button: true,+ label: t.share,+ child: GestureDetector(+ onTap: () => showShareSheet(context, initial: ShareKind.streak),+ child: Container(+ width: 56,+ height: 56,+ decoration: BoxDecoration(color: gc.bgRaised, shape: BoxShape.circle),+ child: Icon(PhosphorIconsRegular.shareNetwork, size: 20, color: gc.text),+ ),),- child: Icon(PhosphorIconsRegular.shareNetwork, size: 20, color: gc.text),),+ ]),+ ),+ if (sets > 0 && fit.sessions.isNotEmpty) ...[+ const SizedBox(height: 10),+ Rise(+ index: 4,+ child: GhostButton(+ label: t.stickerOpen,+ icon: PhosphorIconsRegular.imageSquare,+ onTap: () => showStickerEditor(context, fit.sessions.last, prs: prs),+ ),+ ),+ ],+ const SizedBox(height: 10),+ Rise(+ index: 5,+ child: GhostButton(+ label: t.saveAsRoutine,+ icon: PhosphorIconsRegular.listChecks,+ onTap: () {+ if (fit.saveSessionAsRoutine().isEmpty) return;+ showNotchToast(context, t.savedAsRoutine,+ icon: PhosphorIconsFill.listChecks, accent: gc.sage);+ },),),- ]),- const SizedBox(height: 10),- GhostButton(- label: t.saveAsRoutine,- icon: PhosphorIconsRegular.listChecks,- onTap: () {- if (fit.saveSessionAsRoutine().isEmpty) return;- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(t.savedAsRoutine), behavior: SnackBarBehavior.floating),- );- },- ),- ],+ ],+ ),),);}+ Widget _countUp(double to, Widget Function(double v) builder) => TweenAnimationBuilder<double>(+ tween: Tween(begin: 0, end: to),+ duration: const Duration(milliseconds: 1100),+ curve: Curves.easeOutCubic,+ builder: (context, v, _) => builder(v),+ );+Widget _finishHero(GymColors gc, {required int prs, required int streak, required bool goalHit}) {return ClipRRect(borderRadius: BorderRadius.circular(24),@@ -968,7 +1331,7 @@ class SessionScreen extends StatelessWidget {void showAddToSessionSheet(BuildContext context) {final gc = context.gc;final search = TextEditingController();- showModalBottomSheet<void>(+ showAppSheet<void>(context: context,isScrollControlled: true,backgroundColor: gc.bgRaised,@@ -1086,3 +1449,460 @@ Widget _addRow(BuildContext sheetCtx, GymColors gc, Exercise ex) {),);}++class _ExerciseStage extends StatefulWidget {+ const _ExerciseStage({required this.index, required this.child, this.haptic = false, this.autoMoves});++ final int index;+ final Widget child;+ final bool haptic;+ final int? autoMoves;++ @override+ State<_ExerciseStage> createState() => _ExerciseStageState();+}++class _ExerciseStageState extends State<_ExerciseStage> {+ double _dir = 1;++ @override+ void didUpdateWidget(_ExerciseStage old) {+ super.didUpdateWidget(old);+ if (old.index == widget.index) return;+ _dir = widget.index > old.index ? 1 : -1;+ if (!widget.haptic) return;+ HapticFeedback.selectionClick();+ if (widget.autoMoves != old.autoMoves) _announce();+ }++ void _announce() {+ final ex = fit.currentExercise;+ if (ex == null) return;+ final gc = context.gc;+ final where = fit.inSuperset ? '${t.superset} · ${fit.sessionProgressLabel}' : fit.sessionProgressLabel;+ HapticFeedback.mediumImpact();+ showNotchToast(context, t.catalogName(ex.id, ex.name),+ subtitle: where,+ icon: fit.inSuperset ? PhosphorIconsBold.link : PhosphorIconsBold.arrowRight,+ accent: fit.inSuperset ? gc.brass : gc.ember,+ duration: const Duration(milliseconds: 1900));+ }++ @override+ Widget build(BuildContext context) {+ final current = widget.index;+ final dir = _dir;+ return AnimatedSwitcher(+ duration: const Duration(milliseconds: 520),+ switchInCurve: const Interval(0.3, 1, curve: Curves.easeOutCubic),+ switchOutCurve: const Interval(0.55, 1, curve: Curves.easeInCubic),+ transitionBuilder: (child, animation) {+ final incoming = (child.key as ValueKey?)?.value == current;+ final from = Offset(incoming ? 0.5 * dir : -0.5 * dir, 0);+ return FadeTransition(+ opacity: animation,+ child: SlideTransition(+ position: Tween<Offset>(begin: from, end: Offset.zero).animate(animation),+ child: ScaleTransition(+ scale: Tween<double>(begin: 0.94, end: 1).animate(animation),+ child: child,+ ),+ ),+ );+ },+ layoutBuilder: (currentChild, previousChildren) => Stack(+ alignment: Alignment.topCenter,+ children: [+ ...previousChildren,+ ?currentChild,+ ],+ ),+ child: KeyedSubtree(key: ValueKey(current), child: widget.child),+ );+ }+}++void showSessionOverview(BuildContext context) {+ final gc = context.gc;+ showAppSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: Colors.transparent,+ builder: (sheet) => AnimatedBuilder(+ animation: fit,+ builder: (sheet, _) {+ final s = fit.session;+ if (s == null || s.complete) return const SizedBox.shrink();+ return Container(+ padding: sheetPad(sheet),+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.86),+ 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: 18),+ Text(titleCase(t.workoutOverview),+ style: AppTheme.f(19, weight: FontWeight.w800, color: gc.text)),+ const SizedBox(height: 4),+ Text('${t.exerciseCount(s.exercises.length)} · ${fit.elapsedLabel}',+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary)),+ const SizedBox(height: 16),+ Flexible(+ child: ReorderableListView.builder(+ shrinkWrap: true,+ buildDefaultDragHandles: false,+ itemCount: s.exercises.length,+ onReorder: fit.reorderSessionExercise,+ proxyDecorator: (child, _, _) => Material(color: Colors.transparent, child: child),+ itemBuilder: (context, i) => _overviewRow(sheet, gc, s, i),+ ),+ ),+ const SizedBox(height: 6),+ Text(t.dragToReorder,+ textAlign: TextAlign.center,+ style: AppTheme.f(11, weight: FontWeight.w500, color: gc.textTertiary)),+ ],+ ),+ );+ },+ ),+ );+}++Widget _overviewRow(BuildContext sheet, GymColors gc, WorkoutSession s, int i) {+ final e = s.exercises[i];+ final def = fit.exerciseById(e.id);+ final done = e.sets.where((st) => st.done).length;+ final all = e.sets.isNotEmpty && done == e.sets.length;+ final current = i == s.currentIndex;+ final linked = e.linkedNext || (i > 0 && s.exercises[i - 1].linkedNext);+ return Container(+ key: ObjectKey(e),+ margin: const EdgeInsets.only(bottom: 8),+ decoration: BoxDecoration(+ color: current ? gc.bgRaised2 : Colors.transparent,+ borderRadius: BorderRadius.circular(16),+ border: Border.all(+ color: current ? gc.ember.withValues(alpha: 0.6) : gc.border.withValues(alpha: 0.6)),+ ),+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ fit.goToExercise(i);+ Navigator.of(sheet).pop();+ },+ child: Padding(+ padding: const EdgeInsets.fromLTRB(10, 8, 4, 8),+ child: Row(children: [+ Container(+ width: 26,+ height: 26,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: all ? gc.sage : (current ? gc.ember : gc.bgRaised2),+ shape: BoxShape.circle,+ ),+ child: all+ ? SvgPathIcon(Ic.checkBold, size: 12, color: Colors.white)+ : Text('${i + 1}',+ style: AppTheme.f(11.5,+ weight: FontWeight.w700, color: current ? gc.onEmber : gc.textSecondary)),+ ),+ const SizedBox(width: 10),+ if (def != null) ...[+ SizedBox(width: 40, child: ExerciseMedia(ex: def, height: 40, radius: 10, bordered: false)),+ const SizedBox(width: 10),+ ],+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(t.catalogName(e.id, e.name),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(14, weight: FontWeight.w600, color: gc.text)),+ const SizedBox(height: 2),+ Row(children: [+ Text(t.setsDoneOf(done, e.sets.length),+ style: AppTheme.f(11.5,+ weight: FontWeight.w500, color: all ? gc.sage : gc.textSecondary)),+ if (current) ...[+ Text(' · ', style: AppTheme.f(11.5, color: gc.textTertiary)),+ Text(t.nowLabel,+ style: AppTheme.f(11.5, weight: FontWeight.w700, color: gc.ember)),+ ],+ if (linked) ...[+ const SizedBox(width: 6),+ Icon(PhosphorIconsRegular.link, size: 12, color: gc.brass),+ ],+ ]),+ ],+ ),+ ),+ ReorderableDragStartListener(+ index: i,+ child: SizedBox(+ width: 40,+ height: 44,+ child: Icon(PhosphorIconsRegular.dotsSixVertical, size: 18, color: gc.textTertiary),+ ),+ ),+ ]),+ ),+ ),+ );+}++void showExerciseHistorySheet(BuildContext context, String exerciseId) {+ final gc = context.gc;+ final history = fit.exerciseHistory(exerciseId).take(8).toList();+ final ex = fit.exerciseById(exerciseId);+ showAppSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: Colors.transparent,+ builder: (sheet) => Container(+ padding: sheetPad(sheet),+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.8),+ decoration: BoxDecoration(+ color: gc.bgRaised,+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),+ ),+ 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),+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary)),+ const SizedBox(height: 14),+ if (history.isEmpty)+ Text(t.noHistory, style: AppTheme.f(13, weight: FontWeight.w500, color: gc.textSecondary)),+ for (var i = 0; i < history.length; i++)+ Container(+ padding: const EdgeInsets.symmetric(vertical: 12),+ decoration: BoxDecoration(+ border: i < history.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(history[i].date),+ style: AppTheme.f(13, weight: FontWeight.w600, color: gc.text)),+ ),+ Expanded(+ child: Text(fit.setsSummary(history[i].ex.sets),+ style: AppTheme.f(12.5,+ weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ );+}++void _showLockHint(BuildContext context) {+ HapticFeedback.heavyImpact();+ showNotchToast(+ context,+ t.screenLocked,+ subtitle: t.lockedHint,+ icon: PhosphorIconsFill.fingerprint,+ accent: context.gc.accent,+ );+}++class _LockGuard extends StatefulWidget {+ const _LockGuard({required this.locked, required this.child});++ final bool locked;+ final Widget child;++ @override+ State<_LockGuard> createState() => _LockGuardState();+}++class _LockGuardState extends State<_LockGuard> {+ DateTime? _last;+ int _taps = 0;++ void _tap() {+ final now = DateTime.now();+ if (_last == null || now.difference(_last!) > const Duration(milliseconds: 1500)) _taps = 0;+ _last = now;+ if (++_taps >= 2) {+ _taps = 0;+ _showLockHint(context);+ }+ }++ @override+ Widget build(BuildContext context) {+ return GestureDetector(+ behavior: widget.locked ? HitTestBehavior.opaque : HitTestBehavior.deferToChild,+ onTap: widget.locked ? _tap : null,+ child: IgnorePointer(+ ignoring: widget.locked,+ child: AnimatedOpacity(+ opacity: widget.locked ? 0.35 : 1,+ duration: const Duration(milliseconds: 220),+ child: widget.child,+ ),+ ),+ );+ }+}++class _HoldToUnlock extends StatefulWidget {+ const _HoldToUnlock({required this.onUnlock});++ final VoidCallback onUnlock;++ @override+ State<_HoldToUnlock> createState() => _HoldToUnlockState();+}++class _HoldToUnlockState extends State<_HoldToUnlock> with SingleTickerProviderStateMixin {+ late final AnimationController _hold = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 650),+ reverseDuration: const Duration(milliseconds: 220),+ )..addStatusListener((s) {+ if (s == AnimationStatus.completed) {+ HapticFeedback.mediumImpact();+ widget.onUnlock();+ }+ });+ DateTime? _last;+ int _taps = 0;++ void _down() {+ HapticFeedback.selectionClick();+ _hold.forward();+ }++ void _up() {+ if (_hold.isCompleted) return;+ _hold.reverse();+ final now = DateTime.now();+ if (_last == null || now.difference(_last!) > const Duration(milliseconds: 1500)) _taps = 0;+ _last = now;+ if (++_taps >= 2) {+ _taps = 0;+ _showLockHint(context);+ }+ }++ @override+ void dispose() {+ _hold.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ return Semantics(+ button: true,+ label: t.unlockWorkout,+ hint: t.holdToUnlock,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTapDown: (_) => _down(),+ onTapUp: (_) => _up(),+ onTapCancel: _up,+ child: AnimatedBuilder(+ animation: _hold,+ builder: (context, _) {+ final v = _hold.value;+ return Transform.scale(+ scale: 1 - 0.04 * v,+ child: Container(+ padding: const EdgeInsets.fromLTRB(6, 6, 14, 6),+ decoration: BoxDecoration(+ color: gc.emberSoft,+ borderRadius: BorderRadius.circular(100),+ ),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ SizedBox(+ width: 26,+ height: 26,+ child: Stack(alignment: Alignment.center, children: [+ SizedBox.expand(+ child: CircularProgressIndicator(+ value: v,+ strokeWidth: 2.4,+ strokeCap: StrokeCap.round,+ color: gc.ember,+ backgroundColor: gc.ember.withValues(alpha: 0.15),+ ),+ ),+ Icon(PhosphorIconsFill.fingerprint, size: 14, color: gc.ember),+ ]),+ ),+ const SizedBox(width: 8),+ Flexible(+ child: Text(+ t.holdToUnlock,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(12, weight: FontWeight.w800, color: gc.ember),+ ),+ ),+ ]),+ ),+ );+ },+ ),+ ),+ );+ }+}++class _Celebrate extends StatefulWidget {+ const _Celebrate({required this.active, required this.child});++ final bool active;+ final Widget child;++ @override+ State<_Celebrate> createState() => _CelebrateState();+}++class _CelebrateState extends State<_Celebrate> {+ static Object? _shownFor;++ @override+ void initState() {+ super.initState();+ final s = fit.session;+ if (!widget.active || s == null || identical(_shownFor, s)) return;+ _shownFor = s;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ final gc = context.gc;+ celebrate(context, colors: [gc.accent, gc.brass, gc.sage, gc.text]);+ });+ }++ @override+ Widget build(BuildContext context) => widget.child;+}diff --git a/lib/services/beeper.dart b/lib/services/beeper.dartnew file mode 100644index 0000000..d5c467b--- /dev/null+++ b/lib/services/beeper.dart@@ -0,0 +1,103 @@+import 'dart:io';+import 'dart:math' as math;++import 'package:audioplayers/audioplayers.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:path_provider/path_provider.dart';++class Beeper {+ Beeper._();++ static final instance = Beeper._();++ AudioPlayer? _player;+ String? _tick;+ String? _go;+ bool _failed = false;++ Future<bool> _ready() async {+ if (_player != null) return true;+ if (_failed || kIsWeb) return false;+ try {+ final dir = await getTemporaryDirectory();+ _tick = await _write(dir, 'gm_tick.wav', _tone(880, 0.09));+ _go = await _write(dir, 'gm_go.wav', _tone(1318.5, 0.32));+ final p = AudioPlayer();+ await p.setReleaseMode(ReleaseMode.stop);+ await p.setAudioContext(AudioContext(+ android: const AudioContextAndroid(+ contentType: AndroidContentType.sonification,+ usageType: AndroidUsageType.notification,+ audioFocus: AndroidAudioFocus.gainTransientMayDuck,+ ),+ iOS: AudioContextIOS(category: AVAudioSessionCategory.ambient, options: const {}),+ ));+ _player = p;+ return true;+ } catch (_) {+ _failed = true;+ return false;+ }+ }++ Future<void> tick({required bool sound}) => _play(_TickKind.tick, sound);++ Future<void> go({required bool sound}) => _play(_TickKind.go, sound);++ Future<void> _play(_TickKind kind, bool sound) async {+ try {+ kind == _TickKind.go ? HapticFeedback.heavyImpact() : HapticFeedback.selectionClick();+ } catch (_) {}+ if (!sound || !await _ready()) return;+ final path = kind == _TickKind.go ? _go : _tick;+ if (path == null) return;+ try {+ await _player!.stop();+ await _player!.play(DeviceFileSource(path), volume: 0.9);+ } catch (_) {}+ }++ static Future<String> _write(Directory dir, String name, Uint8List bytes) async {+ final file = File('${dir.path}/$name');+ if (!await file.exists() || await file.length() != bytes.length) {+ await file.writeAsBytes(bytes, flush: true);+ }+ return file.path;+ }++ static Uint8List _tone(double hz, double secs) {+ const rate = 44100;+ final n = (rate * secs).round();+ final data = ByteData(44 + n * 2);+ void text(int at, String s) {+ for (var i = 0; i < s.length; i++) {+ data.setUint8(at + i, s.codeUnitAt(i));+ }+ }++ text(0, 'RIFF');+ data.setUint32(4, 36 + n * 2, Endian.little);+ text(8, 'WAVE');+ text(12, 'fmt ');+ data.setUint32(16, 16, Endian.little);+ data.setUint16(20, 1, Endian.little);+ data.setUint16(22, 1, Endian.little);+ data.setUint32(24, rate, Endian.little);+ data.setUint32(28, rate * 2, Endian.little);+ data.setUint16(32, 2, Endian.little);+ data.setUint16(34, 16, Endian.little);+ text(36, 'data');+ data.setUint32(40, n * 2, Endian.little);+ for (var i = 0; i < n; i++) {+ final t = i / rate;+ final attack = math.min(1.0, i / (rate * 0.004));+ final release = math.exp(-t * (6 / secs));+ final wave = math.sin(2 * math.pi * hz * t) * 0.8 + math.sin(4 * math.pi * hz * t) * 0.2;+ data.setInt16(44 + i * 2, (wave * 0.5 * attack * release * 32767).round(), Endian.little);+ }+ return data.buffer.asUint8List();+ }+}++enum _TickKind { tick, go }diff --git a/lib/services/rest_alarm.dart b/lib/services/rest_alarm.dartindex f0e1d14..04e4cc1 100644--- a/lib/services/rest_alarm.dart+++ b/lib/services/rest_alarm.dart@@ -1,6 +1,9 @@+import 'dart:io' show Platform;+import 'package:audioplayers/audioplayers.dart';import 'package:flutter/foundation.dart';import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart' show AppLifecycleState, WidgetsBinding;import 'package:flutter_local_notifications/flutter_local_notifications.dart';import 'package:timezone/data/latest.dart' as tzdata;import 'package:timezone/timezone.dart' as tz;@@ -12,19 +15,51 @@ class RestAlarm {static final RestAlarm instance = RestAlarm._();static const _id = 1001;- AndroidNotificationDetails get _android => AndroidNotificationDetails(- 'rest_timer',- t.notifRestChannel,- channelDescription: t.notifRestChannelWhy,- importance: Importance.max,- priority: Priority.high,- category: AndroidNotificationCategory.alarm,- playSound: true,- enableVibration: true,- audioAttributesUsage: AudioAttributesUsage.alarm,- fullScreenIntent: true,- visibility: NotificationVisibility.public,- );+ static const _haptics = MethodChannel('gymmane/haptics');+ static final _pattern = Int64List.fromList([0, 350, 180, 350, 180, 600]);++ String style = 'loud';++ AndroidNotificationDetails get _android => switch (style) {+ 'quiet' => AndroidNotificationDetails(+ 'rest_timer_quiet',+ t.notifRestChannel,+ channelDescription: t.notifRestChannelWhy,+ importance: Importance.max,+ priority: Priority.high,+ category: AndroidNotificationCategory.reminder,+ playSound: true,+ enableVibration: true,+ vibrationPattern: _pattern,+ audioAttributesUsage: AudioAttributesUsage.notification,+ visibility: NotificationVisibility.public,+ ),+ 'vibrate' => AndroidNotificationDetails(+ 'rest_timer_vibrate',+ t.notifRestChannel,+ channelDescription: t.notifRestChannelWhy,+ importance: Importance.max,+ priority: Priority.high,+ category: AndroidNotificationCategory.reminder,+ playSound: false,+ enableVibration: true,+ vibrationPattern: _pattern,+ visibility: NotificationVisibility.public,+ ),+ _ => AndroidNotificationDetails(+ 'rest_timer',+ t.notifRestChannel,+ channelDescription: t.notifRestChannelWhy,+ importance: Importance.max,+ priority: Priority.high,+ category: AndroidNotificationCategory.alarm,+ playSound: true,+ enableVibration: true,+ audioAttributesUsage: AudioAttributesUsage.alarm,+ fullScreenIntent: true,+ visibility: NotificationVisibility.public,+ ),+ };AndroidNotificationDetails get _androidAlert => AndroidNotificationDetails('rest_timer_alert',@@ -38,6 +73,22 @@ class RestAlarm {visibility: NotificationVisibility.public,);+ DarwinNotificationDetails get _darwin => DarwinNotificationDetails(+ presentAlert: true,+ presentBanner: true,+ presentList: true,+ presentSound: style != 'vibrate',+ sound: style == 'vibrate' ? null : 'rest_over.wav',+ interruptionLevel: InterruptionLevel.timeSensitive,+ );++ DarwinNotificationDetails get _darwinAlert => const DarwinNotificationDetails(+ presentAlert: true,+ presentBanner: true,+ presentList: true,+ presentSound: false,+ );+final _plugin = FlutterLocalNotificationsPlugin();AudioPlayer? _player;@@ -59,7 +110,12 @@ class RestAlarm {tzdata.initializeTimeZones();await _plugin.initialize(settings: const InitializationSettings(- android: AndroidInitializationSettings('@mipmap/ic_launcher'),+ android: AndroidInitializationSettings('@drawable/ic_stat_gymmane'),+ iOS: DarwinInitializationSettings(+ requestAlertPermission: false,+ requestSoundPermission: false,+ requestBadgePermission: false,+ ),),);_ready = true;@@ -70,30 +126,64 @@ class RestAlarm {final player = AudioPlayer();await player.setReleaseMode(ReleaseMode.stop);await player.setPlayerMode(PlayerMode.mediaPlayer);+ _player = player;+ await _applyAudioContext();+ } catch (e) {+ debugPrint('RestAlarm (audio) no disponible: $e');+ }+ }++ String? _contextFor;++ Future<void> _applyAudioContext() async {+ final player = _player;+ if (player == null || _contextFor == style) return;+ final loud = style == 'loud';+ try {await player.setAudioContext(AudioContext(- android: const AudioContextAndroid(+ android: AudioContextAndroid(isSpeakerphoneOn: false,stayAwake: true,contentType: AndroidContentType.sonification,- usageType: AndroidUsageType.alarm,+ usageType: loud ? AndroidUsageType.alarm : AndroidUsageType.notification,audioFocus: AndroidAudioFocus.gainTransientMayDuck,),- iOS: AudioContextIOS(category: AVAudioSessionCategory.playback, options: const {}),+ iOS: AudioContextIOS(+ category: loud ? AVAudioSessionCategory.playback : AVAudioSessionCategory.ambient,+ options: const {},+ ),),);- _player = player;+ _contextFor = style;} catch (e) {- debugPrint('RestAlarm (audio) no disponible: $e');+ debugPrint('RestAlarm (contexto de audio): $e');+ }+ }++ Future<void> _buzz() async {+ try {+ await _haptics.invokeMethod<void>('buzz');+ } catch (_) {+ try {+ HapticFeedback.heavyImpact();+ } catch (_) {}}}AndroidFlutterLocalNotificationsPlugin? get _androidPlugin =>_plugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();+ IOSFlutterLocalNotificationsPlugin? get _iosPlugin =>+ _plugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>();+Future<bool> notificationsAllowed() async {if (!_ready) return true;try {+ if (Platform.isIOS) {+ final options = await _iosPlugin?.checkPermissions();+ return options?.isEnabled ?? true;+ }return await _androidPlugin?.areNotificationsEnabled() ?? true;} catch (_) {return true;@@ -103,6 +193,9 @@ class RestAlarm {Future<bool> requestPermission() async {if (!_ready) return true;try {+ if (Platform.isIOS) {+ return await _iosPlugin?.requestPermissions(alert: true, sound: true) ?? true;+ }final granted = await _androidPlugin?.requestNotificationsPermission() ?? true;await _androidPlugin?.requestExactAlarmsPermission();return granted;@@ -120,25 +213,32 @@ class RestAlarm {Future<void> fireNow() async {await cancel();+ final visible = WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed;- if (_ready) {+ if (_ready && !visible) {try {await _plugin.show(id: _id,title: t.restOverTitle,body: t.restOverBody,- notificationDetails: NotificationDetails(android: _androidAlert),+ notificationDetails: NotificationDetails(android: _androidAlert, iOS: _darwinAlert),);} catch (e) {debugPrint('No se pudo mostrar el aviso: $e');}}- try {- HapticFeedback.heavyImpact();- } catch (_) {}+ if (style == 'loud') {+ try {+ HapticFeedback.heavyImpact();+ } catch (_) {}+ } else {+ await _buzz();+ }+ if (style == 'vibrate') return;final player = _player;if (player == null) return;try {+ await _applyAudioContext();await player.stop();await player.play(_source, volume: 1.0);} catch (e) {@@ -150,6 +250,7 @@ class RestAlarm {final player = _player;if (player == null) return;try {+ await _applyAudioContext();await player.stop();await player.play(_source, volume: 1.0);} catch (e) {@@ -201,7 +302,7 @@ class RestAlarm {title: t.restOverTitle,body: t.restOverBody,scheduledDate: tz.TZDateTime.now(tz.local).add(after),- notificationDetails: NotificationDetails(android: _android),+ notificationDetails: NotificationDetails(android: _android, iOS: _darwin),androidScheduleMode: AndroidScheduleMode.alarmClock,);} catch (e) {diff --git a/lib/state/workout_state.dart b/lib/state/workout_state.dartindex 93dbdaf..a21b46d 100644--- a/lib/state/workout_state.dart+++ b/lib/state/workout_state.dart@@ -3,6 +3,7 @@ part of 'fit_state.dart';mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsState, RoutinesState {final List<String> selectedMuscles = [];final Set<String> sessionPicks = {};+ final Set<String> pickSeed = {};String trainStep = 'select';WorkoutSession? session;Timer? _sessionTimer;@@ -10,7 +11,11 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStDateTime? _runningSince;int _elapsedBefore = 0;bool sessionPaused = false;+ bool sessionLocked = false;DateTime? logDay;+ int restDoneTick = 0;+ int restTotal = 0;+ int autoMoves = 0;void startWorkout([List<String>? initialMuscles, DateTime? on]) {logDay = on;@@ -27,6 +32,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStlogDay = on;selectedMuscles.clear();sessionPicks.clear();+ pickSeed.clear();trainStep = 'review';pushRoute('train');}@@ -54,6 +60,9 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStsessionPicks..clear()..addAll(_defaultPicks(selectedMuscles).map((e) => e.id));+ pickSeed+ ..clear()+ ..addAll(sessionPicks);notifyListeners();}@@ -61,7 +70,22 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal base = getFilteredExercises(selectedMuscles);final baseIds = base.map((e) => e.id).toSet();final extras = allExercises.where((e) => sessionPicks.contains(e.id) && !baseIds.contains(e.id));- return [...base, ...extras];+ final all = [...base, ...extras];+ return [+ ...all.where((e) => pickSeed.contains(e.id)),+ ...all.where((e) => !pickSeed.contains(e.id)),+ ];+ }++ bool suggests(String id) => !noSuggest.contains(id);++ void toggleSuggest(String id) {+ if (!noSuggest.remove(id)) {+ noSuggest.add(id);+ sessionPicks.remove(id);+ }+ _persist();+ notifyListeners();}List<Exercise> trainSearchResults(String query) {@@ -72,7 +96,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStstatic const _pickTarget = 6;List<Exercise> _defaultPicks(List<String> muscles) {- final pool = getFilteredExercises(muscles);+ final pool = getFilteredExercises(muscles).where((e) => suggests(e.id)).toList();if (pool.length <= _pickTarget) return pool;int rank(Exercise e) {@@ -104,6 +128,29 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStbool isPicked(String id) => sessionPicks.contains(id);+ void clearPicks() {+ sessionPicks.clear();+ notifyListeners();+ }++ void resetDefaultPicks() {+ sessionPicks+ ..clear()+ ..addAll(_defaultPicks(selectedMuscles).map((e) => e.id));+ pickSeed+ ..clear()+ ..addAll(sessionPicks);+ notifyListeners();+ }++ void toggleResetPicks() {+ if (sessionPicks.isNotEmpty) {+ clearPicks();+ } else {+ resetDefaultPicks();+ }+ }+void trainBack() {trainStep = 'select';notifyListeners();@@ -113,6 +160,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSttrainStep = 'select';selectedMuscles.clear();sessionPicks.clear();+ pickSeed.clear();logDay = null;popRoute();}@@ -122,6 +170,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStif (exs.isEmpty) return;_beginSession(exs,plan: {for (final ex in exs) ex.id: routineSets(r, ex.id)},+ planned: {for (final ex in exs) if (hasPlan(r, ex.id)) ex.id: plannedSets(r, ex.id)},chained: {for (final ex in exs) if (chainsToNext(r, ex.id)) ex.id},on: on);}@@ -131,16 +180,55 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStif (exs.isNotEmpty) _beginSession(exs, on: logDay);}- List<SessionSet> _openingSets(String id, {int? count}) {+ List<SessionSet> _fromPlan(String id, List<PlannedSet> planned) {+ final working = planned.where((p) => p.kind != SetKind.warmup).length;+ final base = _workingOpeners(id, count: working == 0 ? 1 : working);+ final first = base.isEmpty ? SessionSet(10, 0, false) : base.first;+ final warmWeight = fromDisplayWeight(_roundTo(toDisplayWeight(first.weight * 0.5), weightStep));+ final out = <SessionSet>[];+ var w = 0;+ for (final p in planned) {+ final warm = p.kind == SetKind.warmup;+ final b = warm || base.isEmpty ? first : base[(w++).clamp(0, base.length - 1)];+ out.add(SessionSet(+ p.reps ?? (warm ? 10 : b.reps),+ p.weightKg ?? (warm ? warmWeight : b.weight),+ false,+ kind: p.kind,+ sec: p.sec ?? b.sec,+ km: p.km ?? b.km,+ ));+ }+ return out;+ }++ List<SessionSet> _openingSets(String id, {int? count, List<PlannedSet>? planned}) {+ if (planned != null && planned.isNotEmpty) return _fromPlan(id, planned);final sets = _workingOpeners(id, count: count);- if (!warmsUp(id) || isRepsOnly(id)) return sets;+ if (!warmsUp(id) || isRepsOnly(id) || modeOf(id).isNotEmpty) return sets;return [..._warmupFor(sets), ...sets];}+ List<SessionSet> _modeOpeners(String mode, List<LoggedSet> last) {+ final cardio = mode == 'cardio';+ 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),+ ];+ if (fromLast.isNotEmpty) return fromLast;+ if (cardio) return [SessionSet(0, 0, false, sec: 1200, km: 0)];+ return [for (var i = 0; i < kDefaultRoutineSets; i++) SessionSet(0, 0, false, sec: 30)];+ }+List<SessionSet> _workingOpeners(String id, {int? count}) {final last = lastSetsFor(id).where((l) => l.counts).toList();+ final mode = modeOf(id);final List<SessionSet> base;- if (last.isNotEmpty) {+ if (mode.isNotEmpty) {+ base = _modeOpeners(mode, last);+ } else if (last.isNotEmpty) {final bump = _progressBump(id, last);base = last.map((l) => SessionSet(l.reps, l.weight + bump, false)).toList();} else {@@ -152,11 +240,12 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal fill = base.last;return [...base,- for (var i = base.length; i < count; i++) SessionSet(fill.reps, fill.weight, false),+ for (var i = base.length; i < count; i++) fill.copy(),];}({double weightKg, int reps, bool up})? nextTarget(String id) {+ if (modeOf(id).isNotEmpty) return null;final last = lastSetsFor(id).where((l) => l.counts).toList();if (last.isEmpty) return null;final reps = last.first.reps;@@ -186,7 +275,10 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}void _beginSession(List<Exercise> exs,- {Map<String, int>? plan, Set<String> chained = const {}, DateTime? on}) {+ {Map<String, int>? plan,+ Map<String, List<PlannedSet>> planned = const {},+ Set<String> chained = const {},+ DateTime? on}) {final s = WorkoutSession();if (on != null) {s.loggedAt = DateTime(on.year, on.month, on.day, 12);@@ -198,14 +290,16 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStex.id,ex.name,ex.primary,- _openingSets(ex.id, count: plan?[ex.id]),+ _openingSets(ex.id, count: plan?[ex.id], planned: planned[ex.id]),linkedNext: chained.contains(ex.id),)).toList();_restTimer?.cancel();_elapsedBefore = 0;sessionPaused = false;- _startTicking();+ sessionLocked = false;+ countdownUntil = startCountdown && !s.manual ? DateTime.now().add(countdownLength) : null;+ _startTicking(from: countdownUntil);session = s;route = 'session';persistNow();@@ -220,10 +314,30 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStint get sessionElapsed => _runningSince == null? _elapsedBefore- : _elapsedBefore + DateTime.now().difference(_runningSince!).inSeconds;+ : _elapsedBefore + math.max(0, DateTime.now().difference(_runningSince!).inSeconds);++ static const countdownLength = Duration(seconds: 5);++ DateTime? countdownUntil;++ bool get countingDown {+ final until = countdownUntil;+ return until != null && session != null && DateTime.now().isBefore(until);+ }++ void endCountdown() {+ final until = countdownUntil;+ if (until == null) return;+ countdownUntil = null;+ final now = DateTime.now();+ if (!sessionPaused && _runningSince != null && _runningSince!.isAfter(now)) _runningSince = now;+ persistNow();+ notifyListeners();+ }void toggleSessionPause() {final s = session;+ if (holding) stopHold();if (sessionPaused) {_startTicking();sessionPaused = false;@@ -245,6 +359,25 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStnotifyListeners();}+ void toggleSessionLock() {+ sessionLocked = !sessionLocked;+ notifyListeners();+ }++ void resumeSession() {+ final s = session;+ if (s == null || s.complete) return;+ resetRoute('session');+ notifyListeners();+ }++ void parkSession() {+ if (route != 'session') return;+ sessionLocked = false;+ resetRoute('home');+ notifyListeners();+ }+String get elapsedLabel {final e = sessionElapsed;return '${(e ~/ 60).toString().padLeft(2, '0')}:${(e % 60).toString().padLeft(2, '0')}';@@ -275,7 +408,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStreturn;}startRest();- if (autoAdvance) _advanceWhenDone(exIdx);+ if (autoAdvance || sessionLocked) _advanceWhenDone(exIdx);}List<int> chainAt(int exIdx) {@@ -306,34 +439,92 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}startRest();final left = chain.where((i) => s.exercises[i].hasUndone).toList();+ final next = pendingAfter(chain.last);if (left.isNotEmpty) {s.currentIndex = left.first;- } else if (autoAdvance && chain.last < s.exercises.length - 1) {- s.currentIndex = chain.last + 1;+ } else if ((autoAdvance || sessionLocked) && next != null) {+ s.currentIndex = next;+ autoMoves++;+ } else if (autoAdvance || sessionLocked) {+ _finishWhenAllDone();}_persist();notifyListeners();}+ int? pendingAfter(int exIdx) {+ final s = session;+ if (s == null) return null;+ final n = s.exercises.length;+ for (var k = 1; k < n; k++) {+ final i = (exIdx + k) % n;+ if (s.exercises[i].hasUndone) return i;+ }+ return null;+ }++ void goNextPending() {+ final s = session;+ if (s == null) return;+ final next = pendingAfter(s.currentIndex);+ if (next == null) {+ nextExercise();+ return;+ }+ goToExercise(next);+ }+static const advanceDelay = Duration(milliseconds: 900);Timer? _advanceTimer;void _advanceWhenDone(int exIdx) {final s = session;- if (s == null || exIdx != s.currentIndex || exIdx >= s.exercises.length - 1) return;+ if (s == null || exIdx != s.currentIndex) return;if (s.exercises[exIdx].sets.any((st) => !st.done)) return;+ if (pendingAfter(exIdx) == null) {+ _finishWhenAllDone();+ return;+ }_advanceTimer?.cancel();- _advanceTimer = Timer(advanceDelay, () {+ _advanceTimer = Timer(_waitForEffort(exIdx) ? effortDelay : advanceDelay, () {final live = session;if (live == null || live.currentIndex != exIdx) return;if (live.exercises[exIdx].sets.any((st) => !st.done)) return;- live.currentIndex = exIdx + 1;+ final next = pendingAfter(exIdx);+ if (next == null) return;+ live.currentIndex = next;+ autoMoves++;_persist();notifyListeners();});}+ static const finishDelay = Duration(milliseconds: 1500);++ static const effortDelay = Duration(milliseconds: 3500);++ bool _waitForEffort(int exIdx) {+ final s = session;+ if (!logRpe || s == null || exIdx < 0 || exIdx >= s.exercises.length) return false;+ final ex = s.exercises[exIdx];+ if (modeOf(ex.id) == 'cardio') return false;+ final last = ex.sets.lastIndexWhere((st) => st.done);+ return last >= 0 && ex.sets[last].counts && ex.sets[last].rpe == null;+ }++ void _finishWhenAllDone() {+ final s = session;+ if (s == null || s.manual || s.complete || s.exercises.any((e) => e.hasUndone)) return;+ _advanceTimer?.cancel();+ _advanceTimer = Timer(_waitForEffort(s.currentIndex) ? effortDelay : finishDelay, () {+ final live = session;+ if (live == null || live.complete || live.exercises.any((e) => e.hasUndone)) return;+ if (route != 'session') return;+ finishSession();+ });+ }+void startRest() {if (sessionPaused || session?.manual == true) return;_restTimer?.cancel();@@ -347,6 +538,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStreturn;}+ restTotal = seconds;_armRest(seconds);askAlarmPermission();notifyListeners();@@ -368,6 +560,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStif (live.restRemaining == null) {live.clearRest();t.cancel();+ restDoneTick++;RestAlarm.instance.fireNow();}notifyListeners();@@ -383,6 +576,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSts.clearRest();RestAlarm.instance.cancel();} else if (!(_restTimer?.isActive ?? false)) {+ restTotal = math.max(restTotal, left);_armRest(left);} else {return;@@ -394,7 +588,9 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal s = session;final left = s?.restRemaining;if (s == null || left == null) return;- _armRest((left + seconds).clamp(5, 600));+ final next = (left + seconds).clamp(5, 600);+ restTotal = math.max(next, restTotal + (next - left));+ _armRest(next);notifyListeners();}@@ -407,9 +603,202 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}void addSet(int exIdx) {- final sets = session!.exercises[exIdx].sets;- final last = sets.isNotEmpty ? sets.last : SessionSet(10, 20, false);- sets.add(SessionSet(last.reps, last.weight, false, kind: last.kind));+ final ex = session!.exercises[exIdx];+ final sets = ex.sets;+ if (sets.isEmpty) {+ final mode = modeOf(ex.id);+ sets.add(mode.isEmpty+ ? SessionSet(10, isRepsOnly(ex.id) ? 0 : 20, false)+ : _modeOpeners(mode, const []).first);+ } else {+ final last = sets.last;+ sets.add(SessionSet(last.reps, last.weight, false, kind: last.kind, sec: last.sec, km: last.km));+ }+ _persist();+ notifyListeners();+ }++ void setSessionSeconds(int exIdx, int setIdx, int sec) {+ _carry(exIdx, setIdx, (st) => st.sec, (st, v) => st.sec = v, sec.clamp(0, 24 * 3600));+ _persist();+ notifyListeners();+ }++ void bumpSessionSeconds(int exIdx, int setIdx, int delta) {+ final st = session!.exercises[exIdx].sets[setIdx];+ final now = st.sec ?? 0;+ final step = delta.abs();+ final snapped = ((now / step).round() * step) + delta;+ setSessionSeconds(exIdx, setIdx, snapped < 0 ? 0 : snapped);+ }++ void setSessionKm(int exIdx, int setIdx, double km) {+ _carry(exIdx, setIdx, (st) => st.km, (st, v) => st.km = v, _round3(km.clamp(0, 1000)));+ _persist();+ notifyListeners();+ }++ void setSessionDistanceShown(int exIdx, int setIdx, double shown) =>+ setSessionKm(exIdx, setIdx, fromDisplayKm(shown));++ void bumpSessionDistance(int exIdx, int setIdx, int dir) {+ final st = session!.exercises[exIdx].sets[setIdx];+ final shown = toDisplayKm(st.km ?? 0);+ final next = ((shown / distanceStep).round() + dir) * distanceStep;+ setSessionDistanceShown(exIdx, setIdx, next < 0 ? 0 : next);+ }++ DateTime? holdEndsAt;+ DateTime? holdStartsAt;+ int holdEx = -1;+ int holdSet = -1;+ Timer? _holdTimer;++ static const holdLeadIn = 5;++ static int _secondsUntil(DateTime? at) {+ if (at == null) return 0;+ final left = at.difference(DateTime.now()).inMilliseconds;+ return left <= 0 ? 0 : (left / 1000).ceil();+ }++ int get holdLead => _secondsUntil(holdStartsAt);++ int? get holdRemaining {+ final end = holdEndsAt;+ if (end == null) return null;+ return math.min(_secondsUntil(end), holdTotal);+ }++ bool get holding => holdEndsAt != null;++ int holdTotal = 0;++ ({int done, int total}) get sessionSetCount {+ final s = session;+ if (s == null) return (done: 0, total: 0);+ var done = 0, total = 0;+ for (final e in s.exercises) {+ for (final st in e.sets) {+ if (!st.counts) continue;+ total++;+ if (st.done) done++;+ }+ }+ return (done: done, total: total);+ }++ void startHold(int exIdx, int setIdx) {+ final s = session;+ if (s == null || exIdx >= s.exercises.length) return;+ final sets = s.exercises[exIdx].sets;+ if (setIdx < 0 || setIdx >= sets.length) return;+ final secs = (sets[setIdx].sec ?? 30).clamp(1, 3600);+ if (s.restRemaining != null) skipRest();+ holdEx = exIdx;+ holdSet = setIdx;+ holdTotal = secs;+ final now = DateTime.now();+ holdStartsAt = now.add(const Duration(seconds: holdLeadIn));+ holdEndsAt = holdStartsAt!.add(Duration(seconds: secs));+ _holdTimer?.cancel();+ final sound = alarmStyle != 'vibrate';+ var shownLead = holdLead;+ var shown = holdRemaining;+ _holdTimer = Timer.periodic(const Duration(milliseconds: 100), (_) {+ final lead = holdLead;+ final left = holdRemaining;+ if (left == 0) {+ Beeper.instance.go(sound: sound);+ _finishHold();+ return;+ }+ if (lead != shownLead) {+ shownLead = lead;+ if (lead == 0) {+ Beeper.instance.go(sound: sound);+ } else if (lead <= 3) {+ Beeper.instance.tick(sound: sound);+ }+ notifyListeners();+ } else if (left != shown) {+ shown = left;+ if (lead == 0 && left != null && left <= 3) Beeper.instance.tick(sound: sound);+ notifyListeners();+ }+ });+ notifyListeners();+ }++ void stopHold() {+ _holdTimer?.cancel();+ _holdTimer = null;+ holdEndsAt = null;+ holdStartsAt = null;+ holdEx = -1;+ holdSet = -1;+ notifyListeners();+ }++ void _finishHold() {+ final exIdx = holdEx, setIdx = holdSet;+ stopHold();+ 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 || sets[setIdx].done) return;+ toggleSet(exIdx, setIdx);+ }++ SessionSet? removeSet(int exIdx, int setIdx) {+ final s = session;+ if (s == null || exIdx < 0 || exIdx >= s.exercises.length) return null;+ final sets = s.exercises[exIdx].sets;+ if (setIdx < 0 || setIdx >= sets.length) return null;+ final gone = sets.removeAt(setIdx);+ _persist();+ notifyListeners();+ return gone;+ }++ void insertSet(int exIdx, int setIdx, SessionSet set) {+ final s = session;+ if (s == null || exIdx < 0 || exIdx >= s.exercises.length) return;+ final sets = s.exercises[exIdx].sets;+ sets.insert(setIdx.clamp(0, sets.length), set);+ _persist();+ notifyListeners();+ }++ void removeWarmupSets(int exIdx) {+ final s = session;+ if (s == null || exIdx < 0 || exIdx >= s.exercises.length) return;+ s.exercises[exIdx].sets.removeWhere((st) => st.kind == SetKind.warmup && !st.done);+ _persist();+ notifyListeners();+ }++ void goToExercise(int i) {+ final s = session;+ if (s == null || i < 0 || i >= s.exercises.length || i == s.currentIndex) return;+ _advanceTimer?.cancel();+ s.currentIndex = i;+ _persist();+ notifyListeners();+ }++ void reorderSessionExercise(int from, int to) {+ final s = session;+ if (s == null || from < 0 || from >= s.exercises.length) return;+ if (to > from) to -= 1;+ to = to.clamp(0, s.exercises.length - 1);+ if (to == from) return;+ final current = s.exercises[s.currentIndex];+ if (from > 0) s.exercises[from - 1].linkedNext = false;+ final moved = s.exercises.removeAt(from)..linkedNext = false;+ s.exercises.insert(to, moved);+ if (to > 0) s.exercises[to - 1].linkedNext = false;+ s.currentIndex = s.exercises.indexOf(current);_persist();notifyListeners();}@@ -449,6 +838,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStvoid addWarmupSets(int exIdx) {final s = session;if (s == null || exIdx >= s.exercises.length) return;+ if (modeOf(s.exercises[exIdx].id).isNotEmpty) return;final sets = s.exercises[exIdx].sets;if (hasWarmup(exIdx)) return;final warm = _warmupFor(sets);@@ -466,6 +856,9 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStsets[setIdx].rpe = rpe;_persist();notifyListeners();+ if (rpe != null && sets[setIdx].done && (autoAdvance || sessionLocked) && _advanceTimer?.isActive == true) {+ _advanceWhenDone(exIdx);+ }}void setSetKind(int exIdx, int setIdx, SetKind kind) {@@ -479,17 +872,30 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}void setSessionReps(int exIdx, int setIdx, int reps) {- session!.exercises[exIdx].sets[setIdx].reps = reps.clamp(0, 999);+ _carry(exIdx, setIdx, (st) => st.reps, (st, v) => st.reps = v, reps.clamp(0, 999));_persist();notifyListeners();}void setSessionWeight(int exIdx, int setIdx, double kg) {- session!.exercises[exIdx].sets[setIdx].weight = _round3(kg.clamp(0, 1000));+ _carry(exIdx, setIdx, (st) => st.weight, (st, v) => st.weight = v, _round3(kg.clamp(0, 1000)));_persist();notifyListeners();}+ void _carry<T>(int exIdx, int setIdx, T Function(SessionSet) read, void Function(SessionSet, T) write, T value) {+ final sets = session!.exercises[exIdx].sets;+ final st = sets[setIdx];+ final before = read(st);+ write(st, value);+ if (before == value) return;+ for (var j = setIdx + 1; j < sets.length; j++) {+ final later = sets[j];+ if (later.done || later.kind != st.kind || read(later) != before) break;+ write(later, value);+ }+ }+void setSessionWeightShown(int exIdx, int setIdx, double shown) =>setSessionWeight(exIdx, setIdx, fromDisplayWeight(shown));@@ -553,6 +959,8 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}void finishSession() {+ _holdTimer?.cancel();+ holdEndsAt = null;_advanceTimer?.cancel();_sessionTimer?.cancel();_restTimer?.cancel();@@ -572,14 +980,12 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSts.summaryDuration = s.manual ? _elapsedBefore : sessionElapsed;s.complete = true;s.clearRest();+ sessionLocked = false;if (done.isNotEmpty) {final logged = <LoggedExercise>[];for (final e in s.exercises) {- final doneSets = e.sets- .where((st) => st.done)- .map((st) => LoggedSet(st.reps, st.weight, kind: st.kind, rpe: st.rpe))- .toList();+ final doneSets = e.sets.where((st) => st.done).map((st) => st.logged).toList();if (doneSets.isNotEmpty) {logged.add(LoggedExercise(e.id, e.name, e.primary, doneSets));}@@ -606,8 +1012,18 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfor (final ex in s.exercises) {if (exerciseById(ex.id) == null) continue;toggleRoutineExercise(id, ex.id);- final working = ex.sets.where((st) => st.kind != SetKind.warmup).length;- bumpRoutineSets(id, ex.id, working - kDefaultRoutineSets);+ if (ex.linkedNext) toggleChain(id, ex.id);+ if (ex.sets.isEmpty) continue;+ setPlannedSets(id, ex.id, [+ for (final st in ex.sets)+ PlannedSet(+ reps: modeOf(ex.id).isEmpty ? st.reps : null,+ weightKg: st.weight > 0 ? st.weight : null,+ kind: st.kind,+ sec: st.sec,+ km: st.km,+ ),+ ]);}persistNow();notifyListeners();@@ -650,12 +1066,19 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt..loggedAt = ls.date..manual = _dayKey(ls.date) != _dayKey(DateTime.now())..exercises = ls.exercises- .map((e) => SessionExercise(e.id, e.name, e.primary,- e.sets.map((x) => SessionSet(x.reps, x.weight, true)).toList()))+ .map((e) => SessionExercise(+ e.id,+ e.name,+ e.primary,+ e.sets+ .map((x) => SessionSet(x.reps, x.weight, true,+ kind: x.kind, rpe: x.rpe, sec: x.sec, km: x.km))+ .toList())).toList();_restTimer?.cancel();_elapsedBefore = ls.durationSec;sessionPaused = false;+ sessionLocked = false;_startTicking();session = s;resetRoute('session');@@ -670,6 +1093,10 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt}void saveAndExit() {+ _holdTimer?.cancel();+ holdEndsAt = null;+ holdEx = -1;+ holdSet = -1;_advanceTimer?.cancel();_sessionTimer?.cancel();_restTimer?.cancel();@@ -677,9 +1104,11 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt_runningSince = null;_elapsedBefore = 0;sessionPaused = false;+ sessionLocked = false;session = null;selectedMuscles.clear();sessionPicks.clear();+ pickSeed.clear();trainStep = 'select';logDay = null;resetRoute('home');diff --git a/lib/widgets/set_kind.dart b/lib/widgets/set_kind.dartnew file mode 100644index 0000000..f75c1e0--- /dev/null+++ b/lib/widgets/set_kind.dart@@ -0,0 +1,29 @@+import 'package:flutter/material.dart';++import '../l10n/l10n.dart';+import '../models/workout.dart';+import '../theme/app_colors.dart';++Color setKindColor(GymColors gc, SetKind kind) => switch (kind) {+ SetKind.warmup => gc.warn,+ SetKind.drop => gc.info,+ SetKind.failure => gc.danger,+ SetKind.restPause => gc.brass,+ SetKind.normal => gc.text,+ };++String setKindLabel(SetKind kind) => switch (kind) {+ SetKind.warmup => t.setTypeWarmup,+ SetKind.drop => t.setTypeDrop,+ SetKind.failure => t.setTypeFailure,+ SetKind.restPause => t.setTypeRestPause,+ SetKind.normal => t.setTypeNormal,+ };++String setKindTag(SetKind kind) => switch (kind) {+ SetKind.warmup => 'W',+ SetKind.drop => 'D',+ SetKind.failure => 'F',+ SetKind.restPause => 'RP',+ SetKind.normal => '',+ };diff --git a/lib/widgets/start_countdown.dart b/lib/widgets/start_countdown.dartnew file mode 100644index 0000000..3ec6f5e--- /dev/null+++ b/lib/widgets/start_countdown.dart@@ -0,0 +1,145 @@+import 'dart:async';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../l10n/l10n.dart';+import '../state/fit_state.dart';+import '../theme/app_colors.dart';+import '../theme/app_theme.dart';++class StartCountdown extends StatefulWidget {+ const StartCountdown({super.key, required this.until});++ final DateTime until;++ @override+ State<StartCountdown> createState() => _StartCountdownState();+}++class _StartCountdownState extends State<StartCountdown> with TickerProviderStateMixin {+ late final AnimationController _beat =+ AnimationController(vsync: this, duration: const Duration(milliseconds: 1000));+ late final AnimationController _veil =+ AnimationController(vsync: this, duration: const Duration(milliseconds: 280))..forward();+ Timer? _tick;+ int _left = 0;+ bool _leaving = false;++ int get _remaining {+ final ms = widget.until.difference(DateTime.now()).inMilliseconds;+ return ms <= 0 ? 0 : (ms / 1000).ceil();+ }++ @override+ void initState() {+ super.initState();+ _left = _remaining;+ _step();+ }++ void _step() {+ if (!mounted) return;+ final left = _remaining;+ if (left <= 0) {+ _finish();+ return;+ }+ if (left != _left || _beat.value == 0) {+ _left = left;+ HapticFeedback.mediumImpact();+ _beat.forward(from: 0);+ setState(() {});+ }+ final ms = widget.until.difference(DateTime.now()).inMilliseconds % 1000;+ _tick = Timer(Duration(milliseconds: ms <= 0 ? 1000 : ms + 5), _step);+ }++ Future<void> _finish() async {+ if (_leaving) return;+ _leaving = true;+ _tick?.cancel();+ HapticFeedback.heavyImpact();+ await _veil.reverse();+ fit.endCountdown();+ }++ @override+ void dispose() {+ _tick?.cancel();+ _beat.dispose();+ _veil.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final first = fit.currentExercise;+ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: _finish,+ child: Material(+ type: MaterialType.transparency,+ child: AnimatedBuilder(+ animation: Listenable.merge([_beat, _veil]),+ builder: (context, _) {+ final veil = Curves.easeOut.transform(_veil.value);+ final b = _beat.value;+ final pop = Curves.easeOutBack.transform((b / 0.45).clamp(0.0, 1.0));+ final fade = b < 0.7 ? 1.0 : 1 - Curves.easeIn.transform((b - 0.7) / 0.3);+ return Stack(+ fit: StackFit.expand,+ children: [+ BackdropFilter(+ filter: ui.ImageFilter.blur(sigmaX: 22 * veil, sigmaY: 22 * veil),+ child: ColoredBox(color: gc.bg.withValues(alpha: 0.72 * veil)),+ ),+ Opacity(+ opacity: veil,+ child: SafeArea(+ child: Column(+ children: [+ const Spacer(flex: 3),+ Text(t.countdownReady.toUpperCase(),+ style: AppTheme.f(13, weight: FontWeight.w800, color: gc.textSecondary, letterSpacing: 3)),+ const SizedBox(height: 18),+ SizedBox(+ height: 200,+ child: Center(+ child: Opacity(+ opacity: fade.clamp(0.0, 1.0),+ child: Transform.scale(+ scale: 1.5 - 0.5 * pop,+ child: Text('$_left',+ style: AppTheme.f(170, weight: FontWeight.w900, color: gc.text, height: 1)),+ ),+ ),+ ),+ ),+ const SizedBox(height: 14),+ if (first != null)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 32),+ child: Text(t.catalogName(first.id, first.name),+ textAlign: TextAlign.center,+ maxLines: 2,+ style: AppTheme.f(20, weight: FontWeight.w800, color: gc.text)),+ ),+ const Spacer(flex: 4),+ Text(t.countdownSkip,+ style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.textTertiary)),+ const SizedBox(height: 28),+ ],+ ),+ ),+ ),+ ],+ );+ },+ ),+ ),+ );+ }+}diff --git a/lib/widgets/timer_panel.dart b/lib/widgets/timer_panel.dartnew file mode 100644index 0000000..441d1fc--- /dev/null+++ b/lib/widgets/timer_panel.dart@@ -0,0 +1,190 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../theme/app_colors.dart';+import '../theme/app_theme.dart';+import 'rolling_text.dart';++String clockLabel(int seconds) {+ final s = seconds < 0 ? 0 : seconds;+ return '${s ~/ 60}:${(s % 60).toString().padLeft(2, '0')}';+}++class TimerPanel extends StatelessWidget {+ const TimerPanel({+ super.key,+ required this.label,+ required this.remaining,+ required this.total,+ required this.elapsed,+ required this.elapsedLabel,+ required this.sets,+ required this.setsLabel,+ required this.hint,+ required this.onTap,+ this.onMinus,+ this.onPlus,+ this.color,+ });++ final String label;+ final int remaining;+ final int total;+ final String elapsed;+ final String elapsedLabel;+ final String sets;+ final String setsLabel;+ final String hint;+ final VoidCallback onTap;+ final VoidCallback? onMinus;+ final VoidCallback? onPlus;+ final Color? color;++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final accent = color ?? gc.sage;+ final left = total <= 0 ? 0.0 : (remaining / total).clamp(0.0, 1.0);+ return Semantics(+ button: true,+ label: '$label ${clockLabel(remaining)}',+ hint: hint,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.lightImpact();+ onTap();+ },+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SizedBox(+ height: 40,+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ _nudge(gc, '−15', onMinus),+ Expanded(+ child: Container(+ height: 40,+ margin: const EdgeInsets.symmetric(horizontal: 10),+ padding: const EdgeInsets.only(top: 9),+ alignment: Alignment.topCenter,+ decoration: BoxDecoration(+ color: gc.bgRaised2,+ borderRadius: const BorderRadius.vertical(top: Radius.circular(18)),+ ),+ child: Text(label.toUpperCase(),+ style: AppTheme.f(11, weight: FontWeight.w800, color: gc.text, letterSpacing: 2)),+ ),+ ),+ _nudge(gc, '+15', onPlus),+ ],+ ),+ ),+ Container(+ padding: const EdgeInsets.fromLTRB(18, 16, 18, 14),+ decoration: BoxDecoration(+ color: gc.bgRaised,+ borderRadius: BorderRadius.circular(26),+ border: Border.all(color: gc.border.withValues(alpha: 0.5)),+ ),+ child: Column(+ children: [+ _Ticks(left: left, lit: accent, dim: gc.bgRaised2),+ const SizedBox(height: 14),+ Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ Expanded(child: _stat(gc, elapsed, elapsedLabel, CrossAxisAlignment.start)),+ Column(+ children: [+ RollingText(clockLabel(remaining),+ countsDown: true,+ style: AppTheme.f(36, weight: FontWeight.w800, color: gc.text, height: 1.05)),+ const SizedBox(height: 4),+ Text(hint.toUpperCase(),+ style: AppTheme.f(10, weight: FontWeight.w800, color: accent, letterSpacing: 1.6)),+ ],+ ),+ Expanded(child: _stat(gc, sets, setsLabel, CrossAxisAlignment.end)),+ ],+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }++ Widget _stat(GymColors gc, String value, String caption, CrossAxisAlignment align) => Column(+ crossAxisAlignment: align,+ children: [+ RollingText(value, style: AppTheme.f(19, weight: FontWeight.w800, color: gc.text, height: 1.1)),+ const SizedBox(height: 3),+ Text(caption.toUpperCase(),+ style: AppTheme.f(9.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.5)),+ ],+ );++ Widget _nudge(GymColors gc, String glyph, VoidCallback? onTap) {+ if (onTap == null) return const SizedBox(width: 56);+ return Semantics(+ button: true,+ label: glyph,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.selectionClick();+ onTap();+ },+ child: Container(+ width: 56,+ height: 32,+ margin: const EdgeInsets.only(bottom: 4),+ alignment: Alignment.center,+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(100)),+ child: Text(glyph, style: AppTheme.f(12.5, weight: FontWeight.w800, color: gc.textSecondary)),+ ),+ ),+ );+ }+}++class _Ticks extends StatelessWidget {+ const _Ticks({required this.left, required this.lit, required this.dim});++ final double left;+ final Color lit;+ final Color dim;++ @override+ Widget build(BuildContext context) {+ return LayoutBuilder(builder: (context, box) {+ const tick = 3.0, gap = 5.5;+ final n = ((box.maxWidth + gap) / (tick + gap)).floor();+ final drained = ((1 - left) * n).floor();+ return SizedBox(+ height: 22,+ child: Row(+ mainAxisAlignment: MainAxisAlignment.spaceBetween,+ children: [+ for (var i = 0; i < n; i++)+ AnimatedContainer(+ duration: const Duration(milliseconds: 380),+ curve: Curves.easeOut,+ width: tick,+ height: i < drained ? 14 : 22,+ decoration: BoxDecoration(+ color: i < drained ? dim : lit,+ borderRadius: BorderRadius.circular(2),+ ),+ ),+ ],+ ),+ );+ });+ }+}diff --git a/test/exercise_notes_test.dart b/test/exercise_notes_test.dartindex f807664..36e71ff 100644--- a/test/exercise_notes_test.dart+++ b/test/exercise_notes_test.dart@@ -25,6 +25,7 @@ void main() {late String exId;Future<void> tapVisible(WidgetTester tester, Finder f) async {+ await tester.pumpAndSettle();await tester.ensureVisible(f);await tester.pumpAndSettle();await tester.tap(f);diff --git a/test/requests_18sep_test.dart b/test/requests_18sep_test.dartnew file mode 100644index 0000000..7d7122e--- /dev/null+++ b/test/requests_18sep_test.dart@@ -0,0 +1,424 @@+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/models/exercise.dart';+import 'package:gymmane/models/live_session.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/plan_share.dart';+import 'package:gymmane/services/rest_alarm.dart';+import 'package:gymmane/services/workout_import.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');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineWith(List<String> ids, {String name = 'Push'}) {+ final id = fit.createRoutine(name);+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ group('sets inside a live workout', () {+ test('changing a set carries over to the sets that still match it', () {+ final r = routineWith([idOf('Barbell Bench Press')]);+ fit.startRoutine(r);+ final sets = fit.session!.exercises.first.sets;+ for (var j = 0; j < sets.length; j++) {+ fit.setSessionWeight(0, j, 60);+ fit.setSessionReps(0, j, 10);+ }+ fit.setSessionWeight(0, sets.length - 1, 70);++ fit.setSessionWeight(0, 0, 62.5);+ fit.setSessionReps(0, 0, 8);+ expect(sets.first.weight, 62.5);+ for (var j = 1; j < sets.length - 1; j++) {+ expect(sets[j].weight, 62.5);+ expect(sets[j].reps, 8);+ }+ expect(sets.last.weight, 70);+ expect(sets.last.reps, 8);+ });++ test('a set can be removed and brought back', () {+ final r = routineWith([idOf('Barbell Bench Press')]);+ fit.startRoutine(r);+ final sets = fit.session!.exercises.single.sets;+ final before = sets.length;+ final gone = fit.removeSet(0, 1)!;+ expect(sets.length, before - 1);+ fit.insertSet(0, 1, gone);+ expect(sets.length, before);+ expect(identical(sets[1], gone), isTrue);+ });++ test('a warm-up added by mistake goes away in one tap', () {+ final r = routineWith([idOf('Barbell Bench Press')]);+ fit.startRoutine(r);+ final working = fit.session!.exercises.single.sets.length;+ fit.addWarmupSets(0);+ expect(fit.hasWarmup(0), isTrue);+ fit.removeWarmupSets(0);+ expect(fit.hasWarmup(0), isFalse);+ expect(fit.session!.exercises.single.sets.length, working);+ });++ test('jumping and reordering keep the exercise you are on', () {+ final ids = [idOf('Barbell Bench Press'), idOf('Barbell Full Squat'), idOf('Pull Up')];+ final r = routineWith(ids);+ fit.toggleChain(r.id, ids[0]);+ fit.startRoutine(r);+ fit.goToExercise(1);+ expect(fit.currentExercise!.id, ids[1]);+ fit.reorderSessionExercise(2, 0);+ expect(fit.session!.exercises.first.id, ids[2]);+ expect(fit.currentExercise!.id, ids[1]);+ expect(fit.session!.exercises.every((e) => !e.linkedNext || e.id != ids[2]), isTrue);+ });+ });++ group('suggestions', () {+ test('an exercise switched off never lands in the picks but stays searchable', () {+ fit.selectedMuscles+ ..clear()+ ..add('chest');+ fit.trainContinue();+ final first = fit.sessionPicks.first;+ fit.toggleSuggest(first);+ fit.trainContinue();+ expect(fit.sessionPicks.contains(first), isFalse);+ expect(fit.trainSearchResults(fit.exerciseById(first)!.name).map((e) => e.id), contains(first));+ expect(fit.recommendedExercises(20).map((e) => e.id), isNot(contains(first)));+ });++ test('the suggested picks come first in the review list', () {+ fit.selectedMuscles+ ..clear()+ ..addAll(['chest', 'triceps']);+ fit.trainContinue();+ final list = fit.reviewExercises();+ final seeded = list.take(fit.pickSeed.length).map((e) => e.id).toSet();+ expect(seeded, fit.pickSeed);+ });++ test('hidden exercises survive a restart', () {+ fit.toggleSuggest(idOf('Barbell Bench Press'));+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.suggests(idOf('Barbell Bench Press')), isFalse);+ });+ });++ group('your own exercises', () {+ test('a catalogue id starting with c is not taken for yours', () {+ expect(fit.isCustom('cycling'), isFalse);+ final mine = fit.addCustomExercise(name: 'Cable thing', primary: 'chest', equipment: 'Barbell');+ expect(fit.isCustom(mine), isTrue);+ });++ test('yours always show up, whatever place is active', () {+ final mine = fit.addCustomExercise(name: 'Mi press raro', primary: 'chest', equipment: 'Barbell');+ final home = fit.addPresetPlace('home');+ fit.setActivePlace(home);+ expect(fit.exercisesMatching('raro').map((e) => e.id), contains(mine));+ });++ test('steps and type travel through a save and back', () {+ final mine = fit.addCustomExercise(+ name: 'Row a la valla',+ primary: 'back',+ equipment: 'Other',+ steps: ['1. Grab the rail', '- Pull', '', 'Lower slowly'],+ mode: 'time',+ );+ final ex = fit.exerciseById(mine)!;+ expect(ex.steps, ['Grab the rail', 'Pull', 'Lower slowly']);+ expect(ex.mode, 'time');+ final back = Exercise.fromJson(ex.toJson());+ expect(back.steps, ex.steps);+ expect(back.mode, 'time');+ fit.updateCustomExercise(mine,+ name: 'Row', primary: 'back', equipment: 'Other', difficulty: 'Beginner', steps: ['Only'], mode: '');+ expect(fit.exerciseById(mine)!.steps, ['Only']);+ expect(fit.modeOf(mine), '');+ });+ });++ group('cardio and timed work', () {+ test('a run opens with time and distance, and remembers them', () {+ final run = idOf('Outdoor Run');+ expect(fit.modeOf(run), 'cardio');+ expect(fit.restFor(run), 0);+ final r = routineWith([run]);+ expect(fit.routineSets(r, run), 1);+ fit.startRoutine(r);+ final st = fit.session!.exercises.single.sets.single;+ expect(st.sec, 1200);+ fit.setSessionKm(0, 0, 5.2);+ fit.setSessionSeconds(0, 0, 1800);+ fit.toggleSet(0, 0);+ fit.finishSession();+ fit.saveAndExit();+ final logged = fit.lastSetsFor(run).single;+ expect(logged.km, 5.2);+ expect(fit.loggedSetLabel(logged), '5.2 km · 30:00');+ fit.startRoutine(r);+ expect(fit.session!.exercises.single.sets.single.km, 5.2);+ expect(fit.nextTarget(run), isNull);+ });++ test('miles show for imperial users', () {+ fit.setUnits('lb');+ expect(fit.distanceLabel(1.609344), '1 mi');+ fit.setUnits('kg');+ });++ test('a plank opens with seconds and the hold can start and stop', () {+ final plank = idOf('Plank');+ expect(fit.modeOf(plank), 'time');+ fit.startRoutine(routineWith([plank]));+ final sets = fit.session!.exercises.single.sets;+ expect(sets.first.sec, 30);+ fit.startHold(0, 0);+ expect(fit.holding, isTrue);+ expect(fit.holdRemaining, 30);+ expect(fit.holdLead, inInclusiveRange(4, 5));+ fit.stopHold();+ expect(fit.holding, isFalse);+ expect(sets.first.done, isFalse);+ });++ test('how an exercise is logged can be changed and changed back', () {+ final rope = idOf('Jump Rope');+ expect(fit.modeOf(rope), 'time');+ fit.setExerciseMode(rope, '');+ expect(fit.modeOf(rope), '');+ fit.setExerciseMode(rope, 'time');+ expect(fit.modeOverride.containsKey(rope), isFalse);+ });++ test('timed and cardio sets keep their fields through json', () {+ final s = SessionSet(0, 20, true, sec: 45, km: null, kind: SetKind.restPause);+ final back = SessionSet.fromJson(s.toJson());+ expect(back.sec, 45);+ expect(back.kind, SetKind.restPause);+ final l = LoggedSet.fromJson(LoggedSet(0, 0, sec: 600, km: 2.5).toJson());+ expect(l.km, 2.5);+ expect(l.oneRm, 0);+ });+ });++ group('planned routines', () {+ test('planned sets open the workout with their type, reps and weight', () {+ final bench = idOf('Barbell Bench Press');+ final r = routineWith([bench]);+ fit.setPlannedSets(r.id, bench, const [+ PlannedSet(reps: 12, weightKg: 30, kind: SetKind.warmup),+ PlannedSet(reps: 8, weightKg: 70),+ PlannedSet(reps: 6, weightKg: 75, kind: SetKind.drop),+ ]);+ expect(fit.routineSets(r, bench), 2);+ fit.startRoutine(r);+ final sets = fit.session!.exercises.single.sets;+ expect(sets.map((s) => s.kind), [SetKind.warmup, SetKind.normal, SetKind.drop]);+ expect(sets.map((s) => s.reps), [12, 8, 6]);+ expect(sets.map((s) => s.weight), [30, 70, 75]);+ });++ test('the set stepper grows and shrinks the plan, never below one working set', () {+ final bench = idOf('Barbell Bench Press');+ final r = routineWith([bench]);+ fit.setPlannedSets(r.id, bench, const [+ PlannedSet(kind: SetKind.warmup),+ PlannedSet(reps: 5, weightKg: 100),+ ]);+ fit.bumpRoutineSets(r.id, bench, 2);+ expect(fit.routineSets(r, bench), 3);+ expect(fit.plannedSets(r, bench).last.weightKg, 100);+ fit.bumpRoutineSets(r.id, bench, -5);+ expect(fit.routineSets(r, bench), 1);+ expect(fit.plannedSets(r, bench).first.kind, SetKind.warmup);+ });++ test('a finished workout saved as routine keeps its sets and supersets', () {+ final ids = [idOf('Barbell Bench Press'), idOf('Barbell Bent Over Row')];+ final r = routineWith(ids);+ fit.toggleChain(r.id, ids.first);+ fit.startRoutine(r);+ fit.setSessionWeight(0, 0, 62.5);+ final saved = fit.saveSessionAsRoutine();+ final made = fit.routines.firstWhere((x) => x.id == saved);+ expect(made.chained, contains(ids.first));+ expect(fit.plannedSets(made, ids.first).first.weightKg, 62.5);+ });+ });++ group('reading plans', () {+ test('an AI plan with weeks, days, reps, weight and supersets', () {+ final plans = parsePlan('Here you go!\n```json\n'+ '{"program": "Base", "unit": "lb", "weeks": ['+ '{"name": "Week 1", "routines": [{"name": "A", "days": ["Monday", "jue"], "exercises": ['+ '{"name": "Barbell Bench Press", "sets": 3, "reps": "8-10", "weight": 135, "rest": "2 min", "superset": true},'+ '{"name": "Barbell Bent Over Row", "sets": 3, "reps": 8}]}]},'+ '{"name": "Week 2", "routines": [{"name": "A", "exercises": ["Pull Up"]}]}]}\n```');+ expect(plans.length, 2);+ expect(plans.first.group, 'Base · Week 1');+ expect(plans.first.days, [1, 4]);+ final bench = plans.first.items.first;+ expect(bench.reps, 8);+ expect(bench.weightKg, closeTo(61.2, 0.1));+ expect(bench.restSec, 120);+ expect(bench.superset, isTrue);+ expect(plans.last.group, 'Base · Week 2');+ });++ test('a csv plan', () {+ final plans = parsePlan('routine;exercise;sets;reps;weight\n'+ 'Push;Barbell Bench Press;4;8;60\nPush;Push Up;3;15;\nLegs;Barbell Full Squat;5;5;100');+ expect(plans.map((p) => p.name), ['Push', 'Legs']);+ expect(plans.first.items.first.weightKg, 60);+ expect(plans.last.items.single.sets, 5);+ });++ test('prose with commas is not taken for a plan', () {+ expect(parsePlan('Sure, here is your routine, enjoy it'), isEmpty);+ });++ test('importing builds planned sets, supersets and the week, once', () {+ final text = '{"routines": [{"name": "Upper", "days": [2], "exercises": ['+ '{"name": "Barbell Bench Press", "sets": 2, "reps": 8, "weight": 60, "superset": true,'+ ' "plan": [{"type": "warmup", "reps": 10, "weight": 30}]},'+ '{"name": "Barbell Bent Over Row", "sets": 3}]}]}';+ final plans = parsePlan(text);+ final first = fit.applyPlan(plans, schedule: true);+ expect(first.routines, 1);+ final r = fit.routines.single;+ final bench = idOf('Barbell Bench Press');+ expect(fit.plannedSets(r, bench).map((p) => p.kind), [SetKind.warmup, SetKind.normal, SetKind.normal]);+ expect(fit.routineSets(r, bench), 2);+ expect(fit.routineSets(r, idOf('Barbell Bent Over Row')), 3);+ expect(r.chained, contains(bench));+ expect(fit.weeklyPlan[2], r.id);+ final again = fit.applyPlan(plans);+ expect(again.routines, 0);+ expect(fit.routines.length, 1);+ });++ test('a shared plan round-trips to another phone, custom exercises included', () {+ final mine = fit.addCustomExercise(+ name: 'Landmine Twist', primary: 'obliques', equipment: 'Barbell', steps: ['Twist']);+ final bench = idOf('Barbell Bench Press');+ final r = routineWith([bench, mine], name: 'Mixed');+ fit.setRoutineGroup(r.id, 'Couple');+ fit.setPlannedSets(r.id, bench, const [PlannedSet(reps: 8, weightKg: 50)]);+ fit.assignRoutineToDay(3, r.id);+ final json = fit.exportPlanJson([r]);+ expect(jsonDecode(json)['gymmane'], 'plan');+ expect(fit.planSummaryText([r]), contains('Mixed'));++ fit.resetAllData();+ final result = fit.applyPlan(parsePlan(json), schedule: true);+ expect(result.routines, 1);+ expect(result.missed, isEmpty);+ final got = fit.routines.single;+ expect(got.name, 'Mixed');+ expect(got.group, 'Couple');+ expect(fit.plannedSets(got, bench).single.weightKg, 50);+ final twist = fit.customExercises.single;+ expect(twist.name, 'Landmine Twist');+ expect(twist.steps, ['Twist']);+ expect(got.exerciseIds, [bench, twist.id]);+ expect(fit.weeklyPlan[3], got.id);+ });++ test('the request for an AI carries the format', () {+ final text = fit.planRequestText();+ expect(text, contains('"weeks"'));+ expect(text, contains('Barbell Bench Press'));+ });+ });++ group('recovery', () {+ test('nothing trained means fully recovered', () {+ expect(fit.overallRecovery(), 100);+ expect(fit.stillRecovering(), isEmpty);+ });++ test('a hard chest day tires the chest and it recovers in a few days', () {+ 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 fresh = fit.muscleRecovery(now: now);+ expect(fresh['chest'], lessThan(0.3));+ expect(fresh['quads'], 1);+ expect(fit.hoursUntilRecovered('chest', now: now), greaterThan(12));+ final later = fit.muscleRecovery(now: now.add(const Duration(days: 4)));+ expect(later['chest'], greaterThan(0.8));+ expect(fit.stillRecovering(now: now), contains('chest'));+ });+ });++ group('settings', () {+ test('the theme can follow the phone and older backups still load', () {+ fit.setThemePref('system');+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.themePref, 'system');+ fit.applyBackup({'dark': false});+ expect(fit.themePref, 'light');+ fit.setThemePref('dark');+ });++ test('the rest alarm style is kept and handed to the alarm', () {+ fit.setAlarmStyle('vibrate');+ expect(RestAlarm.instance.style, 'vibrate');+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.alarmStyle, 'vibrate');+ fit.setAlarmStyle('loud');+ });++ test('height reads in feet and inches for imperial users', () {+ fit.setUnits('lb');+ expect(fit.heightLabel(175), '5′ 9″');+ fit.setUnits('kg');+ expect(fit.heightLabel(175), '175 cm');+ });+ });++ group('lyfta', () {+ const csv = 'Title,Date,Duration,Description,Notes,Exercise,Exercise Note,Superset id,Weight,Reps,'+ 'RIR/RPE,Distance,Time,Set Type,RecordLevel: gold/silver/bronze,RecordType: 1RM / max_weight / volume / reps\n'+ 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Barbell Bent Over Row,,,60.000,10,,,,NORMAL_SET,,\n'+ 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Barbell Bent Over Row,,,70.000,8,,,,NORMAL_SET,1,1\n'+ 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Pull Up,,,,12,,,,NORMAL_SET,,\n';++ test('the export is recognised and read', () {+ expect(detectFormat(csv), ImportFormat.lyfta);+ final result = parseImport(csv);+ final session = result.sessions.single;+ expect(session.durationSec, 3600 + 19 * 60 + 33);+ expect(session.exercises.first.sets.map((s) => s.weightKg), [60, 70]);+ expect(session.exercises.last.name, 'Pull Up');+ });+ });+}diff --git a/test/requests_19sep_test.dart b/test/requests_19sep_test.dartnew file mode 100644index 0000000..de0926e--- /dev/null+++ b/test/requests_19sep_test.dart@@ -0,0 +1,174 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/workout_import.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:gymmane/theme/app_colors.dart';+import 'package:gymmane/widgets/home_widget_views.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');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ Routine oneSetEach(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ final ex = fit.matchExerciseByName(name)!.id;+ fit.toggleRoutineExercise(id, ex);+ fit.bumpRoutineSets(id, ex, -2);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ Future<void> wait(Duration d) => Future<void>.delayed(d + const Duration(milliseconds: 200));++ group('#67 terminar solo', () {+ test('al marcar la última serie del último ejercicio se abre el resumen', () async {+ fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));+ fit.endCountdown();+ expect(fit.route, 'session');++ fit.toggleSet(0, 0);+ await wait(WorkoutState.advanceDelay);+ expect(fit.session!.currentIndex, 1);++ fit.toggleSet(1, 0);+ expect(fit.isSessionComplete, isFalse, reason: 'primero se ve el tic marcado');+ await wait(WorkoutState.finishDelay);+ expect(fit.isSessionComplete, isTrue);+ expect(fit.sessions, hasLength(1));+ });++ test('desmarcar a tiempo lo cancela', () async {+ fit.startRoutine(oneSetEach(['Barbell Bench Press']));+ fit.endCountdown();+ fit.toggleSet(0, 0);+ fit.toggleSet(0, 0);+ await wait(WorkoutState.finishDelay);+ expect(fit.isSessionComplete, isFalse);+ });++ test('con el paso automático apagado espera al botón', () async {+ fit.toggleAutoAdvance();+ fit.startRoutine(oneSetEach(['Barbell Bench Press']));+ fit.endCountdown();+ fit.toggleSet(0, 0);+ await wait(WorkoutState.finishDelay);+ expect(fit.isSessionComplete, isFalse);+ fit.toggleAutoAdvance();+ });++ test('si quedan series atrás, vuelve a ellas en vez de terminar', () async {+ fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));+ fit.endCountdown();+ fit.goToExercise(1);+ fit.toggleSet(1, 0);+ await wait(WorkoutState.finishDelay);+ expect(fit.isSessionComplete, isFalse);+ expect(fit.session!.currentIndex, 0);+ });+ });++ test('#58 el paso automático queda contado para avisar del cambio', () async {+ fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));+ fit.endCountdown();+ final before = fit.autoMoves;+ fit.goToExercise(1);+ expect(fit.autoMoves, before, reason: 'moverse a mano no avisa');+ fit.goToExercise(0);+ fit.toggleSet(0, 0);+ await wait(WorkoutState.advanceDelay);+ expect(fit.autoMoves, before + 1);+ });++ test('el check puesto a mano se quita con otro toque', () {+ final today = fit.todayIndex;+ fit.toggleCheckin(today);+ expect(fit.isDayDone(today), isTrue);+ fit.toggleCheckin(today);+ expect(fit.isDayDone(today), isFalse);+ expect(fit.dateForWeekday(today).day, DateTime.now().day);+ });++ testWidgets('el widget de hoy dice hecho o no sin poner el día', (tester) async {+ Future<void> show(bool done) => tester.pumpWidget(Directionality(+ textDirection: TextDirection.ltr,+ child: Center(child: TodayWidgetView(gc: GymColors.dark, done: done, planned: true, streak: 0)),+ ));+ await show(false);+ expect(find.text('${DateTime.now().day}'), findsNothing);+ expect(find.byIcon(Icons.fitness_center_rounded), findsOneWidget);+ await show(true);+ expect(find.byIcon(Icons.check_rounded), findsOneWidget);+ });++ testWidgets('el widget de la semana cuenta los días hechos', (tester) async {+ await tester.pumpWidget(Directionality(+ textDirection: TextDirection.ltr,+ child: Center(+ child: WeekWidgetView(+ gc: GymColors.dark,+ done: const [true, false, true, false, false, false, false],+ goal: 4,+ ),+ ),+ ));+ expect(find.text('2'), findsOneWidget);+ expect(find.text('/4'), findsOneWidget);+ expect(find.byIcon(Icons.check_rounded), findsNWidgets(2));+ final geo = WeekWidgetView.geometry(const Size(320, 150));+ final origin = tester.getTopLeft(find.byType(WeekWidgetView));+ final dots = find.byWidgetPredicate(+ (w) => w is Container && w.decoration is BoxDecoration && (w.decoration as BoxDecoration).shape == BoxShape.circle);+ expect(dots, findsNWidgets(7));+ for (var i = 0; i < 7; i++) {+ final c = tester.getCenter(dots.at(i)) - origin;+ expect(c.dx / 320, closeTo(geo[0] + geo[1] * i, 0.002));+ expect(c.dy / 150, closeTo(geo[2], 0.002));+ }+ });++ group('#55 nombres de Lyfta', () {+ String? match(String name) => fit.matchExerciseByName(name)?.name;++ test('no cambia de músculo por una palabra suelta', () {+ expect(match('Dumbbell Seated Curl'), isNot('Seated Leg Curl'));+ expect(match('Lever Seated Leg Extension'), isNot(contains('Calf')));+ expect(match('Dumbbell Seated One Arm Rotate'), isNull);+ });++ test('el nombre exacto gana', () {+ expect(match('Lever Seated Reverse Fly'), 'Lever Seated Reverse Fly');+ expect(match('Smith Seated Shoulder Press'), 'Smith Seated Shoulder Press');+ });++ test('encuentra el ejercicio aunque el nombre traiga más cosas', () {+ expect(match('Cable Standing Face Pull (with rope)'), 'Face Pull');+ expect(match('Barbell Feet Flat Bench Press (male)'), 'Barbell Bench Press');+ expect(match('Lever Pec Deck Fly'), 'Pec Deck');+ expect(match('Close Grip Preacher Curl'), 'Barbell Preacher Curl');+ });++ test('su columna RIR/RPE se entiende en las dos escalas', () {+ const csv = 'Title,Date,Duration,Description,Notes,Exercise,Exercise Note,Superset id,Weight,Reps,'+ 'RIR/RPE,Distance,Time,Set Type,RecordLevel: gold/silver/bronze,RecordType: 1RM / max_weight / volume / reps\n'+ 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,10,2,,,NORMAL_SET,,\n'+ 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,8,8.5,,,NORMAL_SET,,\n'+ 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,8,,,,NORMAL_SET,,\n';+ final sets = parseImport(csv).sessions.single.exercises.single.sets;+ expect(sets.map((s) => s.rpe), [8, 8.5, null]);+ });+ });+}diff --git a/test/rpe_test.dart b/test/rpe_test.dartnew file mode 100644index 0000000..559e3fb--- /dev/null+++ b/test/rpe_test.dart@@ -0,0 +1,98 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/workout_import.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();+ });++ group('tabla de RPE', () {+ test('coincide con la tabla de RTS', () {+ expect(rpePercent(1, 10), 1.0);+ expect(rpePercent(5, 8), closeTo(0.811, 1e-9));+ expect(rpePercent(3, 9.5), closeTo(0.907, 1e-9));+ expect(rpePercent(12, 6), closeTo(0.574, 1e-9));+ });++ test('fuera de la tabla no se inventa nada', () {+ expect(rpePercent(5, null), isNull);+ expect(rpePercent(5, 5), isNull);+ expect(rpePercent(13, 8), isNull);+ expect(rpePercent(0, 8), isNull);+ });++ test('el 1RM usa la tabla cuando la serie lleva RPE', () {+ expect(LoggedSet(5, 100, rpe: 8).oneRm, closeTo(100 / 0.811, 1e-6));+ expect(LoggedSet(5, 100).oneRm, closeTo(100 * (1 + 5 / 30), 1e-6));+ expect(LoggedSet(15, 50, rpe: 8).oneRm, closeTo(50 * (1 + 15 / 30), 1e-6));+ });+ });++ group('RPE o RIR', () {+ test('apagado por defecto y se elige la escala', () {+ expect(fit.effortMode, '');+ fit.setEffortMode('rir');+ expect(fit.logRpe, isTrue);+ expect(fit.usesRir, isTrue);+ expect(fit.effortLabel(8), 'RIR 2');+ expect(fit.effortTag(8.5), 'R1.5');+ fit.setEffortMode('rpe');+ expect(fit.effortLabel(8), 'RPE 8');+ expect(fit.effortTag(8), '@8');+ fit.setEffortMode('');+ expect(fit.logRpe, isFalse);+ expect(fit.effortScale, 'rpe');+ });++ test('la escala se guarda en la copia', () {+ fit.setEffortMode('rir');+ final data = fit.toJson();+ fit.resetAllData();+ expect(fit.effortMode, '');+ fit.applyBackup(data);+ expect(fit.effortMode, 'rir');+ });+ });++ group('CSV', () {+ test('la exportación lleva el RPE y se vuelve a leer', () {+ final csv = Store.instance.exportCsv([+ LoggedSession(DateTime(2026, 9, 19), 1800, [+ LoggedExercise('EIeI8Vf', 'Barbell Bench Press', 'chest', [+ LoggedSet(5, 100, rpe: 8.5),+ LoggedSet(5, 100),+ ]),+ ]),+ ]);+ final rows = csv.trim().split('\n');+ expect(rows.first, endsWith(',rpe'));+ expect(rows[1], endsWith(',8.5'));+ expect(rows[2], endsWith(','));++ final back = parseImport(csv);+ final sets = back.sessions.single.exercises.single.sets;+ expect(sets.first.rpe, 8.5);+ expect(sets.last.rpe, isNull);+ });++ 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'+ '"Push","19 Sep 2026, 10:00","19 Sep 2026, 11:00","","Bench Press (Barbell)","","",0,"normal",100,5,,,8\n';+ final hevySets = parseImport(hevy).sessions.single.exercises.single.sets;+ expect(hevySets.single.rpe, 8);++ const generic = 'date,exercise,reps,weight,rir\n2026-09-19,Squat,5,120,2\n';+ final genericSets = parseImport(generic).sessions.single.exercises.single.sets;+ expect(genericSets.single.rpe, 8);+ });+ });+}diff --git a/test/session_lock_test.dart b/test/session_lock_test.dartnew file mode 100644index 0000000..32eb434--- /dev/null+++ b/test/session_lock_test.dart@@ -0,0 +1,84 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/state/fit_state.dart';++void _reset() {+ fit.saveAndExit();+ fit.sessions.clear();+ fit.routines.clear();+}++void main() {+ setUp(_reset);+ tearDown(_reset);++ test('the lock only lives while a workout is on screen', () {+ final id = fit.createRoutine('Pull');+ fit.toggleRoutineExercise(id, 'EIeI8Vf');+ fit.startRoutine(fit.routines.first);+ expect(fit.sessionLocked, isFalse);++ fit.toggleSessionLock();+ expect(fit.sessionLocked, isTrue);++ fit.parkSession();+ expect(fit.sessionLocked, isFalse);+ expect(fit.route, 'home');++ fit.resumeSession();+ fit.toggleSessionLock();+ fit.finishSession();+ expect(fit.sessionLocked, isFalse);++ fit.saveAndExit();+ expect(fit.sessionLocked, isFalse);+ });++ test('finishing the last exercise goes back to the first one left', () async {+ final id = fit.createRoutine('Full');+ for (final e in fit.allExercises.take(3)) {+ fit.toggleRoutineExercise(id, e.id);+ }+ fit.startRoutine(fit.routines.first);+ fit.toggleSessionLock();+ final s = fit.session!;+ for (var j = 0; j < s.exercises[0].sets.length; j++) {+ fit.toggleSet(0, j);+ }+ fit.goToExercise(2);+ for (var j = 0; j < s.exercises[2].sets.length; j++) {+ fit.toggleSet(2, j);+ }+ expect(fit.pendingAfter(2), 1);++ await Future<void>.delayed(WorkoutState.advanceDelay + const Duration(milliseconds: 150));+ expect(s.currentIndex, 1);+ });++ test('the workout clock waits for the start countdown', () {+ final id = fit.createRoutine('Push');+ fit.toggleRoutineExercise(id, 'EIeI8Vf');+ expect(fit.startCountdown, isTrue);++ fit.startRoutine(fit.routines.first);+ expect(fit.countingDown, isTrue);+ expect(fit.sessionElapsed, 0);++ fit.endCountdown();+ expect(fit.countdownUntil, isNull);+ expect(fit.countingDown, isFalse);++ fit.toggleStartCountdown();+ fit.saveAndExit();+ fit.startRoutine(fit.routines.first);+ expect(fit.countdownUntil, isNull);+ fit.toggleStartCountdown();+ });++ test('keep-screen-on is a persisted preference that defaults to on', () {+ expect(fit.keepScreenOn, isTrue);+ fit.toggleKeepScreenOn();+ expect(fit.keepScreenOn, isFalse);+ expect(fit.toJson()['keepAwake'], isFalse);+ fit.toggleKeepScreenOn();+ });+}