Compare commits

..

No commits in common. "cf2d917b3399187a66edafc31369db1ce2818127" and "97f4e49a5f7a171ec6ec605242048534c95ae894" have entirely different histories.

59 changed files with 1145 additions and 3454 deletions

View File

@ -2,7 +2,7 @@
# Runtime: tkinter/subprocess/socket/sqlite3 (stdlib) plus gatelock (below). # Runtime: tkinter/subprocess/socket/sqlite3 (stdlib) plus gatelock (below).
bandit==1.9.4 bandit==1.9.4
codespell==2.4.3 codespell==2.4.3
coverage==7.16.2 coverage==7.16.1
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.2.0#subdirectory=freedays freedays @ git+https://github.com/kuhyx/utils@freedays-v0.2.0#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.2#subdirectory=gatelock gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.2#subdirectory=gatelock

View File

@ -15,7 +15,6 @@ class BreakSnapshot {
required this.workoutType, required this.workoutType,
required this.breakEndMs, required this.breakEndMs,
required this.breakDurationSecs, required this.breakDurationSecs,
required this.breakFailSecs,
required this.breakLabel, required this.breakLabel,
required this.breakForExIdx, required this.breakForExIdx,
required this.breakForSetIdx, required this.breakForSetIdx,
@ -50,7 +49,6 @@ class BreakSnapshot {
final keys = [ final keys = [
'breakEndMs', 'breakEndMs',
'breakDurationSecs', 'breakDurationSecs',
'breakFailSecs',
'breakForExIdx', 'breakForExIdx',
'breakForSetIdx', 'breakForSetIdx',
'nextExIdx', 'nextExIdx',
@ -69,7 +67,6 @@ class BreakSnapshot {
workoutType: workoutType, workoutType: workoutType,
breakEndMs: i('breakEndMs')!, breakEndMs: i('breakEndMs')!,
breakDurationSecs: i('breakDurationSecs')!, breakDurationSecs: i('breakDurationSecs')!,
breakFailSecs: i('breakFailSecs')!,
breakLabel: breakLabel, breakLabel: breakLabel,
breakForExIdx: i('breakForExIdx')!, breakForExIdx: i('breakForExIdx')!,
breakForSetIdx: i('breakForSetIdx')!, breakForSetIdx: i('breakForSetIdx')!,
@ -96,11 +93,7 @@ class BreakSnapshot {
/// Full length of the running rest, for the countdown's denominator. /// Full length of the running rest, for the countdown's denominator.
final int breakDurationSecs; final int breakDurationSecs;
/// The running rest's exercise's fail rest, so a `−1 rep` press can re-cut /// Human label of the running rest, e.g. 'Rest (3 min — well done!)'.
/// the rest while the UI is dead.
final int breakFailSecs;
/// Human label of the running rest, e.g. 'Rest' or 'Warmup rest'.
final String breakLabel; final String breakLabel;
/// Exercise the running rest belongs to, or -1. /// Exercise the running rest belongs to, or -1.
@ -153,7 +146,6 @@ class BreakSnapshot {
'workoutType': workoutType, 'workoutType': workoutType,
'breakEndMs': breakEndMs, 'breakEndMs': breakEndMs,
'breakDurationSecs': breakDurationSecs, 'breakDurationSecs': breakDurationSecs,
'breakFailSecs': breakFailSecs,
'breakLabel': breakLabel, 'breakLabel': breakLabel,
'breakForExIdx': breakForExIdx, 'breakForExIdx': breakForExIdx,
'breakForSetIdx': breakForSetIdx, 'breakForSetIdx': breakForSetIdx,
@ -181,7 +173,6 @@ class BreakSnapshot {
workoutType: workoutType, workoutType: workoutType,
breakEndMs: breakEndMs ?? this.breakEndMs, breakEndMs: breakEndMs ?? this.breakEndMs,
breakDurationSecs: breakDurationSecs ?? this.breakDurationSecs, breakDurationSecs: breakDurationSecs ?? this.breakDurationSecs,
breakFailSecs: breakFailSecs,
breakLabel: breakLabel ?? this.breakLabel, breakLabel: breakLabel ?? this.breakLabel,
breakForExIdx: breakForExIdx, breakForExIdx: breakForExIdx,
breakForSetIdx: breakForSetIdx, breakForSetIdx: breakForSetIdx,

View File

@ -7,9 +7,6 @@ const double kDefaultMaxWeight = 27.5;
/// Weight increment used for progression steps (kg). /// Weight increment used for progression steps (kg).
const double kWeightIncrement = 2.5; const double kWeightIncrement = 2.5;
/// Reps in every warmup set. Even on purpose: the user alternates sides.
const int kWarmupReps = 6;
/// Immutable definition of a single exercise and its current target state. /// Immutable definition of a single exercise and its current target state.
class Exercise { class Exercise {
/// Creates an exercise with the given parameters. /// Creates an exercise with the given parameters.

View File

@ -1,223 +0,0 @@
/// Per-exercise progression state, as stored in SQLite and synced to
/// Firebase.
library;
import 'dart:developer';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/progression.dart';
/// Default rest after a set that hit its target reps.
const int kDefaultRestSuccessSecs = 180;
/// Default rest after a set that fell short: the longer one.
const int kDefaultRestFailSecs = 300;
/// Default rest after the warmup set.
const int kDefaultRestWarmupSecs = 180;
/// Shortest rest the settings sheet offers.
const int kMinRestSecs = 30;
/// Longest rest the settings sheet offers.
const int kMaxRestSecs = 600;
/// Step of the settings sheet's rest steppers.
const int kRestStepSecs = 15;
/// Per-exercise progression state stored in SQLite.
///
/// Every field is `required` deliberately: a state rebuilt field by field
/// (a threshold edit, a restore) that forgot one would silently reset it,
/// and a required parameter makes the compiler find every such site.
class ExerciseState implements ProgressionInputs {
/// Creates an [ExerciseState] with all progression fields.
ExerciseState({
required this.name,
required this.weight,
required this.reps,
required this.successStreak,
required this.failStreak,
required this.maxWeight,
required this.successThreshold,
required this.failThreshold,
required this.mode,
required this.repsHigh,
required this.repsLow,
required this.hasWarmup,
required this.pausedUntil,
required this.restSuccessSecs,
required this.restFailSecs,
required this.restWarmupSecs,
});
/// The state a never-trained [ex] starts from.
factory ExerciseState.initial(Exercise ex) => ExerciseState(
name: ex.name,
weight: ex.weight,
reps: ex.reps,
successStreak: 0,
failStreak: 0,
maxWeight: ex.maxWeight,
successThreshold: 3,
failThreshold: 2,
mode: ProgressionMode.weight,
repsHigh: kDefaultRepsHigh,
repsLow: kDefaultRepsLow,
hasWarmup: ex.hasWarmup,
pausedUntil: null,
restSuccessSecs: kDefaultRestSuccessSecs,
restFailSecs: kDefaultRestFailSecs,
restWarmupSecs: kDefaultRestWarmupSecs,
);
/// Exercise name (matches [Exercise.name], used as primary key).
final String name;
/// Current working weight in kg.
@override
double weight;
/// Current target reps per set.
@override
int reps;
/// Consecutive successful workouts since last progression.
int successStreak;
/// Consecutive failed workouts since last regression.
int failStreak;
/// Weight cap; reps increase instead of weight when this is reached.
@override
final double maxWeight;
/// Successes needed in a row before the target goes up.
int successThreshold;
/// Failures needed in a row before the target goes down.
int failThreshold;
/// How the target goes up and down.
@override
final ProgressionMode mode;
/// Double progression: reps at which the weight goes up (`n`).
@override
final int repsHigh;
/// Double progression: reps the heavier weight starts at (`m`).
@override
final int repsLow;
/// Whether this exercise gets a warmup set (and its rest).
final bool hasWarmup;
/// The first day the exercise is back after an injury pause (a local
/// midnight), or null when it is not paused. While paused it is recorded
/// as FAILED in every workout, so progression steps down instead of the
/// exercise coming back at the load it left with.
final DateTime? pausedUntil;
/// Rest after a set that hit its target reps, in seconds.
final int restSuccessSecs;
/// Rest after a set that fell short, in seconds.
final int restFailSecs;
/// Rest after the warmup set, in seconds.
final int restWarmupSecs;
/// Whether the exercise is paused at [now].
bool isPausedAt(DateTime now) {
final until = pausedUntil;
return until != null && now.isBefore(until);
}
/// Returns a copy with the given fields replaced.
ExerciseState copyWith({
double? weight,
int? reps,
int? successStreak,
int? failStreak,
int? successThreshold,
int? failThreshold,
ProgressionMode? mode,
int? repsHigh,
int? repsLow,
bool? hasWarmup,
DateTime? pausedUntil,
int? restSuccessSecs,
int? restFailSecs,
int? restWarmupSecs,
bool resume = false,
}) => ExerciseState(
name: name,
weight: weight ?? this.weight,
reps: reps ?? this.reps,
successStreak: successStreak ?? this.successStreak,
failStreak: failStreak ?? this.failStreak,
maxWeight: maxWeight,
successThreshold: successThreshold ?? this.successThreshold,
failThreshold: failThreshold ?? this.failThreshold,
mode: mode ?? this.mode,
repsHigh: repsHigh ?? this.repsHigh,
repsLow: repsLow ?? this.repsLow,
hasWarmup: hasWarmup ?? this.hasWarmup,
// `resume` exists because a null argument cannot mean "clear it".
pausedUntil: resume ? null : (pausedUntil ?? this.pausedUntil),
restSuccessSecs: restSuccessSecs ?? this.restSuccessSecs,
restFailSecs: restFailSecs ?? this.restFailSecs,
restWarmupSecs: restWarmupSecs ?? this.restWarmupSecs,
);
}
/// First local midnight [days] days after [now]: the day a pause started at
/// [now] ends.
DateTime pauseEnd(DateTime now, int days) =>
DateTime(now.year, now.month, now.day + days);
/// `2026-10-11` for storage; the inverse of [parsePauseDate].
String formatPauseDate(DateTime d) =>
'${d.year.toString().padLeft(4, '0')}-'
'${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';
/// Reads a stored pause date; null means not paused.
///
/// Anything unreadable is reported and treated as "not paused": the
/// exercise then shows up in the workout, which is the visible failure.
DateTime? parsePauseDate(Object? raw) {
if (raw == null) return null;
final parsed = raw is String ? DateTime.tryParse(raw) : null;
if (parsed == null) {
log(
'ExerciseState: unreadable paused_until "$raw" — treating the '
'exercise as not paused.',
level: 900,
);
}
return parsed;
}
const _months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
/// `11 Oct`: how a pause's end date is shown.
String formatShortDate(DateTime d) => '${d.day} ${_months[d.month - 1]}';
/// `3:00`: how a rest length is shown.
String formatRest(int secs) =>
'${secs ~/ 60}:${(secs % 60).toString().padLeft(2, '0')}';

View File

@ -1,141 +0,0 @@
/// The progression rule: what a success, a failure, or a long break does to
/// an exercise's target, for each of the three progression modes.
///
/// Pure on purpose. `applyProgression` (what finishing a workout does) and
/// the workout/history previews ("→ 25 kg × 6") both call these functions,
/// so a preview can never promise something the finish does not deliver.
library;
import 'dart:developer';
import 'package:workout_app/models/exercise.dart';
/// Default rep ceiling `n` for [ProgressionMode.doubleProgression].
const int kDefaultRepsHigh = 12;
/// Default restart reps `m` for [ProgressionMode.doubleProgression].
const int kDefaultRepsLow = 6;
/// How an exercise advances once its success streak hits the threshold.
enum ProgressionMode {
/// +2.5 kg per step; +1 rep instead once the weight cap is reached.
weight('weight'),
/// +1 rep per step, weight never changes.
reps('reps'),
/// +1 rep per step until `n` reps, then +2.5 kg and back to `m` reps.
doubleProgression('double');
const ProgressionMode(this.storageKey);
/// Value stored in SQLite and Firebase. Never rename: synced data holds it.
final String storageKey;
/// Parses [raw]; null means "not set yet" and is silently [weight] (every
/// row written before modes existed). Anything else unknown is a bug in
/// some writer, so it is reported before falling back.
static ProgressionMode parse(Object? raw) {
if (raw == null) return weight;
for (final m in values) {
if (m.storageKey == raw) return m;
}
log(
'ProgressionMode: unknown mode "$raw" — treating it as weight '
'progression. Some writer stored a value this build does not know.',
level: 900,
);
return weight;
}
}
/// A working target: the weight and reps of every working set.
class ProgressionTarget {
/// Creates a [ProgressionTarget].
const ProgressionTarget(this.weight, this.reps);
/// Working weight in kg.
final double weight;
/// Target reps per set.
final int reps;
@override
String toString() => 'ProgressionTarget($weight kg × $reps)';
}
/// The inputs the rule needs; implemented by `ExerciseState`.
abstract interface class ProgressionInputs {
/// Current working weight in kg.
double get weight;
/// Current target reps.
int get reps;
/// Weight cap (the heaviest dumbbell available).
double get maxWeight;
/// The active progression mode.
ProgressionMode get mode;
/// Double progression: reps at which the weight goes up (`n`).
int get repsHigh;
/// Double progression: reps the heavier weight starts at (`m`).
int get repsLow;
}
/// The target after a success streak reaches its threshold.
ProgressionTarget targetAfterSuccess(ProgressionInputs s) {
final atCap = s.weight >= s.maxWeight;
final heavier = (s.weight + kWeightIncrement).clamp(0.0, s.maxWeight);
switch (s.mode) {
case ProgressionMode.weight:
return atCap
? ProgressionTarget(s.weight, s.reps + 1)
: ProgressionTarget(heavier, s.reps);
case ProgressionMode.reps:
return ProgressionTarget(s.weight, s.reps + 1);
case ProgressionMode.doubleProgression:
// `>=`, not `==`: an exercise switched into this mode above `n` reps
// (Situp sits at 30) must still promote, not climb forever.
if (s.reps < s.repsHigh || atCap) {
return ProgressionTarget(s.weight, s.reps + 1);
}
return ProgressionTarget(heavier, s.repsLow);
}
}
/// The target after a fail streak reaches its threshold, or after a break
/// of more than a week (one regression step in every mode).
ProgressionTarget targetAfterFailure(ProgressionInputs s) {
final lighter = (s.weight - kWeightIncrement).clamp(0.0, s.maxWeight);
switch (s.mode) {
case ProgressionMode.weight:
return ProgressionTarget(lighter, s.reps);
case ProgressionMode.reps:
return ProgressionTarget(s.weight, s.reps - 1 < 1 ? 1 : s.reps - 1);
case ProgressionMode.doubleProgression:
if (s.reps > s.repsLow) return ProgressionTarget(s.weight, s.reps - 1);
// At `m` the step down is the exact inverse of a step up: lighter and
// back to `n`. With no weight left to drop that would only make the
// exercise harder, so it stays put.
if (s.weight <= 0) return ProgressionTarget(s.weight, s.reps);
return ProgressionTarget(lighter, s.repsHigh);
}
}
/// Short label for moving from [from] to [to]: `25 kg`, `13 reps`,
/// `25 kg × 6`, or `same` when the rule has nowhere left to go.
String describeTargetChange(ProgressionInputs from, ProgressionTarget to) {
final weightChanged = to.weight != from.weight;
final repsChanged = to.reps != from.reps;
if (weightChanged && repsChanged) return '${_kg(to.weight)} kg × ${to.reps}';
if (weightChanged) return '${_kg(to.weight)} kg';
if (repsChanged) return '${to.reps} reps';
return 'same';
}
/// `25` for 25.0, `27.5` for 27.5 — no trailing `.0` noise in tight rows.
String _kg(double w) =>
w == w.roundToDouble() ? w.toInt().toString() : w.toString();

View File

@ -9,7 +9,12 @@ const double kSitupMaxWeight = 10;
/// Plan A: lower-body and push/pull focus. /// Plan A: lower-body and push/pull focus.
final workoutA = [ final workoutA = [
const Exercise(name: 'Dumbbell Lunge', sets: 5, reps: 12, weight: 7.5), const Exercise(name: 'Dumbbell Lunge', sets: 5, reps: 12, weight: 7.5),
const Exercise(name: 'Dumbbell Bench Press', sets: 5, reps: 12, weight: 22.5), const Exercise(
name: 'Dumbbell Bench Press',
sets: 5,
reps: 12,
weight: 22.5,
),
const Exercise(name: 'Dumbbell Row', sets: 4, reps: 6, weight: 22.5), const Exercise(name: 'Dumbbell Row', sets: 4, reps: 6, weight: 22.5),
const Exercise(name: 'Dumbbell Curl', sets: 3, reps: 12, weight: 12.5), const Exercise(name: 'Dumbbell Curl', sets: 3, reps: 12, weight: 12.5),
]; ];
@ -28,7 +33,12 @@ final workoutB = [
reps: 12, reps: 12,
weight: 7.5, weight: 7.5,
), ),
const Exercise(name: 'Dumbbell Bench Press', sets: 5, reps: 12, weight: 22.5), const Exercise(
name: 'Dumbbell Bench Press',
sets: 5,
reps: 12,
weight: 22.5,
),
const Exercise( const Exercise(
name: 'Situp', name: 'Situp',
sets: 3, sets: 3,
@ -38,16 +48,3 @@ final workoutB = [
hasWarmup: false, hasWarmup: false,
), ),
]; ];
/// The plan's own warmup default for [name]; true for an unknown name.
///
/// What a NULL `has_warmup` means. The column is nullable on purpose: rows
/// from before the toggle existed, old backups and old Firebase records all
/// lack it, and a blanket default of "on" would quietly give Situp its
/// warmup back on every restore.
bool planHasWarmup(String name) {
for (final ex in [...workoutA, ...workoutB]) {
if (ex.name == name) return ex.hasWarmup;
}
return true;
}

View File

@ -11,6 +11,7 @@ import 'dart:math';
import 'package:crdt_sync/crdt_sync.dart'; import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/services/storage_service.dart'; import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/workout_sync_service.dart'; import 'package:workout_app/services/workout_sync_service.dart';
import 'package:workout_app/ui/theme.dart'; import 'package:workout_app/ui/theme.dart';
@ -142,7 +143,10 @@ class _HistoryScreenState extends State<HistoryScreen> {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
backgroundColor: colorScheme.surfaceContainerHigh, backgroundColor: colorScheme.surfaceContainerHigh,
title: Text('Progress', style: TextStyle(color: colorScheme.onSurface)), title: Text(
'Progress',
style: TextStyle(color: colorScheme.onSurface),
),
iconTheme: IconThemeData(color: colorScheme.onSurface), iconTheme: IconThemeData(color: colorScheme.onSurface),
), ),
body: _loading body: _loading
@ -175,7 +179,9 @@ class _HistoryScreenState extends State<HistoryScreen> {
List<Widget> _buildTotalView() => [ List<Widget> _buildTotalView() => [
const _SectionLabel('TOTAL VOLUME (2-session rolling avg, kg)'), const _SectionLabel('TOTAL VOLUME (2-session rolling avg, kg)'),
const SizedBox(height: 6), const SizedBox(height: 6),
_WeightChart(points: _rollingAvg2(_totalVolumePoints(_rows))), _WeightChart(
points: _rollingAvg2(_totalVolumePoints(_rows)),
),
const SizedBox(height: 16), const SizedBox(height: 16),
WorkoutCalendar( WorkoutCalendar(
workoutDates: _allWorkoutDates(_rows, _syncedRows), workoutDates: _allWorkoutDates(_rows, _syncedRows),
@ -212,7 +218,9 @@ class _HistoryScreenState extends State<HistoryScreen> {
], ],
const _SectionLabel('WEIGHT OVER TIME'), const _SectionLabel('WEIGHT OVER TIME'),
const SizedBox(height: 6), const SizedBox(height: 6),
_WeightChart(points: _exerciseWeightPoints(_rows, name)), _WeightChart(
points: _exerciseWeightPoints(_rows, name),
),
const SizedBox(height: 16), const SizedBox(height: 16),
WorkoutCalendar( WorkoutCalendar(
workoutDates: _exerciseDates(_rows, name), workoutDates: _exerciseDates(_rows, name),

View File

@ -73,6 +73,15 @@ class _ProgressStatsCard extends StatelessWidget {
final ExerciseState state; final ExerciseState state;
String _nextWeightLabel(double current, double max, double inc) {
if (current >= max) return '+1 rep';
return '+${inc}kg (${(current + inc).clamp(0.0, max)}kg)';
}
String _prevWeightLabel(double current, double inc) {
return '-${inc}kg (${(current - inc).clamp(0.0, double.infinity)}kg)';
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final successLeft = state.successThreshold - state.successStreak; final successLeft = state.successThreshold - state.successStreak;
@ -90,7 +99,7 @@ class _ProgressStatsCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'${state.name} — ${state.weight}kg × ${state.reps}', '${state.name} — ${state.weight}kg',
style: TextStyle( style: TextStyle(
color: colorScheme.onSurface, color: colorScheme.onSurface,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@ -104,8 +113,11 @@ class _ProgressStatsCard extends StatelessWidget {
current: state.successStreak, current: state.successStreak,
threshold: state.successThreshold, threshold: state.successThreshold,
leftLabel: '$successLeft more', leftLabel: '$successLeft more',
// The same rule applyProgression runs, in every mode. actionLabel: _nextWeightLabel(
actionLabel: describeTargetChange(state, targetAfterSuccess(state)), state.weight,
state.maxWeight,
kWeightIncrement,
),
direction: '↑', direction: '↑',
), ),
const SizedBox(height: 6), const SizedBox(height: 6),
@ -115,7 +127,7 @@ class _ProgressStatsCard extends StatelessWidget {
current: state.failStreak, current: state.failStreak,
threshold: state.failThreshold, threshold: state.failThreshold,
leftLabel: '$failLeft more', leftLabel: '$failLeft more',
actionLabel: describeTargetChange(state, targetAfterFailure(state)), actionLabel: _prevWeightLabel(state.weight, kWeightIncrement),
direction: '↓', direction: '↓',
), ),
], ],

View File

@ -1,5 +1,5 @@
/// Settings screen: manual weight and rep overrides, each exercise's /// Settings screen: per-exercise streak thresholds and manual weight
/// settings sheet, plus links to the sync surfaces. /// overrides, plus links to the sync surfaces.
/// ///
/// "Sync settings" is the shared `sync_settings_ui` package (Firebase sync; /// "Sync settings" is the shared `sync_settings_ui` package (Firebase sync;
/// no Backup section -- see the class doc on [SettingsScreen] for why). /// no Backup section -- see the class doc on [SettingsScreen] for why).
@ -23,20 +23,20 @@ import 'package:workout_app/services/google_sign_in_backend.dart';
import 'package:workout_app/services/progression_sync_service.dart'; import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart'; import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart'; import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
part 'settings_screen_actions.dart'; part 'settings_screen_actions.dart';
part 'settings_screen_exercise_list.dart';
part 'settings_screen_exercise_sections.dart'; part 'settings_screen_exercise_sections.dart';
part 'settings_screen_rows.dart'; part 'settings_screen_rows.dart';
part 'settings_screen_sandbox.dart'; part 'settings_screen_sandbox.dart';
part 'settings_screen_sections.dart'; part 'settings_screen_sections.dart';
part 'settings_screen_thresholds.dart';
part 'settings_screen_widget.dart'; part 'settings_screen_widget.dart';
class _SettingsScreenState extends State<SettingsScreen> { class _SettingsScreenState extends State<SettingsScreen> {
bool _loading = true; bool _loading = true;
final Map<String, ExerciseState> _states = {}; final Map<String, int> _successThresholds = {};
final Map<String, int> _failThresholds = {};
final Map<String, double> _weights = {}; final Map<String, double> _weights = {};
final Map<String, int> _reps = {}; final Map<String, int> _reps = {};
@ -97,7 +97,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
for (final s in states) { for (final s in states) {
_states[s.name] = s; _successThresholds[s.name] = s.successThreshold;
_failThresholds[s.name] = s.failThreshold;
_weights[s.name] = s.weight; _weights[s.name] = s.weight;
_reps[s.name] = s.reps; _reps[s.name] = s.reps;
} }
@ -152,29 +153,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
}); });
} }
/// Opens [state]'s settings sheet. Every edit is saved as it happens, the Future<void> _onThresholdChanged(String name, int success, int fail) async {
/// same as from the workout tile; once the sheet closes the result goes to setState(() {
/// Firebase, so a reinstall before the next workout keeps it. _successThresholds[name] = success;
Future<void> _openExercise(ExerciseState state) async { _failThresholds[name] = fail;
var edited = false; });
await showExerciseSettingsSheet( await StorageService.instance.setExerciseThresholds(
context, name,
state: state, successThreshold: success,
onChanged: (updated) { failThreshold: fail,
edited = true;
setState(() => _states[updated.name] = updated);
unawaited(StorageService.instance.setExerciseSettings(updated));
},
);
if (!edited) return;
final pushed =
await (widget.progressionPusher ??
ProgressionSyncService().pushProgression)();
if (!mounted || pushed.changed) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Saved on this phone, not synced: ${pushed.reason}'),
),
); );
} }
@ -202,10 +189,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
onRepsChanged: _onRepsChanged, onRepsChanged: _onRepsChanged,
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
_ExercisesSection( _ThresholdsSection(
orderedNames: _orderedNames, orderedNames: _orderedNames,
states: _states, successThresholds: _successThresholds,
onOpen: (s) => unawaited(_openExercise(s)), failThresholds: _failThresholds,
onThresholdChanged: (name, success, fail) =>
unawaited(_onThresholdChanged(name, success, fail)),
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
_SyncSection( _SyncSection(

View File

@ -1,136 +0,0 @@
// The PER EXERCISE section: one row per exercise, opening the same settings
// sheet as the mode chip on its workout tile.
//
// See settings_screen_rows.dart for why this is a `part` file. Reusing the
// sheet rather than mirroring its controls here is the point: the two
// surfaces cannot drift apart when there is only one of them.
part of 'settings_screen.dart';
/// The PER EXERCISE section.
class _ExercisesSection extends StatelessWidget {
const _ExercisesSection({
required this.orderedNames,
required this.states,
required this.onOpen,
});
/// Exercise names in display order.
final List<String> orderedNames;
/// Stored state per exercise; a missing entry renders nothing.
final Map<String, ExerciseState> states;
/// Opens the settings sheet for the tapped exercise.
final ValueChanged<ExerciseState> onOpen;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('PER EXERCISE'),
const SizedBox(height: 4),
Text(
'Progression, warmup, rest and injury pause. '
'Same settings as the workout tile.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
const SizedBox(height: 12),
...orderedNames.map((name) {
final s = states[name];
if (s == null) return const SizedBox.shrink();
return _ExerciseSettingsRow(state: s, onTap: () => onOpen(s));
}),
],
);
}
}
/// `Squat` over `kg · ↑3 ↓2 · rest 3:00 / 5:00 · warmup 3:00`.
class _ExerciseSettingsRow extends StatelessWidget {
const _ExerciseSettingsRow({required this.state, required this.onTap});
final ExerciseState state;
final VoidCallback onTap;
String get _summary {
final s = state;
final mode = switch (s.mode) {
ProgressionMode.weight => 'kg',
ProgressionMode.reps => 'reps',
ProgressionMode.doubleProgression => '${s.repsLow}→${s.repsHigh} reps',
};
final warmup = s.hasWarmup
? 'warmup ${formatRest(s.restWarmupSecs)}'
: 'no warmup';
return '$mode · ↑${s.successThreshold} ↓${s.failThreshold} · '
'rest ${formatRest(s.restSuccessSecs)} / '
'${formatRest(s.restFailSecs)} · $warmup';
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final until = state.isPausedAt(DateTime.now()) ? state.pausedUntil : null;
return Semantics(
container: true,
button: true,
label: '${state.name} exercise settings',
excludeSemantics: true,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(AppRadius.sm),
child: Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(AppRadius.sm),
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
state.name,
style: TextStyle(
color: colorScheme.onSurface,
fontWeight: FontWeight.bold,
fontSize: AppTextSize.label,
),
),
const SizedBox(height: 4),
Text(
_summary,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
if (until != null) ...[
const SizedBox(height: 4),
Text(
'Paused — back on ${formatShortDate(until)}',
style: TextStyle(
color: colorScheme.error,
fontSize: AppTextSize.caption,
),
),
],
],
),
),
Icon(Icons.tune, color: colorScheme.onSurfaceVariant),
],
),
),
),
);
}
}

View File

@ -1,4 +1,4 @@
// The WEIGHTS and TARGET REPS sections. // The WEIGHTS, TARGET REPS and PROGRESSION THRESHOLDS sections.
// //
// A `part` for the same reason as settings_screen_sections.dart: these stay // A `part` for the same reason as settings_screen_sections.dart: these stay
// library-private. Each takes the ordered names plus the one map it reads, so // library-private. Each takes the ordered names plus the one map it reads, so
@ -103,3 +103,59 @@ class _RepsSection extends StatelessWidget {
); );
} }
} }
/// The PROGRESSION THRESHOLDS section: streak lengths before a weight change.
class _ThresholdsSection extends StatelessWidget {
const _ThresholdsSection({
required this.orderedNames,
required this.successThresholds,
required this.failThresholds,
required this.onThresholdChanged,
});
/// Exercise names in display order.
final List<String> orderedNames;
/// Successes before a weight increase, per exercise; defaults to 3.
final Map<String, int> successThresholds;
/// Failures before a weight decrease, per exercise; defaults to 2.
final Map<String, int> failThresholds;
/// Invoked with (name, successThreshold, failThreshold) on either change.
final void Function(String name, int success, int fail) onThresholdChanged;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _SectionHeader('PROGRESSION THRESHOLDS'),
const SizedBox(height: 4),
Text(
'Consecutive successes (↑) or failures (↓) '
'before weight changes.',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
const SizedBox(height: 12),
...orderedNames.map((name) {
final sThresh = successThresholds[name] ?? 3;
final fThresh = failThresholds[name] ?? 2;
return _ExerciseThresholdCard(
name: name,
successThreshold: sThresh,
failThreshold: fThresh,
onSuccessChanged: (v) =>
onThresholdChanged(name, v, failThresholds[name]!),
onFailChanged: (v) =>
onThresholdChanged(name, successThresholds[name]!, v),
);
}),
],
);
}
}

View File

@ -0,0 +1,123 @@
// The stepper button and the per-exercise threshold card.
//
// See settings_screen_rows.dart for why these are `part` files.
part of 'settings_screen.dart';
class _ExerciseThresholdCard extends StatelessWidget {
const _ExerciseThresholdCard({
required this.name,
required this.successThreshold,
required this.failThreshold,
required this.onSuccessChanged,
required this.onFailChanged,
});
final String name;
final int successThreshold;
final int failThreshold;
final ValueChanged<int> onSuccessChanged;
final ValueChanged<int> onFailChanged;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!;
return Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(AppRadius.sm),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: TextStyle(
color: colorScheme.onSurface,
fontWeight: FontWeight.bold,
fontSize: AppTextSize.label,
),
),
const SizedBox(height: 10),
_ThresholdRow(
label: '↑ Increase after N successes',
value: successThreshold,
color: status.success,
onChanged: onSuccessChanged,
),
const SizedBox(height: 6),
_ThresholdRow(
label: '↓ Decrease after N failures',
value: failThreshold,
color: colorScheme.error,
onChanged: onFailChanged,
),
],
),
);
}
}
class _ThresholdRow extends StatelessWidget {
const _ThresholdRow({
required this.label,
required this.value,
required this.color,
required this.onChanged,
});
final String label;
final int value;
final Color color;
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Row(
children: [
Expanded(
child: Text(
label,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
),
const SizedBox(width: 8),
for (int i = 1; i <= 5; i++)
Padding(
padding: const EdgeInsets.only(left: 4),
child: GestureDetector(
onTap: () => onChanged(i),
child: Container(
width: 32,
height: 32,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: i == value
? color
: colorScheme.surfaceContainerHighest,
),
alignment: Alignment.center,
child: Text(
'$i',
style: TextStyle(
// on-fill on the selected (filled) circle.
color: i == value
? colorScheme.onPrimary
: colorScheme.onSurface,
fontWeight: FontWeight.bold,
fontSize: AppTextSize.label,
),
),
),
),
),
],
);
}
}

View File

@ -1,12 +1,12 @@
// The public SettingsScreen widget and its injectable seams. // The public SettingsScreen widget and its injectable seams.
// //
// A `part` so the widget stays in the same library as its private state class // A `part` so the widget stays in the same library as its private state class
// while the constructor and its twelve test seams — each needing its own doc // while the constructor and its eleven test seams — each needing its own doc
// comment under `public_member_api_docs` — live somewhere the state logic can // comment under `public_member_api_docs` — live somewhere the state logic can
// be read without scrolling past them. // be read without scrolling past them.
part of 'settings_screen.dart'; part of 'settings_screen.dart';
/// Screen for per-exercise settings and manual weight/rep overrides. /// Screen for editing per-exercise thresholds and manual weight overrides.
/// ///
/// No [BackupSlot] is wired into the shared Sync settings screen: unlike the /// No [BackupSlot] is wired into the shared Sync settings screen: unlike the
/// notes app and home_inventory, workout_app has no user-facing export/import /// notes app and home_inventory, workout_app has no user-facing export/import
@ -33,7 +33,6 @@ class SettingsScreen extends StatefulWidget {
this.storageChecker, this.storageChecker,
this.storageRequester, this.storageRequester,
this.progressionPuller, this.progressionPuller,
this.progressionPusher,
}); });
/// Injectable HTTP client, passed through to [GitHubMirrorScreen] so its /// Injectable HTTP client, passed through to [GitHubMirrorScreen] so its
@ -85,10 +84,6 @@ class SettingsScreen extends StatefulWidget {
/// into the shared screen's connect flow. /// into the shared screen's connect flow.
final Future<ProgressionSyncResult> Function()? progressionPuller; final Future<ProgressionSyncResult> Function()? progressionPuller;
/// Pushes progression after an exercise's settings sheet closes with edits.
/// Injected so tests never reach Firebase.
final Future<ProgressionSyncResult> Function()? progressionPusher;
@override @override
State<SettingsScreen> createState() => _SettingsScreenState(); State<SettingsScreen> createState() => _SettingsScreenState();
} }

View File

@ -31,6 +31,7 @@ import 'package:workout_app/widgets/break_banner.dart';
import 'package:workout_app/widgets/exercise_tile.dart'; import 'package:workout_app/widgets/exercise_tile.dart';
import 'package:workout_app/widgets/workout_summary_dialog.dart'; import 'package:workout_app/widgets/workout_summary_dialog.dart';
part 'workout_screen_appbar.dart';
part 'workout_screen_body.dart'; part 'workout_screen_body.dart';
part 'workout_screen_breaks.dart'; part 'workout_screen_breaks.dart';
part 'workout_screen_dialogs.dart'; part 'workout_screen_dialogs.dart';
@ -73,6 +74,8 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
late List<List<int>> _doneReps; late List<List<int>> _doneReps;
late List<bool> _warmupTapped; late List<bool> _warmupTapped;
late DateTime _startTime; late DateTime _startTime;
late Timer _elapsedTimer;
Duration _elapsed = Duration.zero;
Map<String, ExerciseState> _exerciseStates = {}; Map<String, ExerciseState> _exerciseStates = {};
@ -109,6 +112,9 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
} else { } else {
_initFresh(); _initFresh();
} }
_elapsedTimer = Timer.periodic(const Duration(seconds: 1), (_) {
setState(() => _elapsed = DateTime.now().difference(_startTime));
});
// Coming back to the foreground is the one moment the countdown is // Coming back to the foreground is the one moment the countdown is
// guaranteed to be stale: ticks stop while the app is away, and the clock // guaranteed to be stale: ticks stop while the app is away, and the clock
// has to be re-read before the user sees a frame. // has to be re-read before the user sees a frame.
@ -143,15 +149,12 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
setState(() { setState(() {
_exerciseStates = {for (final s in states) s.name: s}; _exerciseStates = {for (final s in states) s.name: s};
}); });
// The first snapshot can go out before this load lands, and it would
// count a paused exercise's sets until the next tap. A no-op if the
// service has not started yet: start() builds its own, current one.
unawaited(_breaks.push(_buildSnapshot()));
} }
} }
@override @override
void dispose() { void dispose() {
_elapsedTimer.cancel();
_breakTimer?.cancel(); _breakTimer?.cancel();
_lifecycle.dispose(); _lifecycle.dispose();
// Deliberately NOT stopping the break service here. The back button pops // Deliberately NOT stopping the break service here. The back button pops
@ -172,6 +175,8 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
// ── Helpers ──────────────────────────────────────────────────────────────── // ── Helpers ────────────────────────────────────────────────────────────────
bool get _allSetsCompleted => _tapped.every((row) => row.every((t) => t));
/// Runs [fn] inside `setState` on behalf of this library's extensions. /// Runs [fn] inside `setState` on behalf of this library's extensions.
/// ///
/// `setState` is `@protected`, so an extension cannot call it directly. This /// `setState` is `@protected`, so an extension cannot call it directly. This
@ -188,6 +193,7 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
/// called from an extension, so the rest is in [_persistFinishedWorkout]. /// called from an extension, so the rest is in [_persistFinishedWorkout].
Future<void> _finishWorkout() async { Future<void> _finishWorkout() async {
SandboxLog.event('workout finish', {'type': widget.workoutType}); SandboxLog.event('workout finish', {'type': widget.workoutType});
_elapsedTimer.cancel();
_breakTimer?.cancel(); _breakTimer?.cancel();
// Before the state flips: the service must not outlive the workout, and // Before the state flips: the service must not outlive the workout, and
// with stopWithTask="false" nothing else will ever stop it. // with stopWithTask="false" nothing else will ever stop it.
@ -206,13 +212,16 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
// finish, so the route is pinned until the workout is finished or reset. // finish, so the route is pinned until the workout is finished or reset.
// Outside lock mode the back button behaves exactly as it always has. // Outside lock mode the back button behaves exactly as it always has.
canPop: !lockModeEnabled, canPop: !lockModeEnabled,
// No app bar (2026-09-27): the workout type and clock were not worth
// their height, and Reset/Finish now live in the rest strip. SafeArea
// keeps that strip out from under the status bar the app bar used to
// pad away.
child: Scaffold( child: Scaffold(
body: SafeArea( appBar: _WorkoutAppBar(
child: _WorkoutBody( title:
'Workout ${widget.workoutType} · ${_formatDuration(_elapsed)}',
finished: _finished,
allSetsCompleted: _allSetsCompleted,
onReset: () => unawaited(_confirmReset()),
onFinish: () => unawaited(_confirmFinish()),
),
body: _WorkoutBody(
exercises: widget.exercises, exercises: widget.exercises,
exerciseStates: _exerciseStates, exerciseStates: _exerciseStates,
tapped: _tapped, tapped: _tapped,
@ -220,16 +229,13 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
warmupTapped: _warmupTapped, warmupTapped: _warmupTapped,
inBreak: _inBreak, inBreak: _inBreak,
breakRemaining: _breakRemaining, breakRemaining: _breakRemaining,
finished: _finished, breakLabel: _breakLabel,
allSetsCompleted: _allSetsCompleted,
onSkipBreak: _skipBreak, onSkipBreak: _skipBreak,
onReset: () => unawaited(_confirmReset()),
onFinish: () => unawaited(_confirmFinish()),
onTapCircle: _tapCircle, onTapCircle: _tapCircle,
onLongPressCircle: _resetCircle, onLongPressCircle: _resetCircle,
onTapWarmup: _tapWarmup, onTapWarmup: _tapWarmup,
onSettingsChanged: (s) => unawaited(_onSettingsChanged(s)), onThresholdChanged: (name, success, fail) =>
), unawaited(_onThresholdChanged(name, success, fail)),
), ),
), ),
); );

View File

@ -0,0 +1,68 @@
// The active-workout app bar: elapsed clock plus Reset / Finish actions.
//
// See workout_screen_session.dart for why this is a `part`.
part of 'workout_screen.dart';
/// App bar for [WorkoutScreen], showing the running clock and the two
/// destructive actions.
///
/// A widget rather than a method so the state class stays under the file-length
/// cap; it reads only what it is given and never calls `setState` itself.
class _WorkoutAppBar extends StatelessWidget implements PreferredSizeWidget {
const _WorkoutAppBar({
required this.title,
required this.finished,
required this.allSetsCompleted,
required this.onReset,
required this.onFinish,
});
/// Full app-bar title, already including the formatted elapsed time.
final String title;
/// Whether the workout is over — hides both actions once true.
final bool finished;
/// Whether every set is tapped; Finish stays disabled until it is.
final bool allSetsCompleted;
/// Invoked when the user taps Reset.
final VoidCallback onReset;
/// Invoked when the user taps Finish.
final VoidCallback onFinish;
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!;
return AppBar(
automaticallyImplyLeading: false,
backgroundColor: colorScheme.surfaceContainerHigh,
title: Text(title, style: TextStyle(color: colorScheme.onSurface)),
actions: [
if (!finished)
TextButton(
onPressed: onReset,
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
),
if (!finished)
TextButton(
onPressed: allSetsCompleted ? onFinish : null,
child: Text(
'Finish',
style: TextStyle(
color: allSetsCompleted
? status.success
: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.bold,
),
),
),
],
);
}
}

View File

@ -22,22 +22,19 @@ class _WorkoutBody extends StatelessWidget {
required this.warmupTapped, required this.warmupTapped,
required this.inBreak, required this.inBreak,
required this.breakRemaining, required this.breakRemaining,
required this.finished, required this.breakLabel,
required this.allSetsCompleted,
required this.onSkipBreak, required this.onSkipBreak,
required this.onReset,
required this.onFinish,
required this.onTapCircle, required this.onTapCircle,
required this.onLongPressCircle, required this.onLongPressCircle,
required this.onTapWarmup, required this.onTapWarmup,
required this.onSettingsChanged, required this.onThresholdChanged,
}); });
/// The exercises in this session, in display order. /// The exercises in this session, in display order.
final List<Exercise> exercises; final List<Exercise> exercises;
/// Progression state per exercise name; a missing entry (not loaded yet) /// Progression state per exercise name; a missing entry falls back to
/// falls back to [ExerciseState.initial] for this session's targets. /// the tile's default thresholds.
final Map<String, ExerciseState> exerciseStates; final Map<String, ExerciseState> exerciseStates;
/// Per-exercise, per-set completion flags. /// Per-exercise, per-set completion flags.
@ -55,21 +52,12 @@ class _WorkoutBody extends StatelessWidget {
/// Seconds left in the current rest period. /// Seconds left in the current rest period.
final int breakRemaining; final int breakRemaining;
/// Whether the workout is over; hides Reset and Finish. /// Human-readable label for the current rest period.
final bool finished; final String breakLabel;
/// Whether every set is recorded; enables Finish.
final bool allSetsCompleted;
/// Invoked when the user skips the rest period. /// Invoked when the user skips the rest period.
final VoidCallback onSkipBreak; final VoidCallback onSkipBreak;
/// Invoked when the user taps Reset.
final VoidCallback onReset;
/// Invoked when the user taps Finish.
final VoidCallback onFinish;
/// Invoked with (exerciseIndex, setIndex) when a set circle is tapped. /// Invoked with (exerciseIndex, setIndex) when a set circle is tapped.
final void Function(int exIdx, int setIdx) onTapCircle; final void Function(int exIdx, int setIdx) onTapCircle;
@ -79,8 +67,8 @@ class _WorkoutBody extends StatelessWidget {
/// Invoked with the exercise index when its warmup is tapped. /// Invoked with the exercise index when its warmup is tapped.
final void Function(int exIdx) onTapWarmup; final void Function(int exIdx) onTapWarmup;
/// Invoked with the edited state after every settings-sheet change. /// Invoked with (exerciseName, successThreshold, failThreshold) on edit.
final ValueChanged<ExerciseState> onSettingsChanged; final void Function(String name, int success, int fail) onThresholdChanged;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -89,11 +77,8 @@ class _WorkoutBody extends StatelessWidget {
BreakBanner( BreakBanner(
active: inBreak, active: inBreak,
breakRemaining: breakRemaining, breakRemaining: breakRemaining,
breakLabel: inBreak ? breakLabel : 'Rest',
onSkip: onSkipBreak, onSkip: onSkipBreak,
finished: finished,
canFinish: allSetsCompleted,
onReset: onReset,
onFinish: onFinish,
), ),
Expanded( Expanded(
child: LayoutBuilder( child: LayoutBuilder(
@ -123,17 +108,20 @@ class _WorkoutBody extends StatelessWidget {
} }
Widget _tile(int i) { Widget _tile(int i) {
final ex = exercises[i]; final exName = exercises[i].name;
final state = exerciseStates[exName];
return ExerciseTile( return ExerciseTile(
exercise: ex, exercise: exercises[i],
state: exerciseStates[ex.name] ?? ExerciseState.initial(ex),
tapped: tapped[i], tapped: tapped[i],
doneReps: doneReps[i], doneReps: doneReps[i],
warmupTapped: warmupTapped[i], warmupTapped: warmupTapped[i],
successThreshold: state?.successThreshold ?? 3,
failThreshold: state?.failThreshold ?? 2,
onTapCircle: (s) => onTapCircle(i, s), onTapCircle: (s) => onTapCircle(i, s),
onLongPressCircle: (s) => onLongPressCircle(i, s), onLongPressCircle: (s) => onLongPressCircle(i, s),
onTapWarmup: () => onTapWarmup(i), onTapWarmup: () => onTapWarmup(i),
onSettingsChanged: onSettingsChanged, onThresholdChanged: (success, fail) =>
onThresholdChanged(exName, success, fail),
); );
} }
} }

View File

@ -1,10 +1,15 @@
// Rest-period timers, per-exercise state lookups and settings edits. // Rest-period timers and per-exercise threshold edits.
// //
// See workout_screen_session.dart for why this is a `part`. `setState` is // See workout_screen_session.dart for why this is a `part`. `setState` is
// `@protected` and unreachable from an extension, so these mutate through the // `@protected` and unreachable from an extension, so these mutate through the
// state class's `_applyBreakState` shim instead. // state class's `_applyBreakState` shim instead.
part of 'workout_screen.dart'; part of 'workout_screen.dart';
// Rest lengths (the sandbox flavor overrides them all in _startBreak).
const _successBreakSecs = 180; // 3 min after successful set
const _failBreakSecs = 300; // 5 min after failed set
const _warmupBreakSecs = 180; // 3 min after warmup
// How late a restored break's end cue may still be played. Long enough to // How late a restored break's end cue may still be played. Long enough to
// cover the app being killed and reopened mid-rest; short enough that // cover the app being killed and reopened mid-rest; short enough that
// resuming yesterday's session does not blast the sound across the gym. // resuming yesterday's session does not blast the sound across the gym.
@ -12,29 +17,6 @@ const _expiredBreakGraceSecs = 120;
/// Starting, ticking, cancelling and finishing the rest period between sets. /// Starting, ticking, cancelling and finishing the rest period between sets.
extension _WorkoutScreenBreaks on _WorkoutScreenState { extension _WorkoutScreenBreaks on _WorkoutScreenState {
/// Every set recorded, not counting paused exercises: those have no sets
/// to tap and are recorded as failed at Finish.
bool get _allSetsCompleted {
for (var i = 0; i < _tapped.length; i++) {
if (!_isPaused(i) && !_tapped[i].every((t) => t)) return false;
}
return true;
}
/// Whether exercise [exIdx] is on an injury pause right now.
bool _isPaused(int exIdx) =>
_exerciseStates[widget.exercises[exIdx].name]?.isPausedAt(
DateTime.now(),
) ??
false;
/// Exercise [exIdx]'s stored state, or its defaults while the states are
/// still loading: that is where its rest lengths live.
ExerciseState _stateOf(int exIdx) {
final ex = widget.exercises[exIdx];
return _exerciseStates[ex.name] ?? ExerciseState.initial(ex);
}
void _startBreak(int secs, String label, int exIdx, int setIdx) { void _startBreak(int secs, String label, int exIdx, int setIdx) {
// The one place every rest is born, so the sandbox's short override // The one place every rest is born, so the sandbox's short override
// applies to warmup, success and fail rests alike. // applies to warmup, success and fail rests alike.
@ -42,9 +24,6 @@ extension _WorkoutScreenBreaks on _WorkoutScreenState {
final restLabel = Sandbox.restLabel(label); final restLabel = Sandbox.restLabel(label);
SandboxLog.event('break start', { SandboxLog.event('break start', {
'secs': restSecs, 'secs': restSecs,
// The exercise's own rest, before the sandbox override: the only way
// to see per-exercise rest lengths in the sandbox flavor.
'planned': secs,
'label': restLabel, 'label': restLabel,
'exercise': exIdx, 'exercise': exIdx,
'set': setIdx, 'set': setIdx,
@ -107,33 +86,16 @@ extension _WorkoutScreenBreaks on _WorkoutScreenState {
unawaited(_saveActiveSession()); unawaited(_saveActiveSession());
} }
/// Persists an edit from an exercise's settings sheet and shows it. Future<void> _onThresholdChanged(String name, int success, int fail) async {
/// await StorageService.instance.setExerciseThresholds(
/// Turning a warmup off while its own rest is running ends that rest: the name,
/// user just said the warmup is not part of this exercise any more. successThreshold: success,
/// Pausing the exercise ends any rest of it, for the same reason. failThreshold: fail,
Future<void> _onSettingsChanged(ExerciseState updated) async { );
SandboxLog.event('exercise settings', { if (mounted) {
'exercise': updated.name, _applyBreakState(() {
'mode': updated.mode.storageKey, _writeThresholds(name, success, fail);
'repsHigh': updated.repsHigh,
'repsLow': updated.repsLow,
'warmup': updated.hasWarmup,
'pausedUntil': updated.pausedUntil?.toIso8601String(),
'restSuccess': updated.restSuccessSecs,
'restFail': updated.restFailSecs,
'restWarmup': updated.restWarmupSecs,
}); });
await StorageService.instance.setExerciseSettings(updated);
if (!mounted) return;
_applyBreakState(() => _exerciseStates[updated.name] = updated);
final exIdx = widget.exercises.indexWhere((e) => e.name == updated.name);
final paused = updated.isPausedAt(DateTime.now());
final warmupRestGone = !updated.hasWarmup && _breakForSetIdx == -1;
if (_inBreak && _breakForExIdx == exIdx && (paused || warmupRestGone)) {
_cancelBreak();
} }
// Always: a pause changes the notification's "sets left" and next set.
unawaited(_saveActiveSession());
} }
} }

View File

@ -5,6 +5,7 @@ part of 'workout_screen.dart';
/// The write-everything step that runs once a workout is marked finished. /// The write-everything step that runs once a workout is marked finished.
extension _WorkoutScreenFinish on _WorkoutScreenState { extension _WorkoutScreenFinish on _WorkoutScreenState {
/// Writes the finished session, applies progression, and shows the summary. /// Writes the finished session, applies progression, and shows the summary.
/// ///
/// Called by [_WorkoutScreenState._finishWorkout], which owns the `setState` /// Called by [_WorkoutScreenState._finishWorkout], which owns the `setState`
@ -15,19 +16,15 @@ extension _WorkoutScreenFinish on _WorkoutScreenState {
for (var i = 0; i < widget.exercises.length; i++) { for (var i = 0; i < widget.exercises.length; i++) {
final ex = widget.exercises[i]; final ex = widget.exercises[i];
// A paused exercise is recorded as FAILED every time, whatever was
// tapped before the pause: the user asked for it to step down while
// they are injured, not to come back at the load it left with.
final paused = _isPaused(i);
results.add( results.add(
ExerciseResult( ExerciseResult(
exercise: ex, exercise: ex,
warmupDone: !paused && _warmupTapped[i], warmupDone: _warmupTapped[i],
sets: List.generate( sets: List.generate(
ex.sets, ex.sets,
(s) => SetResult( (s) => SetResult(
targetReps: ex.reps, targetReps: ex.reps,
doneReps: !paused && _tapped[i][s] ? _doneReps[i][s] : 0, doneReps: _tapped[i][s] ? _doneReps[i][s] : 0,
weight: ex.weight, weight: ex.weight,
), ),
), ),
@ -103,8 +100,10 @@ extension _WorkoutScreenFinish on _WorkoutScreenState {
showDialog<void>( showDialog<void>(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
builder: (_) => builder: (_) => WorkoutSummaryDialog(
WorkoutSummaryDialog(session: session, syncResult: syncResult), session: session,
syncResult: syncResult,
),
), ),
); );
} }

View File

@ -17,11 +17,6 @@ extension _WorkoutScreenIntents on _WorkoutScreenState {
workoutType: widget.workoutType, workoutType: widget.workoutType,
breakEndMs: _breakClock?.endTime.millisecondsSinceEpoch ?? 0, breakEndMs: _breakClock?.endTime.millisecondsSinceEpoch ?? 0,
breakDurationSecs: _breakDurationSecs, breakDurationSecs: _breakDurationSecs,
breakFailSecs: Sandbox.rest(
_breakForExIdx >= 0 && _breakForExIdx < widget.exercises.length
? _stateOf(_breakForExIdx).restFailSecs
: kDefaultRestFailSecs,
),
breakLabel: _breakLabel, breakLabel: _breakLabel,
breakForExIdx: _breakForExIdx, breakForExIdx: _breakForExIdx,
breakForSetIdx: _breakForSetIdx, breakForSetIdx: _breakForSetIdx,
@ -57,9 +52,6 @@ extension _WorkoutScreenIntents on _WorkoutScreenState {
} }
int? _firstUntappedIn(int exIdx) { int? _firstUntappedIn(int exIdx) {
// A paused exercise has nothing left to do, so the notification never
// offers it as the next set.
if (_isPaused(exIdx)) return null;
for (var s = 0; s < _tapped[exIdx].length; s++) { for (var s = 0; s < _tapped[exIdx].length; s++) {
if (!_tapped[exIdx][s]) return s; if (!_tapped[exIdx][s]) return s;
} }
@ -82,9 +74,8 @@ extension _WorkoutScreenIntents on _WorkoutScreenState {
int _setsRemaining() { int _setsRemaining() {
var count = 0; var count = 0;
for (var ex = 0; ex < _tapped.length; ex++) { for (final row in _tapped) {
if (_isPaused(ex)) continue; for (final done in row) {
for (final done in _tapped[ex]) {
if (!done) count++; if (!done) count++;
} }
} }
@ -140,10 +131,6 @@ extension _WorkoutScreenIntents on _WorkoutScreenState {
_skipBreak(); _skipBreak();
case BreakIntentKind.done: case BreakIntentKind.done:
if (!_isValidSet(intent)) return; if (!_isValidSet(intent)) return;
if (_isPaused(intent.exIdx)) {
_dropIntent(intent, 'that exercise is paused');
return;
}
if (_tapped[intent.exIdx][intent.setIdx]) { if (_tapped[intent.exIdx][intent.setIdx]) {
_dropIntent(intent, 'that set was already recorded'); _dropIntent(intent, 'that set was already recorded');
return; return;
@ -165,8 +152,7 @@ extension _WorkoutScreenIntents on _WorkoutScreenState {
bool _isValidSet(BreakIntent intent) { bool _isValidSet(BreakIntent intent) {
final exOk = intent.exIdx >= 0 && intent.exIdx < widget.exercises.length; final exOk = intent.exIdx >= 0 && intent.exIdx < widget.exercises.length;
if (!exOk || if (!exOk || intent.setIdx < 0 ||
intent.setIdx < 0 ||
intent.setIdx >= _tapped[intent.exIdx].length) { intent.setIdx >= _tapped[intent.exIdx].length) {
_dropIntent(intent, 'it points at a set this workout does not have'); _dropIntent(intent, 'it points at a set this workout does not have');
return false; return false;

View File

@ -123,7 +123,7 @@ extension _WorkoutScreenSession on _WorkoutScreenState {
} }
/// When the user decrements reps on the set that triggered the current break, /// When the user decrements reps on the set that triggered the current break,
/// switch between the exercise's success and fail rest lengths. /// switch between 3-min (success) and 5-min (fail) durations.
void _recomputeBreakIfNeeded(int exIdx, int setIdx) { void _recomputeBreakIfNeeded(int exIdx, int setIdx) {
// Read the clock ONCE. `_inBreak` re-reads DateTime.now() every time it is // Read the clock ONCE. `_inBreak` re-reads DateTime.now() every time it is
// touched, so guarding on it and then dereferencing `_breakClock!` is a // touched, so guarding on it and then dereferencing `_breakClock!` is a
@ -134,14 +134,15 @@ extension _WorkoutScreenSession on _WorkoutScreenState {
if (_breakForSetIdx == -1) return; // warmup break, never recompute if (_breakForSetIdx == -1) return; // warmup break, never recompute
final succeeded = _doneReps[exIdx][setIdx] >= widget.exercises[exIdx].reps; final succeeded = _doneReps[exIdx][setIdx] >= widget.exercises[exIdx].reps;
final state = _stateOf(exIdx);
final newDuration = Sandbox.rest( final newDuration = Sandbox.rest(
succeeded ? state.restSuccessSecs : state.restFailSecs, succeeded ? _successBreakSecs : _failBreakSecs,
); );
if (newDuration == clock.durationSecs) return; if (newDuration == clock.durationSecs) return;
_breakClock = clock.withDuration(newDuration); _breakClock = clock.withDuration(newDuration);
_breakLabel = Sandbox.restLabel('Rest'); _breakLabel = Sandbox.restLabel(
succeeded ? 'Rest (3 min — well done!)' : 'Rest (5 min — keep going!)',
);
} }
/// True when [setIdx] is the last untapped set of exercise [exIdx]. /// True when [setIdx] is the last untapped set of exercise [exIdx].
@ -160,11 +161,9 @@ extension _WorkoutScreenSession on _WorkoutScreenState {
_Rest? _restAfterSet(int exIdx, int setIdx) { _Rest? _restAfterSet(int exIdx, int setIdx) {
if (_isLastSetOfExercise(exIdx, setIdx)) return null; if (_isLastSetOfExercise(exIdx, setIdx)) return null;
final succeeded = _doneReps[exIdx][setIdx] >= widget.exercises[exIdx].reps; final succeeded = _doneReps[exIdx][setIdx] >= widget.exercises[exIdx].reps;
final state = _stateOf(exIdx); return succeeded
return _Rest( ? const _Rest(_successBreakSecs, 'Rest (3 min — well done!)')
succeeded ? state.restSuccessSecs : state.restFailSecs, : const _Rest(_failBreakSecs, 'Rest (5 min — keep going!)');
'Rest',
);
} }
/// Plays the sound and haptic that tell the user the rest period is over. /// Plays the sound and haptic that tell the user the rest period is over.
@ -186,6 +185,26 @@ extension _WorkoutScreenSession on _WorkoutScreenState {
} }
} }
/// Rewrites [name]'s thresholds in `_exerciseStates`, in place.
///
/// A no-op when the screen holds no state for [name], so editing an unloaded
/// exercise cannot insert a half-built entry.
void _writeThresholds(String name, int success, int fail) {
final s = _exerciseStates[name];
if (s != null) {
_exerciseStates[name] = ExerciseState(
name: s.name,
weight: s.weight,
reps: s.reps,
successStreak: s.successStreak,
failStreak: s.failStreak,
maxWeight: s.maxWeight,
successThreshold: success,
failThreshold: fail,
);
}
}
/// Ends the break early at the user's request and re-persists the session. /// Ends the break early at the user's request and re-persists the session.
void _skipBreak() { void _skipBreak() {
SandboxLog.event('break skip'); SandboxLog.event('break skip');
@ -194,6 +213,13 @@ extension _WorkoutScreenSession on _WorkoutScreenState {
} }
} }
/// Formats [d] as `h:mm:ss`, dropping the hours part under an hour.
String _formatDuration(Duration d) {
final m = d.inMinutes.remainder(60).toString().padLeft(2, '0');
final s = d.inSeconds.remainder(60).toString().padLeft(2, '0');
return '${d.inHours > 0 ? '${d.inHours}:' : ''}$m:$s';
}
/// A rest period's duration and the label shown on the break banner. /// A rest period's duration and the label shown on the break banner.
class _Rest { class _Rest {
const _Rest(this.seconds, this.label); const _Rest(this.seconds, this.label);
@ -201,6 +227,6 @@ class _Rest {
/// How long the rest lasts. /// How long the rest lasts.
final int seconds; final int seconds;
/// Notification text for this rest. /// Banner text explaining why this rest length was chosen.
final String label; final String label;
} }

View File

@ -52,7 +52,7 @@ extension _WorkoutScreenTaps on _WorkoutScreenState {
if (_finished || _warmupTapped[exIdx]) return; if (_finished || _warmupTapped[exIdx]) return;
_applyBreakState(() => _warmupTapped[exIdx] = true); _applyBreakState(() => _warmupTapped[exIdx] = true);
if (!_inBreak) { if (!_inBreak) {
_startBreak(_stateOf(exIdx).restWarmupSecs, 'Warmup rest', exIdx, -1); _startBreak(_warmupBreakSecs, 'Warmup rest (3 min)', exIdx, -1);
} }
unawaited(_saveActiveSession(toFirebase: true)); unawaited(_saveActiveSession(toFirebase: true));
} }

View File

@ -175,7 +175,11 @@ class BreakTaskHandler {
/// The UI overwrites this with the truth as soon as it drains the queue — /// The UI overwrites this with the truth as soon as it drains the queue —
/// but it may be dead, and a button that visibly does nothing reads as /// but it may be dead, and a button that visibly does nothing reads as
/// broken. Only the fields the press certainly changes are moved. /// broken. Only the fields the press certainly changes are moved.
BreakSnapshot _predict(BreakIntentKind kind, BreakSnapshot s, DateTime now) { BreakSnapshot _predict(
BreakIntentKind kind,
BreakSnapshot s,
DateTime now,
) {
switch (kind) { switch (kind) {
case BreakIntentKind.skipBreak: case BreakIntentKind.skipBreak:
return s.copyWith(breakEndMs: 0); return s.copyWith(breakEndMs: 0);
@ -187,9 +191,8 @@ class BreakTaskHandler {
case BreakIntentKind.minusRep: case BreakIntentKind.minusRep:
if (!s.hasBreak || s.breakForSetIdx < 0) return s; if (!s.hasBreak || s.breakForSetIdx < 0) return s;
// A decrement turns a success into a failure, which is the longer // A decrement turns a success into a failure, which is the longer
// rest. Re-cut from the start, exactly as the screen does, to the // rest. Re-cut from the start, exactly as the screen does.
// length the screen sent for this exercise. const failSecs = 300;
final failSecs = s.breakFailSecs;
final clock = BreakClock( final clock = BreakClock(
endTime: DateTime.fromMillisecondsSinceEpoch(s.breakEndMs), endTime: DateTime.fromMillisecondsSinceEpoch(s.breakEndMs),
durationSecs: s.breakDurationSecs, durationSecs: s.breakDurationSecs,
@ -197,7 +200,7 @@ class BreakTaskHandler {
return s.copyWith( return s.copyWith(
breakEndMs: clock.endTime.millisecondsSinceEpoch, breakEndMs: clock.endTime.millisecondsSinceEpoch,
breakDurationSecs: failSecs, breakDurationSecs: failSecs,
breakLabel: 'Rest', breakLabel: 'Rest (5 min — keep going!)',
); );
} }
} }

View File

@ -100,21 +100,8 @@ class ProgressionSyncService {
'max_weight': s.maxWeight, 'max_weight': s.maxWeight,
'success_threshold': s.successThreshold, 'success_threshold': s.successThreshold,
'fail_threshold': s.failThreshold, 'fail_threshold': s.failThreshold,
'progression_mode': s.mode.storageKey,
'reps_high': s.repsHigh,
'reps_low': s.repsLow,
'has_warmup': s.hasWarmup,
'paused_until': switch (s.pausedUntil) {
null => null,
final d => formatPauseDate(d),
},
'rest_success_secs': s.restSuccessSecs,
'rest_fail_secs': s.restFailSecs,
'rest_warmup_secs': s.restWarmupSecs,
}; };
// Every field after fail_threshold is lenient: records pushed before it
// existed must still restore, with the meaning a NULL column has locally.
static ExerciseState _stateFromJson(Map<String, dynamic> j) => ExerciseState( static ExerciseState _stateFromJson(Map<String, dynamic> j) => ExerciseState(
name: j['name']! as String, name: j['name']! as String,
weight: (j['weight']! as num).toDouble(), weight: (j['weight']! as num).toDouble(),
@ -124,17 +111,6 @@ class ProgressionSyncService {
maxWeight: (j['max_weight']! as num).toDouble(), maxWeight: (j['max_weight']! as num).toDouble(),
successThreshold: (j['success_threshold'] as num?)?.toInt() ?? 3, successThreshold: (j['success_threshold'] as num?)?.toInt() ?? 3,
failThreshold: (j['fail_threshold'] as num?)?.toInt() ?? 2, failThreshold: (j['fail_threshold'] as num?)?.toInt() ?? 2,
mode: ProgressionMode.parse(j['progression_mode']),
repsHigh: (j['reps_high'] as num?)?.toInt() ?? kDefaultRepsHigh,
repsLow: (j['reps_low'] as num?)?.toInt() ?? kDefaultRepsLow,
hasWarmup: j['has_warmup'] as bool? ?? planHasWarmup(j['name']! as String),
pausedUntil: parsePauseDate(j['paused_until']),
restSuccessSecs:
(j['rest_success_secs'] as num?)?.toInt() ?? kDefaultRestSuccessSecs,
restFailSecs:
(j['rest_fail_secs'] as num?)?.toInt() ?? kDefaultRestFailSecs,
restWarmupSecs:
(j['rest_warmup_secs'] as num?)?.toInt() ?? kDefaultRestWarmupSecs,
); );
/// The remote path holding [name]'s progression record. /// The remote path holding [name]'s progression record.
@ -173,7 +149,9 @@ class ProgressionSyncService {
final text = await client.getFileText(path); final text = await client.getFileText(path);
if (text == null) return null; if (text == null) return null;
try { try {
final record = Record.fromJson(jsonDecode(text) as Map<String, dynamic>); final record = Record.fromJson(
jsonDecode(text) as Map<String, dynamic>,
);
final field = record.fields[_payloadField]; final field = record.fields[_payloadField];
if (field == null) return null; if (field == null) return null;
final payload = field.$1; final payload = field.$1;

View File

@ -9,23 +9,55 @@ import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart'; import 'package:sqflite/sqflite.dart';
import 'package:workout_app/models/exercise.dart'; import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/models/workout_plan.dart'; import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/backup_service.dart'; import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/progression_sync_service.dart'; import 'package:workout_app/services/progression_sync_service.dart';
// Re-exported: ExerciseState was defined here until it moved to models/, and
// every caller still reaches it through this import.
export 'package:workout_app/models/exercise_state.dart';
export 'package:workout_app/models/progression.dart';
part 'storage_service_backup.dart'; part 'storage_service_backup.dart';
part 'storage_service_exercises.dart'; part 'storage_service_exercises.dart';
part 'storage_service_sandbox.dart'; part 'storage_service_sandbox.dart';
part 'storage_service_schema.dart'; part 'storage_service_schema.dart';
part 'storage_service_sessions.dart'; part 'storage_service_sessions.dart';
/// Per-exercise progression state stored in SQLite.
class ExerciseState {
/// Creates an [ExerciseState] with all required progression fields.
ExerciseState({
required this.name,
required this.weight,
required this.reps,
required this.successStreak,
required this.failStreak,
required this.maxWeight,
required this.successThreshold,
required this.failThreshold,
});
/// Exercise name (matches [Exercise.name], used as primary key).
final String name;
/// Current working weight in kg.
double weight;
/// Current target reps per set.
int reps;
/// Consecutive successful workouts since last progression.
int successStreak;
/// Consecutive failed workouts since last regression.
int failStreak;
/// Weight cap; reps increase instead of weight when this is reached.
final double maxWeight;
/// Successes needed in a row before weight/reps increase.
int successThreshold;
/// Failures needed in a row before weight decreases.
int failThreshold;
}
/// Singleton SQLite service for workout data persistence. /// Singleton SQLite service for workout data persistence.
class StorageService { class StorageService {
StorageService._(); StorageService._();
@ -78,7 +110,7 @@ class StorageService {
// coverage:ignore-end // coverage:ignore-end
_db = await openDatabase( _db = await openDatabase(
dbPath, dbPath,
version: 6, version: 3,
onCreate: _createSchema, onCreate: _createSchema,
onUpgrade: _migrateSchema, onUpgrade: _migrateSchema,
// In tests resetForTesting() reopens a ':memory:' DB per test; sqflite's // In tests resetForTesting() reopens a ':memory:' DB per test; sqflite's

View File

@ -17,9 +17,8 @@ extension StorageServiceExercises on StorageService {
); );
if (rows.isEmpty) return null; if (rows.isEmpty) return null;
final r = rows.first; final r = rows.first;
final warmup = r['has_warmup'] as int?;
return ExerciseState( return ExerciseState(
name: name, name: r['name']! as String,
weight: r['weight']! as double, weight: r['weight']! as double,
reps: r['reps']! as int, reps: r['reps']! as int,
successStreak: r['success_streak']! as int, successStreak: r['success_streak']! as int,
@ -27,14 +26,6 @@ extension StorageServiceExercises on StorageService {
maxWeight: r['max_weight']! as double, maxWeight: r['max_weight']! as double,
successThreshold: r['success_threshold'] as int? ?? 3, successThreshold: r['success_threshold'] as int? ?? 3,
failThreshold: r['fail_threshold'] as int? ?? 2, failThreshold: r['fail_threshold'] as int? ?? 2,
mode: ProgressionMode.parse(r['progression_mode']),
repsHigh: r['reps_high'] as int? ?? kDefaultRepsHigh,
repsLow: r['reps_low'] as int? ?? kDefaultRepsLow,
hasWarmup: warmup == null ? planHasWarmup(name) : warmup != 0,
pausedUntil: parsePauseDate(r['paused_until']),
restSuccessSecs: r['rest_success_secs']! as int,
restFailSecs: r['rest_fail_secs']! as int,
restWarmupSecs: r['rest_warmup_secs']! as int,
); );
} }
@ -57,49 +48,15 @@ extension StorageServiceExercises on StorageService {
}) async { }) async {
await _db.update( await _db.update(
'exercise_state', 'exercise_state',
{'success_threshold': successThreshold, 'fail_threshold': failThreshold}, {
'success_threshold': successThreshold,
'fail_threshold': failThreshold,
},
where: 'name = ?', where: 'name = ?',
whereArgs: [name], whereArgs: [name],
); );
} }
/// Updates how [state]'s exercise progresses, whether it warms up and how
/// long it rests.
///
/// Streaks are kept: they count workouts, not a mode, and switching mode
/// mid-streak should not cost the user the sessions already banked. The
/// current weight and reps are untouched too — the new mode takes effect
/// at the next finished workout.
Future<void> setExerciseSettings(ExerciseState state) async {
await _db.update(
'exercise_state',
{
'success_threshold': state.successThreshold,
'fail_threshold': state.failThreshold,
'progression_mode': state.mode.storageKey,
'reps_high': state.repsHigh,
'reps_low': state.repsLow,
'has_warmup': state.hasWarmup ? 1 : 0,
'paused_until': _pauseColumn(state),
..._restColumnValues(state),
},
where: 'name = ?',
whereArgs: [state.name],
);
unawaited(_backupNow());
}
Map<String, int> _restColumnValues(ExerciseState s) => {
'rest_success_secs': s.restSuccessSecs,
'rest_fail_secs': s.restFailSecs,
'rest_warmup_secs': s.restWarmupSecs,
};
String? _pauseColumn(ExerciseState s) {
final until = s.pausedUntil;
return until == null ? null : formatPauseDate(until);
}
/// Sets the target reps for [name], resetting streaks. /// Sets the target reps for [name], resetting streaks.
/// ///
/// Progression can only ever raise reps (by one, and only once an exercise /// Progression can only ever raise reps (by one, and only once an exercise
@ -137,12 +94,6 @@ extension StorageServiceExercises on StorageService {
'max_weight': state.maxWeight, 'max_weight': state.maxWeight,
'success_threshold': state.successThreshold, 'success_threshold': state.successThreshold,
'fail_threshold': state.failThreshold, 'fail_threshold': state.failThreshold,
'progression_mode': state.mode.storageKey,
'reps_high': state.repsHigh,
'reps_low': state.repsLow,
'has_warmup': state.hasWarmup ? 1 : 0,
'paused_until': _pauseColumn(state),
..._restColumnValues(state),
}, conflictAlgorithm: ConflictAlgorithm.replace); }, conflictAlgorithm: ConflictAlgorithm.replace);
} }
@ -170,13 +121,7 @@ extension StorageServiceExercises on StorageService {
result.add(ex); result.add(ex);
// coverage:ignore-end // coverage:ignore-end
} else { } else {
result.add( result.add(ex.copyWith(weight: state.weight, reps: state.reps));
ex.copyWith(
weight: state.weight,
reps: state.reps,
hasWarmup: state.hasWarmup,
),
);
} }
} }
return result; return result;

View File

@ -4,14 +4,9 @@
// See storage_service_backup.dart for why these are `part` extensions. // See storage_service_backup.dart for why these are `part` extensions.
part of 'storage_service.dart'; part of 'storage_service.dart';
/// The v6 rest-length columns, shared by create and migrate.
const _restColumns =
'rest_success_secs INTEGER NOT NULL DEFAULT $kDefaultRestSuccessSecs, '
'rest_fail_secs INTEGER NOT NULL DEFAULT $kDefaultRestFailSecs, '
'rest_warmup_secs INTEGER NOT NULL DEFAULT $kDefaultRestWarmupSecs';
/// Schema creation, migration, and seeding. /// Schema creation, migration, and seeding.
extension StorageServiceSchema on StorageService { extension StorageServiceSchema on StorageService {
Future<void> _createSchema(Database db, int version) async { Future<void> _createSchema(Database db, int version) async {
await db.execute(''' await db.execute('''
CREATE TABLE exercise_state ( CREATE TABLE exercise_state (
@ -22,13 +17,7 @@ extension StorageServiceSchema on StorageService {
fail_streak INTEGER NOT NULL DEFAULT 0, fail_streak INTEGER NOT NULL DEFAULT 0,
max_weight REAL NOT NULL, max_weight REAL NOT NULL,
success_threshold INTEGER NOT NULL DEFAULT 3, success_threshold INTEGER NOT NULL DEFAULT 3,
fail_threshold INTEGER NOT NULL DEFAULT 2, fail_threshold INTEGER NOT NULL DEFAULT 2
progression_mode TEXT NOT NULL DEFAULT 'weight',
reps_high INTEGER NOT NULL DEFAULT $kDefaultRepsHigh,
reps_low INTEGER NOT NULL DEFAULT $kDefaultRepsLow,
has_warmup INTEGER,
paused_until TEXT,
$_restColumns
) )
'''); ''');
await db.execute(''' await db.execute('''
@ -80,31 +69,6 @@ extension StorageServiceSchema on StorageService {
'(id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL)', '(id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL)',
); );
} }
if (oldVersion < 4) {
// has_warmup is left NULL: that reads as the plan's default (see
// planHasWarmup), so existing rows keep exactly the warmups they had.
for (final column in [
"progression_mode TEXT NOT NULL DEFAULT 'weight'",
'reps_high INTEGER NOT NULL DEFAULT $kDefaultRepsHigh',
'reps_low INTEGER NOT NULL DEFAULT $kDefaultRepsLow',
'has_warmup INTEGER',
]) {
await db.execute('ALTER TABLE exercise_state ADD COLUMN $column');
}
}
if (oldVersion < 5) {
// NULL = not paused.
await db.execute(
'ALTER TABLE exercise_state ADD COLUMN paused_until TEXT',
);
}
if (oldVersion < 6) {
// NOT NULL with a default, so every existing row -- and every v5 row a
// raw backup restore inserts later -- gets the old fixed rests.
for (final column in _restColumns.split(', ')) {
await db.execute('ALTER TABLE exercise_state ADD COLUMN $column');
}
}
} }
Future<void> _seedDefaultsIfNeeded() async { Future<void> _seedDefaultsIfNeeded() async {
@ -124,13 +88,6 @@ extension StorageServiceSchema on StorageService {
'max_weight': ex.maxWeight, 'max_weight': ex.maxWeight,
'success_threshold': 3, 'success_threshold': 3,
'fail_threshold': 2, 'fail_threshold': 2,
'progression_mode': ProgressionMode.weight.storageKey,
'reps_high': kDefaultRepsHigh,
'reps_low': kDefaultRepsLow,
'has_warmup': ex.hasWarmup ? 1 : 0,
'rest_success_secs': kDefaultRestSuccessSecs,
'rest_fail_secs': kDefaultRestFailSecs,
'rest_warmup_secs': kDefaultRestWarmupSecs,
}); });
} }
} }
@ -150,4 +107,5 @@ extension StorageServiceSchema on StorageService {
// coverage:ignore-end // coverage:ignore-end
// ── Settings ─────────────────────────────────────────────────────────────── // ── Settings ───────────────────────────────────────────────────────────────
} }

View File

@ -9,10 +9,6 @@ part of 'storage_service.dart';
/// Progression application and session recording. /// Progression application and session recording.
extension StorageServiceSessions on StorageService { extension StorageServiceSessions on StorageService {
/// Applies progressive overload or regression based on [succeededExercises]. /// Applies progressive overload or regression based on [succeededExercises].
///
/// The step itself comes from [targetAfterSuccess] / [targetAfterFailure],
/// the same functions the workout screen previews with, so what the tile
/// promises is what finishing does.
Future<void> applyProgression({ Future<void> applyProgression({
required Map<String, bool> succeededExercises, required Map<String, bool> succeededExercises,
required DateTime lastWorkoutDate, required DateTime lastWorkoutDate,
@ -24,47 +20,66 @@ extension StorageServiceSessions on StorageService {
final state = await getExerciseState(entry.key); final state = await getExerciseState(entry.key);
if (state == null) continue; if (state == null) continue;
final Map<String, Object> update;
if (hadBreak) { if (hadBreak) {
// A week off is one regression step, in whatever mode is active. final newWeight = (state.weight - kWeightIncrement).clamp(
final t = targetAfterFailure(state); 0.0,
update = { state.maxWeight,
'weight': t.weight, );
'reps': t.reps,
'success_streak': 0,
'fail_streak': 0,
};
} else if (entry.value) {
final newStreak = state.successStreak + 1;
final step = newStreak >= state.successThreshold;
final t = step
? targetAfterSuccess(state)
: ProgressionTarget(state.weight, state.reps);
update = {
'weight': t.weight,
'reps': t.reps,
'success_streak': step ? 0 : newStreak,
'fail_streak': 0,
};
} else {
final newStreak = state.failStreak + 1;
final step = newStreak >= state.failThreshold;
final t = step
? targetAfterFailure(state)
: ProgressionTarget(state.weight, state.reps);
update = {
'weight': t.weight,
'reps': t.reps,
'fail_streak': step ? 0 : newStreak,
'success_streak': 0,
};
}
await _db.update( await _db.update(
'exercise_state', 'exercise_state',
update, {'weight': newWeight, 'success_streak': 0, 'fail_streak': 0},
where: 'name = ?', where: 'name = ?',
whereArgs: [entry.key], whereArgs: [entry.key],
); );
continue;
}
if (entry.value) {
final newStreak = state.successStreak + 1;
final shouldProgress = newStreak >= state.successThreshold;
var newWeight = state.weight;
var newReps = state.reps;
if (shouldProgress) {
if (state.weight >= state.maxWeight) {
newReps = state.reps + 1;
} else {
newWeight = (state.weight + kWeightIncrement).clamp(
0.0,
state.maxWeight,
);
}
}
await _db.update(
'exercise_state',
{
'weight': newWeight,
'reps': newReps,
'success_streak': shouldProgress ? 0 : newStreak,
'fail_streak': 0,
},
where: 'name = ?',
whereArgs: [entry.key],
);
} else {
final newStreak = state.failStreak + 1;
final shouldRegress = newStreak >= state.failThreshold;
final newWeight = shouldRegress
? (state.weight - kWeightIncrement).clamp(0.0, state.maxWeight)
: state.weight;
await _db.update(
'exercise_state',
{
'weight': newWeight,
'fail_streak': shouldRegress ? 0 : newStreak,
'success_streak': 0,
},
where: 'name = ?',
whereArgs: [entry.key],
);
}
} }
} }
@ -109,7 +124,9 @@ extension StorageServiceSessions on StorageService {
/// engine acted on. /// engine acted on.
/// ///
/// Returns the number of sessions restored. /// Returns the number of sessions restored.
Future<int> restoreSyncedSessions(List<Map<String, dynamic>> payloads) async { Future<int> restoreSyncedSessions(
List<Map<String, dynamic>> payloads,
) async {
if (payloads.isEmpty) return 0; if (payloads.isEmpty) return 0;
final existing = await _db.query('workout_history', columns: ['json']); final existing = await _db.query('workout_history', columns: ['json']);
final seen = <String>{ final seen = <String>{

View File

@ -4,72 +4,45 @@ library;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:workout_app/ui/theme.dart'; import 'package:workout_app/ui/theme.dart';
/// Fixed-height strip: the rest countdown, Skip, and the workout's Reset and /// Fixed-height strip showing a rest countdown and a skip button.
/// Finish actions.
/// ///
/// The strip is always laid out, rest or no rest: an appearing banner used /// The strip is always laid out, rest or no rest: an appearing banner used
/// to steal its height from the exercise list and shift every tile down /// to steal its height from the exercise list and shift every tile down
/// (2026-09-20). Between rests it renders the same shape muted, so starting /// (2026-09-20). Between rests it renders the same shape muted, so starting
/// a rest changes colours and the number, never a position. The same holds /// a rest changes colours and the number, never a position.
/// for the buttons: a hidden one keeps its space.
///
/// There is no label. The colour of the number already says whether a rest
/// is running, and "Rest (5 min — keep going!)" only cost height (2026-09-27).
class BreakBanner extends StatelessWidget { class BreakBanner extends StatelessWidget {
/// Creates a [BreakBanner]. /// Creates a [BreakBanner].
const BreakBanner({ const BreakBanner({
required this.active, required this.active,
required this.breakRemaining, required this.breakRemaining,
required this.breakLabel,
required this.onSkip, required this.onSkip,
required this.finished,
required this.canFinish,
required this.onReset,
required this.onFinish,
super.key, super.key,
}); });
/// Total strip height; a constant so the layout below never depends on /// Total strip height; a constant so the layout below never depends on
/// the text metrics of what the strip happens to show. /// the text metrics of what the strip happens to show.
static const double height = 56; static const double height = 64;
/// Whether a rest is running. When false the countdown is muted and Skip /// Whether a rest is running. When false the strip is muted and Skip is
/// is hidden (its space is kept). /// hidden (its space is kept).
final bool active; final bool active;
/// Seconds remaining in the current break. /// Seconds remaining in the current break.
final int breakRemaining; final int breakRemaining;
/// Display label for the break (e.g. 'Rest' or 'Warmup rest').
final String breakLabel;
/// Called when the user taps the Skip button. /// Called when the user taps the Skip button.
final VoidCallback onSkip; final VoidCallback onSkip;
/// Whether the workout is over; hides Reset and Finish (space kept).
final bool finished;
/// Whether every set is recorded; Finish is disabled until it is.
final bool canFinish;
/// Called when the user taps Reset.
final VoidCallback onReset;
/// Called when the user taps Finish.
final VoidCallback onFinish;
String _fmt(int secs) { String _fmt(int secs) {
final m = (secs ~/ 60).toString().padLeft(2, '0'); final m = (secs ~/ 60).toString().padLeft(2, '0');
final s = (secs % 60).toString().padLeft(2, '0'); final s = (secs % 60).toString().padLeft(2, '0');
return '$m:$s'; return '$m:$s';
} }
/// [child] when [visible], otherwise the same box left empty.
static Widget _slot({required bool visible, required Widget child}) =>
Visibility(
visible: visible,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: child,
);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme; final colorScheme = Theme.of(context).colorScheme;
@ -82,47 +55,44 @@ class BreakBanner extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 16), padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row( child: Row(
children: [ children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
breakLabel,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
),
),
Text( Text(
_fmt(breakRemaining), _fmt(breakRemaining),
style: TextStyle( style: TextStyle(
// Warning (caution/pending) while the countdown runs; muted // Warning (caution/pending) while the countdown runs;
// between rests so the idle strip recedes. // muted between rests so the idle strip recedes.
color: active ? status.warning : colorScheme.onSurfaceVariant, color: active
? status.warning
: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.title, fontSize: AppTextSize.title,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontFeatures: const [FontFeature.tabularFigures()], fontFeatures: const [FontFeature.tabularFigures()],
), ),
), ),
const Spacer(), ],
_slot( ),
),
Visibility(
visible: active, visible: active,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: TextButton( child: TextButton(
onPressed: onSkip, onPressed: onSkip,
child: Text('Skip', style: TextStyle(color: colorScheme.primary)), child: Text('Skip', style: TextStyle(color: colorScheme.primary)),
), ),
), ),
_slot(
visible: !finished,
child: TextButton(
onPressed: onReset,
child: Text('Reset', style: TextStyle(color: colorScheme.error)),
),
),
_slot(
visible: !finished,
child: TextButton(
onPressed: canFinish ? onFinish : null,
child: Text(
'Finish',
style: TextStyle(
color: canFinish
? status.success
: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.bold,
),
),
),
),
], ],
), ),
); );

View File

@ -1,195 +0,0 @@
/// Bottom sheet for one exercise's progression mode, rep range, warmup,
/// streak thresholds, rest lengths and injury pause — opened from the mode
/// chip on its workout tile and from the Settings screen.
library;
import 'package:flutter/material.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/ui/theme.dart';
part 'exercise_settings_sheet_rest.dart';
part 'exercise_settings_sheet_rows.dart';
/// Opens the settings sheet for [state]; [onChanged] runs on every edit.
///
/// Edits apply immediately rather than on a Save button: the sheet is a
/// quick mid-workout adjustment, and a dismissed sheet losing its changes
/// would be the surprising outcome.
Future<void> showExerciseSettingsSheet(
BuildContext context, {
required ExerciseState state,
required ValueChanged<ExerciseState> onChanged,
}) => showModalBottomSheet<void>(
context: context,
// Taller than the default 9/16-of-the-screen cap once the rest rows are
// in; the sheet sizes to its content and scrolls on a short screen.
isScrollControlled: true,
builder: (_) => ExerciseSettingsSheet(state: state, onChanged: onChanged),
);
/// Upper bound for the double-progression rep ceiling `n`.
const int _maxRepsHigh = 50;
/// Default injury-pause length.
const int kDefaultPauseDays = 14;
/// The sheet's contents. Public so tests can pump it without a route.
class ExerciseSettingsSheet extends StatefulWidget {
/// Creates an [ExerciseSettingsSheet].
const ExerciseSettingsSheet({
required this.state,
required this.onChanged,
super.key,
});
/// The state being edited, as it was when the sheet opened.
final ExerciseState state;
/// Called with the updated state after every edit.
final ValueChanged<ExerciseState> onChanged;
@override
State<ExerciseSettingsSheet> createState() => _ExerciseSettingsSheetState();
}
class _ExerciseSettingsSheetState extends State<ExerciseSettingsSheet> {
late ExerciseState _s = widget.state;
int _pauseDays = kDefaultPauseDays;
void _update(ExerciseState next) {
setState(() => _s = next);
widget.onChanged(next);
}
String get _modeHint => switch (_s.mode) {
ProgressionMode.weight =>
'+$kWeightIncrement kg per step; +1 rep once at the '
'${_s.maxWeight} kg cap',
ProgressionMode.reps => '+1 rep per step; the weight never changes',
ProgressionMode.doubleProgression =>
'+1 rep per step up to ${_s.repsHigh}, then +$kWeightIncrement kg '
'and back to ${_s.repsLow}',
};
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final caption = TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: AppTextSize.caption,
);
final isDouble = _s.mode == ProgressionMode.doubleProgression;
return SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_s.name,
style: TextStyle(
color: colorScheme.onSurface,
fontWeight: FontWeight.bold,
fontSize: AppTextSize.body,
),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: SegmentedButton<ProgressionMode>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: ProgressionMode.weight,
label: Text('Weight'),
),
ButtonSegment(
value: ProgressionMode.reps,
label: Text('Reps'),
),
ButtonSegment(
value: ProgressionMode.doubleProgression,
label: Text('Reps→kg'),
),
],
selected: {_s.mode},
onSelectionChanged: (m) => _update(_s.copyWith(mode: m.first)),
),
),
const SizedBox(height: 8),
// Fixed two-line box: the hint's length differs per mode, and a
// sheet that changes height under the finger is the jump the
// user asked never to see.
SizedBox(
height: 34,
child: Text(_modeHint, style: caption, maxLines: 2),
),
// Kept laid out in every mode for the same reason.
Visibility(
visible: isDouble,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: _SettingRow(
label: '+kg at',
name: 'Top reps',
value: _s.repsHigh,
min: _s.repsLow + 1,
max: _maxRepsHigh,
suffix: 'reps, restart at',
trailing: _Stepper(
name: 'Restart reps',
value: _s.repsLow,
min: 1,
max: _s.repsHigh - 1,
onChanged: (v) => _update(_s.copyWith(repsLow: v)),
),
onChanged: (v) => _update(_s.copyWith(repsHigh: v)),
),
),
const SizedBox(height: 4),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Warmup set'),
value: _s.hasWarmup,
onChanged: (v) => _update(_s.copyWith(hasWarmup: v)),
),
_SettingRow(
label: '↑ after',
name: 'Wins needed',
value: _s.successThreshold,
min: 1,
max: 5,
suffix: 'wins, ↓ after',
trailing: _Stepper(
name: 'Fails allowed',
value: _s.failThreshold,
min: 1,
max: 5,
onChanged: (v) => _update(_s.copyWith(failThreshold: v)),
),
onChanged: (v) => _update(_s.copyWith(successThreshold: v)),
),
const SizedBox(height: 8),
_RestRows(state: _s, onChanged: _update),
const SizedBox(height: 8),
_PauseRow(
pausedUntil: _s.isPausedAt(DateTime.now())
? _s.pausedUntil
: null,
days: _pauseDays,
onDaysChanged: (v) => setState(() => _pauseDays = v),
onPause: () => _update(
_s.copyWith(pausedUntil: pauseEnd(DateTime.now(), _pauseDays)),
),
onResume: () => _update(_s.copyWith(resume: true)),
),
],
),
),
);
}
}

View File

@ -1,76 +0,0 @@
// Rest-length rows for the exercise settings sheet.
//
// `part` file: split out for the 250-line cap; these widgets stay private.
part of 'exercise_settings_sheet.dart';
/// `Rest ✓ [3:00] ✗ [5:00]`, then `Warmup rest [3:00]`.
///
/// The warmup line stays laid out when the warmup is off, so toggling it
/// never changes the sheet's height under the finger.
class _RestRows extends StatelessWidget {
const _RestRows({required this.state, required this.onChanged});
final ExerciseState state;
final ValueChanged<ExerciseState> onChanged;
_Stepper _stepper(String name, int value, ValueChanged<int> onChanged) =>
_Stepper(
name: name,
value: value,
min: kMinRestSecs,
max: kMaxRestSecs,
step: kRestStepSecs,
format: formatRest,
onChanged: onChanged,
);
@override
Widget build(BuildContext context) {
final style = TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontSize: AppTextSize.label,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text('Rest ✓', style: style),
const SizedBox(width: 8),
_stepper(
'Success rest',
state.restSuccessSecs,
(v) => onChanged(state.copyWith(restSuccessSecs: v)),
),
const SizedBox(width: 12),
Text('✗', style: style),
const SizedBox(width: 8),
_stepper(
'Fail rest',
state.restFailSecs,
(v) => onChanged(state.copyWith(restFailSecs: v)),
),
],
),
const SizedBox(height: 8),
Visibility(
visible: state.hasWarmup,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: Row(
children: [
Text('Warmup rest', style: style),
const SizedBox(width: 8),
_stepper(
'Warmup rest',
state.restWarmupSecs,
(v) => onChanged(state.copyWith(restWarmupSecs: v)),
),
],
),
),
],
);
}
}

View File

@ -1,208 +0,0 @@
// Rows and steppers for the exercise settings sheet.
//
// `part` file: split out for the 250-line cap; these widgets stay private.
part of 'exercise_settings_sheet.dart';
/// `label [stepper] suffix [trailing]` on one line.
class _SettingRow extends StatelessWidget {
const _SettingRow({
required this.label,
required this.name,
required this.value,
required this.min,
required this.max,
required this.suffix,
required this.trailing,
required this.onChanged,
});
final String label;
/// Semantic name of the leading stepper.
final String name;
final int value;
final int min;
final int max;
final String suffix;
final Widget trailing;
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
final style = TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontSize: AppTextSize.label,
);
return Row(
children: [
Text(label, style: style),
const SizedBox(width: 8),
_Stepper(
name: name,
value: value,
min: min,
max: max,
onChanged: onChanged,
),
const SizedBox(width: 8),
Text(suffix, style: style),
const SizedBox(width: 8),
trailing,
],
);
}
}
/// `[-] value [+]`, with the buttons disabled at the bounds.
class _Stepper extends StatelessWidget {
const _Stepper({
required this.name,
required this.value,
required this.min,
required this.max,
required this.onChanged,
this.step = 1,
this.format,
});
/// What is being stepped; names the buttons for screen readers and
/// `android_ui`, which otherwise see two identical unlabelled icons.
final String name;
final int value;
final int min;
final int max;
final ValueChanged<int> onChanged;
/// How far one press moves [value].
final int step;
/// Renders [value]; plain digits when null. A formatted value gets a
/// wider box so `10:00` fits.
final String Function(int)? format;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final fmt = format;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
_btn(
context,
'$name down',
Icons.remove,
value > min ? value - step : null,
),
SizedBox(
width: fmt == null ? 28 : 44,
child: Text(
fmt == null ? '$value' : fmt(value),
textAlign: TextAlign.center,
style: TextStyle(
color: colorScheme.onSurface,
fontSize: AppTextSize.label,
fontWeight: FontWeight.bold,
),
),
),
_btn(context, '$name up', Icons.add, value < max ? value + step : null),
],
);
}
Widget _btn(BuildContext context, String label, IconData icon, int? next) {
final colorScheme = Theme.of(context).colorScheme;
return Semantics(
container: true,
button: true,
label: label,
excludeSemantics: true,
child: InkWell(
onTap: next == null ? null : () => onChanged(next),
borderRadius: BorderRadius.circular(AppRadius.sm),
child: Container(
width: 32,
height: 32,
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(AppRadius.sm),
),
alignment: Alignment.center,
child: Icon(
icon,
size: 16,
color: next != null
? colorScheme.onSurface
: colorScheme.onSurfaceVariant,
),
),
),
);
}
}
/// Pause controls, one fixed-height line in both states:
/// `Pause for [14] days [Pause]`, or `Paused — back on 11 Oct [Resume]`.
class _PauseRow extends StatelessWidget {
const _PauseRow({
required this.pausedUntil,
required this.days,
required this.onDaysChanged,
required this.onPause,
required this.onResume,
});
/// End of the running pause, or null when not paused.
final DateTime? pausedUntil;
final int days;
final ValueChanged<int> onDaysChanged;
final VoidCallback onPause;
final VoidCallback onResume;
static const int _maxDays = 60;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final style = TextStyle(
color: colorScheme.onSurface,
fontSize: AppTextSize.label,
);
final until = pausedUntil;
return SizedBox(
height: 40,
child: Row(
children: until == null
? [
Text('Pause for', style: style),
const SizedBox(width: 8),
_Stepper(
name: 'Pause days',
value: days,
min: 1,
max: _maxDays,
onChanged: onDaysChanged,
),
const SizedBox(width: 8),
Text('days', style: style),
const Spacer(),
TextButton(onPressed: onPause, child: const Text('Pause')),
]
: [
Icon(
Icons.pause_circle_outline,
size: 18,
color: colorScheme.error,
),
const SizedBox(width: 8),
Text(
'Paused — back on ${formatShortDate(until)}',
style: style,
),
const Spacer(),
TextButton(onPressed: onResume, child: const Text('Resume')),
],
),
);
}
}

View File

@ -1,43 +1,33 @@
/// Card widget for a single exercise: header with the progression-mode chip, /// Card widget for a single exercise showing warmup and main-set rep circles.
/// one row of warmup + set circles, and the progress line.
library; library;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:workout_app/models/exercise.dart'; import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/ui/theme.dart'; import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
import 'package:workout_app/widgets/rep_circle.dart'; import 'package:workout_app/widgets/rep_circle.dart';
part 'exercise_tile_rows.dart'; part 'exercise_tile_rows.dart';
/// Card widget displaying warmup and working-set rep circles for one exercise. /// Card widget displaying warmup and working-set rep circles for one exercise.
///
/// Its height is the same in every state — warmup on or off, any mode, any
/// streak, done or not — so the workout column never rescales mid-workout.
/// A disabled warmup leaves its slot empty rather than closing it up.
class ExerciseTile extends StatelessWidget { class ExerciseTile extends StatelessWidget {
/// Creates an [ExerciseTile]. /// Creates an [ExerciseTile].
const ExerciseTile({ const ExerciseTile({
required this.exercise, required this.exercise,
required this.state,
required this.tapped, required this.tapped,
required this.doneReps, required this.doneReps,
required this.warmupTapped, required this.warmupTapped,
required this.successThreshold,
required this.failThreshold,
required this.onTapCircle, required this.onTapCircle,
required this.onLongPressCircle, required this.onLongPressCircle,
required this.onTapWarmup, required this.onTapWarmup,
required this.onSettingsChanged, required this.onThresholdChanged,
super.key, super.key,
}); });
/// The exercise definition to display (this session's targets). /// The exercise definition to display.
final Exercise exercise; final Exercise exercise;
/// Progression state: mode, streaks, thresholds, warmup toggle.
final ExerciseState state;
/// Per-set tap state; true when a set circle has been tapped. /// Per-set tap state; true when a set circle has been tapped.
final List<bool> tapped; final List<bool> tapped;
@ -47,6 +37,12 @@ class ExerciseTile extends StatelessWidget {
/// Whether the warmup circle has been tapped. /// Whether the warmup circle has been tapped.
final bool warmupTapped; final bool warmupTapped;
/// Success streak threshold shown in the inline settings row.
final int successThreshold;
/// Fail streak threshold shown in the inline settings row.
final int failThreshold;
/// Called when a working-set circle is tapped. /// Called when a working-set circle is tapped.
final void Function(int setIdx) onTapCircle; final void Function(int setIdx) onTapCircle;
@ -56,14 +52,8 @@ class ExerciseTile extends StatelessWidget {
/// Called when the warmup circle is tapped. /// Called when the warmup circle is tapped.
final VoidCallback onTapWarmup; final VoidCallback onTapWarmup;
/// Called with the edited state after every change in the settings sheet. /// Called when the user changes thresholds inline (newSuccess, newFail).
final ValueChanged<ExerciseState> onSettingsChanged; final void Function(int success, int fail) onThresholdChanged;
/// Gap between circles in the set row.
static const double circleGap = 8;
/// Height of the set row; the paused placeholder takes exactly this.
static const double setRowHeight = 52;
bool get _allCompleted => tapped.every((t) => t); bool get _allCompleted => tapped.every((t) => t);
@ -74,24 +64,18 @@ class ExerciseTile extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme; final colorScheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!; final status = Theme.of(context).extension<AppStatusColors>()!;
final paused = state.isPausedAt(DateTime.now());
var headerColor = colorScheme.surfaceContainerHigh; var headerColor = colorScheme.surfaceContainerHigh;
// A paused card never turns green/red: its taps no longer count. if (_allCompleted) {
if (_allCompleted && !paused) {
headerColor = _allSucceeded ? status.success : colorScheme.error; headerColor = _allSucceeded ? status.success : colorScheme.error;
} }
// A filled success/danger card needs on-fill text throughout (tokens.md: // A filled success/danger card needs on-fill text throughout (tokens.md:
// one on-fill value for all four fills, never a per-fill judgment call). // one on-fill value for all four fills, never a per-fill judgment call).
final filled = _allCompleted && !paused; final onHeader = _allCompleted
final onHeaderMuted = filled ? colorScheme.onPrimary
: colorScheme.onSurface;
final onHeaderMuted = _allCompleted
? colorScheme.onPrimary ? colorScheme.onPrimary
: colorScheme.onSurfaceVariant; : colorScheme.onSurfaceVariant;
// Paused: the whole header recedes to the muted ink.
final onHeader = filled
? colorScheme.onPrimary
: paused
? onHeaderMuted
: colorScheme.onSurface;
return Card( return Card(
color: headerColor, color: headerColor,
@ -105,8 +89,6 @@ class ExerciseTile extends StatelessWidget {
Expanded( Expanded(
child: Text( child: Text(
exercise.name, exercise.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle( style: TextStyle(
color: onHeader, color: onHeader,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@ -114,13 +96,6 @@ class ExerciseTile extends StatelessWidget {
), ),
), ),
), ),
const SizedBox(width: 6),
_ModeChip(
state: state,
color: onHeaderMuted,
onTap: () => showExerciseSettings(context),
),
const SizedBox(width: 8),
Text( Text(
'${exercise.sets}×${exercise.reps}×${exercise.weight}kg', '${exercise.sets}×${exercise.reps}×${exercise.weight}kg',
style: TextStyle( style: TextStyle(
@ -131,29 +106,20 @@ class ExerciseTile extends StatelessWidget {
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
// A Row, not a Wrap: a set row that spilled onto a second line if (exercise.hasWarmup) ...[
// would change the tile's height, and a Row overflowing fails _WarmupRow(
// loudly in tests instead.
if (paused)
_PausedRow(until: state.pausedUntil!, color: onHeaderMuted)
else
Row(
children: [
Visibility(
visible: state.hasWarmup,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: _WarmupCircle(
semanticLabel: '${exercise.name} warmup',
warmupWeight: exercise.warmupWeight, warmupWeight: exercise.warmupWeight,
tapped: warmupTapped, tapped: warmupTapped,
onTap: onTapWarmup, onTap: onTapWarmup,
), ),
), const SizedBox(height: 10),
for (var s = 0; s < exercise.sets; s++) ...[ ],
const SizedBox(width: circleGap), Wrap(
RepCircle( spacing: 8,
runSpacing: 8,
children: List.generate(
exercise.sets,
(s) => RepCircle(
semanticLabel: '${exercise.name} set ${s + 1}', semanticLabel: '${exercise.name} set ${s + 1}',
targetReps: exercise.reps, targetReps: exercise.reps,
doneReps: doneReps[s], doneReps: doneReps[s],
@ -161,23 +127,19 @@ class ExerciseTile extends StatelessWidget {
onTap: () => onTapCircle(s), onTap: () => onTapCircle(s),
onLongPress: () => onLongPressCircle(s), onLongPress: () => onLongPressCircle(s),
), ),
], ),
],
), ),
// Color inherited from the shared dividerTheme (line-dark). // Color inherited from the shared dividerTheme (line-dark).
const Divider(height: 20), const Divider(height: 20),
_ProgressRow(state: state, onFill: filled), _ThresholdRow(
successThreshold: successThreshold,
failThreshold: failThreshold,
onSuccessChanged: (v) => onThresholdChanged(v, failThreshold),
onFailChanged: (v) => onThresholdChanged(successThreshold, v),
),
], ],
), ),
), ),
); );
} }
/// Opens the settings sheet for this exercise.
Future<void> showExerciseSettings(BuildContext context) =>
showExerciseSettingsSheet(
context,
state: state,
onChanged: onSettingsChanged,
);
} }

View File

@ -1,81 +1,129 @@
// Mode chip, inline warmup circle and progress line for ExerciseTile. // Threshold row, mini stepper and warm-up row for ExerciseTile.
// //
// `part` file: these widgets are library-private and stay that way. // `part` file: these widgets are library-private and stay that way.
// See history_screen_charts.dart for the full reasoning. // See history_screen_charts.dart for the full reasoning.
part of 'exercise_tile.dart'; part of 'exercise_tile.dart';
/// Tappable chip naming the progression mode; opens the settings sheet. class _ThresholdRow extends StatelessWidget {
/// const _ThresholdRow({
/// Fixed width, so switching mode never moves the header's other text. required this.successThreshold,
class _ModeChip extends StatelessWidget { required this.failThreshold,
const _ModeChip({ required this.onSuccessChanged,
required this.state, required this.onFailChanged,
required this.color,
required this.onTap,
}); });
final ExerciseState state; final int successThreshold;
final Color color; final int failThreshold;
final VoidCallback onTap; final ValueChanged<int> onSuccessChanged;
final ValueChanged<int> onFailChanged;
static const double width = 64;
String get _text => switch (state.mode) {
ProgressionMode.weight => 'kg',
ProgressionMode.reps => 'reps',
ProgressionMode.doubleProgression => '${state.repsLow}→${state.repsHigh}',
};
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Semantics( final colorScheme = Theme.of(context).colorScheme;
container: true, final status = Theme.of(context).extension<AppStatusColors>()!;
button: true, final captionStyle = TextStyle(
label: '${state.name} progression settings', color: colorScheme.onSurfaceVariant,
excludeSemantics: true, fontSize: AppTextSize.caption,
child: InkWell( );
onTap: onTap, return Row(
borderRadius: BorderRadius.circular(AppRadius.sm), children: [
child: Container( Icon(Icons.trending_up, size: 13, color: status.success),
width: width, const SizedBox(width: 4),
height: 26, Text('after', style: captionStyle),
decoration: BoxDecoration( const SizedBox(width: 6),
border: Border.all(color: color), _MiniStepper(
borderRadius: BorderRadius.circular(AppRadius.sm), value: successThreshold,
onChanged: onSuccessChanged,
), ),
alignment: Alignment.center, const SizedBox(width: 4),
child: Row( Text('↑', style: captionStyle),
const Spacer(),
Icon(Icons.trending_down, size: 13, color: colorScheme.error),
const SizedBox(width: 4),
Text('after', style: captionStyle),
const SizedBox(width: 6),
_MiniStepper(
value: failThreshold,
onChanged: onFailChanged,
),
const SizedBox(width: 4),
Text('↓', style: captionStyle),
],
);
}
}
class _MiniStepper extends StatelessWidget {
const _MiniStepper({required this.value, required this.onChanged});
final int value;
final ValueChanged<int> onChanged;
static const _min = 1;
static const _max = 5;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon(Icons.tune, size: 13, color: color), _btn(
const SizedBox(width: 3), context,
Flexible( Icons.remove,
child: Text( value > _min ? () => onChanged(value - 1) : null,
_text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color, fontSize: AppTextSize.caption),
), ),
SizedBox(
width: 22,
child: Text(
'$value',
textAlign: TextAlign.center,
style: TextStyle(
color: colorScheme.onSurface,
fontSize: AppTextSize.caption,
),
),
),
_btn(
context,
Icons.add,
value < _max ? () => onChanged(value + 1) : null,
), ),
], ],
);
}
Widget _btn(BuildContext context, IconData icon, VoidCallback? onTap) {
final colorScheme = Theme.of(context).colorScheme;
return GestureDetector(
onTap: onTap,
child: Container(
width: 22,
height: 22,
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(4),
), ),
alignment: Alignment.center,
child: Icon(
icon,
size: 12,
color: onTap != null
? colorScheme.onSurface
: colorScheme.onSurfaceVariant,
), ),
), ),
); );
} }
} }
/// The warmup as the first circle of the set row: outlined, the size of a class _WarmupRow extends StatelessWidget {
/// set circle, showing `W×6` over the warmup weight. const _WarmupRow({
class _WarmupCircle extends StatelessWidget {
const _WarmupCircle({
required this.semanticLabel,
required this.warmupWeight, required this.warmupWeight,
required this.tapped, required this.tapped,
required this.onTap, required this.onTap,
}); });
final String semanticLabel;
final double warmupWeight; final double warmupWeight;
final bool tapped; final bool tapped;
final VoidCallback onTap; final VoidCallback onTap;
@ -84,24 +132,25 @@ class _WarmupCircle extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme; final colorScheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!; final status = Theme.of(context).extension<AppStatusColors>()!;
// Tapped = a completed milestone, same semantic as every other "done" final mutedStyle = TextStyle(
// indicator in this app. On-fill ink on the filled circle; muted on the color: colorScheme.onSurfaceVariant,
// outline-only one, which is what sets it apart from a working set. fontSize: AppTextSize.caption,
final fg = tapped ? colorScheme.onPrimary : colorScheme.onSurfaceVariant; );
final small = TextStyle(color: fg, fontSize: AppTextSize.caption); return Row(
return GestureDetector( children: [
Text('Warmup 1×5×', style: mutedStyle),
Text('${warmupWeight}kg', style: mutedStyle),
const SizedBox(width: 10),
GestureDetector(
onTap: tapped ? null : onTap, onTap: tapped ? null : onTap,
child: Semantics(
container: true,
button: true,
label: semanticLabel,
excludeSemantics: true,
child: AnimatedContainer( child: AnimatedContainer(
duration: const Duration(milliseconds: 200), duration: const Duration(milliseconds: 200),
width: 52, width: 36,
height: 52, height: 36,
decoration: BoxDecoration( decoration: BoxDecoration(
shape: BoxShape.circle, shape: BoxShape.circle,
// Tapped = a completed milestone, same semantic as every other
// "done" indicator in this app (rep circles, calendar days).
color: tapped ? status.success : Colors.transparent, color: tapped ? status.success : Colors.transparent,
border: Border.all( border: Border.all(
color: tapped ? status.success : colorScheme.outline, color: tapped ? status.success : colorScheme.outline,
@ -109,111 +158,25 @@ class _WarmupCircle extends StatelessWidget {
), ),
), ),
alignment: Alignment.center, alignment: Alignment.center,
child: Column( child: Icon(
mainAxisSize: MainAxisSize.min, tapped ? Icons.check : Icons.fitness_center,
children: [ // on-fill on the filled circle; muted on the empty outline one.
Text( color: tapped
'W×$kWarmupReps',
style: small.copyWith(fontWeight: FontWeight.bold, height: 1.1),
),
Text('$warmupWeight', style: small.copyWith(height: 1.1)),
],
),
),
),
);
}
}
/// `↑ 2/3 → 25 kg` … `↓ 0/2 → 20 kg`: both streaks against their
/// thresholds, and what the next step up or down will set.
///
/// The targets come from the same rule `applyProgression` runs, so the
/// line cannot promise a step the finish would not take.
class _ProgressRow extends StatelessWidget {
const _ProgressRow({required this.state, required this.onFill});
final ExerciseState state;
/// Whether the card is a filled success/danger colour.
final bool onFill;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final status = Theme.of(context).extension<AppStatusColors>()!;
final textColor = onFill
? colorScheme.onPrimary ? colorScheme.onPrimary
: colorScheme.onSurfaceVariant; : colorScheme.onSurfaceVariant,
final up = describeTargetChange(state, targetAfterSuccess(state)); size: 16,
final down = describeTargetChange(state, targetAfterFailure(state));
return Row(
children: [
Expanded(
child: _half(
Icons.trending_up,
onFill ? textColor : status.success,
'${state.successStreak}/${state.successThreshold} → $up',
textColor,
), ),
), ),
const SizedBox(width: 8),
Expanded(
child: _half(
Icons.trending_down,
onFill ? textColor : colorScheme.error,
'${state.failStreak}/${state.failThreshold} → $down',
textColor,
), ),
), const SizedBox(width: 6),
], Text(
); tapped ? 'done' : 'optional',
} style: TextStyle(
color: tapped ? status.success : colorScheme.onSurfaceVariant,
Widget _half(IconData icon, Color iconColor, String text, Color color) { fontSize: AppTextSize.caption,
return Row(
children: [
Icon(icon, size: 14, color: iconColor),
const SizedBox(width: 4),
Expanded(
child: Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color, fontSize: AppTextSize.caption),
), ),
), ),
], ],
); );
} }
} }
/// Stands in for the set row while the exercise is paused: same height, so
/// pausing moves nothing on the screen.
class _PausedRow extends StatelessWidget {
const _PausedRow({required this.until, required this.color});
final DateTime until;
final Color color;
@override
Widget build(BuildContext context) {
return SizedBox(
height: ExerciseTile.setRowHeight,
child: Row(
children: [
Icon(Icons.pause_circle_outline, size: 20, color: color),
const SizedBox(width: 8),
Expanded(
child: Text(
'Paused — back on ${formatShortDate(until)} · counts as failed',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color, fontSize: AppTextSize.label),
),
),
],
),
);
}
}

View File

@ -5,7 +5,6 @@ const _full = BreakSnapshot(
workoutType: 'B', workoutType: 'B',
breakEndMs: 1789432100123, breakEndMs: 1789432100123,
breakDurationSecs: 180, breakDurationSecs: 180,
breakFailSecs: 300,
breakLabel: 'Rest (3 min — well done!)', breakLabel: 'Rest (3 min — well done!)',
breakForExIdx: 0, breakForExIdx: 0,
breakForSetIdx: 1, breakForSetIdx: 1,
@ -30,7 +29,6 @@ void main() {
expect(decoded.breakLabel, contains('well done')); expect(decoded.breakLabel, contains('well done'));
expect(decoded.nextWeight, 42.5); expect(decoded.nextWeight, 42.5);
expect(decoded.setsRemaining, 7); expect(decoded.setsRemaining, 7);
expect(decoded.breakFailSecs, 300);
expect(decoded.finished, isTrue); expect(decoded.finished, isTrue);
}); });
@ -52,16 +50,13 @@ void main() {
BreakSnapshot.tryFromMap(_full.toMap()..['workoutType'] = 1), BreakSnapshot.tryFromMap(_full.toMap()..['workoutType'] = 1),
isNull, isNull,
); );
expect(BreakSnapshot.tryFromMap(_full.toMap()..['nextExName'] = 1), isNull); expect(
BreakSnapshot.tryFromMap(_full.toMap()..['nextExName'] = 1),
isNull,
);
expect(BreakSnapshot.tryFromMap(_full.toMap()..['breakLabel'] = 1), isNull); expect(BreakSnapshot.tryFromMap(_full.toMap()..['breakLabel'] = 1), isNull);
expect( expect(BreakSnapshot.tryFromMap(_full.toMap()..['nextWeight'] = 'x'), isNull);
BreakSnapshot.tryFromMap(_full.toMap()..['nextWeight'] = 'x'), expect(BreakSnapshot.tryFromMap(_full.toMap()..['breakEndMs'] = 'x'), isNull);
isNull,
);
expect(
BreakSnapshot.tryFromMap(_full.toMap()..['breakEndMs'] = 'x'),
isNull,
);
}); });
test('a missing finished flag reads as not finished', () { test('a missing finished flag reads as not finished', () {
@ -94,7 +89,6 @@ void main() {
expect(same.breakEndMs, _full.breakEndMs); expect(same.breakEndMs, _full.breakEndMs);
expect(same.breakLabel, _full.breakLabel); expect(same.breakLabel, _full.breakLabel);
expect(same.breakDurationSecs, _full.breakDurationSecs); expect(same.breakDurationSecs, _full.breakDurationSecs);
expect(same.breakFailSecs, _full.breakFailSecs);
expect(same.setsRemaining, _full.setsRemaining); expect(same.setsRemaining, _full.setsRemaining);
expect(same.finished, _full.finished); expect(same.finished, _full.finished);
}); });
@ -104,7 +98,6 @@ void main() {
workoutType: 'A', workoutType: 'A',
breakEndMs: 0, breakEndMs: 0,
breakDurationSecs: 0, breakDurationSecs: 0,
breakFailSecs: 300,
breakLabel: '', breakLabel: '',
breakForExIdx: -1, breakForExIdx: -1,
breakForSetIdx: -1, breakForSetIdx: -1,

View File

@ -1,70 +0,0 @@
// ExerciseState's injury-pause and rest-length fields and their formatting
// helpers. Split from progression_test.dart for the 250-line cap.
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
// ExerciseState.initial starts in weight mode, the same as the progression
// tests' default.
final _base = ExerciseState.initial(
const Exercise(name: 'X', sets: 3, reps: 8, weight: 20),
);
void main() {
group('injury pause', () {
final now = DateTime(2026, 9, 27, 17, 30);
test('pauseEnd is local midnight n days on', () {
expect(pauseEnd(now, 14), DateTime(2026, 10, 11));
});
test('isPausedAt is true until that midnight, false from it', () {
final s = _base.copyWith(pausedUntil: pauseEnd(now, 14));
expect(s.isPausedAt(now), isTrue);
expect(s.isPausedAt(DateTime(2026, 10, 10, 23, 59)), isTrue);
expect(s.isPausedAt(DateTime(2026, 10, 11)), isFalse);
expect(_base.isPausedAt(now), isFalse);
});
test('copyWith keeps a pause, and resume clears it', () {
final paused = _base.copyWith(pausedUntil: DateTime(2026, 10, 11));
expect(paused.copyWith(reps: 3).pausedUntil, DateTime(2026, 10, 11));
expect(paused.copyWith(resume: true).pausedUntil, isNull);
});
test('dates round-trip through storage format', () {
final d = DateTime(2026, 1, 5);
expect(formatPauseDate(d), '2026-01-05');
expect(parsePauseDate(formatPauseDate(d)), d);
});
test('null, garbage and non-strings read as not paused', () {
expect(parsePauseDate(null), isNull);
expect(parsePauseDate('soon'), isNull);
expect(parsePauseDate(42), isNull);
});
test('rests default to the old fixed lengths and survive copyWith', () {
final s = _base;
expect(
(s.restSuccessSecs, s.restFailSecs, s.restWarmupSecs),
(180, 300, 180),
);
final edited = s.copyWith(restFailSecs: 240);
expect(edited.restFailSecs, 240);
expect(edited.copyWith(reps: 3).restFailSecs, 240);
});
test('formatRest', () {
expect(formatRest(30), '0:30');
expect(formatRest(195), '3:15');
expect(formatRest(600), '10:00');
});
test('formatShortDate', () {
expect(formatShortDate(DateTime(2026, 10, 11)), '11 Oct');
expect(formatShortDate(DateTime(2026, 1, 1)), '1 Jan');
expect(formatShortDate(DateTime(2026, 12, 31)), '31 Dec');
});
});
}

View File

@ -1,223 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/progression.dart';
ExerciseState _s({
required ProgressionMode mode,
double weight = 20,
int reps = 8,
double maxWeight = 27.5,
int repsHigh = 12,
int repsLow = 6,
}) => ExerciseState(
name: 'X',
weight: weight,
reps: reps,
successStreak: 0,
failStreak: 0,
maxWeight: maxWeight,
successThreshold: 3,
failThreshold: 2,
mode: mode,
repsHigh: repsHigh,
repsLow: repsLow,
hasWarmup: true,
pausedUntil: null,
restSuccessSecs: kDefaultRestSuccessSecs,
restFailSecs: kDefaultRestFailSecs,
restWarmupSecs: kDefaultRestWarmupSecs,
);
void _expectTarget(ProgressionTarget t, double weight, int reps) {
expect((t.weight, t.reps), (weight, reps), reason: '$t');
}
void main() {
group('ProgressionMode.parse', () {
test('reads every storage key back to its mode', () {
for (final m in ProgressionMode.values) {
expect(ProgressionMode.parse(m.storageKey), m);
}
});
test('null (a row from before modes existed) is weight', () {
expect(ProgressionMode.parse(null), ProgressionMode.weight);
});
test('an unknown value falls back to weight', () {
expect(ProgressionMode.parse('sideways'), ProgressionMode.weight);
});
});
group('weight mode (unchanged behaviour)', () {
test('success below the cap adds 2.5 kg', () {
_expectTarget(
targetAfterSuccess(_s(mode: ProgressionMode.weight)),
22.5,
8,
);
});
test('success above the cap clamps to it', () {
final s = _s(mode: ProgressionMode.weight, weight: 26);
_expectTarget(targetAfterSuccess(s), 27.5, 8);
});
test('success at the cap adds a rep instead', () {
final s = _s(mode: ProgressionMode.weight, weight: 27.5);
_expectTarget(targetAfterSuccess(s), 27.5, 9);
});
test('failure drops 2.5 kg, never below zero', () {
_expectTarget(
targetAfterFailure(_s(mode: ProgressionMode.weight)),
17.5,
8,
);
final light = _s(mode: ProgressionMode.weight, weight: 1);
_expectTarget(targetAfterFailure(light), 0, 8);
});
});
group('reps mode', () {
test('success adds a rep and never touches the weight', () {
_expectTarget(targetAfterSuccess(_s(mode: ProgressionMode.reps)), 20, 9);
});
test('failure removes a rep, floored at 1', () {
_expectTarget(targetAfterFailure(_s(mode: ProgressionMode.reps)), 20, 7);
final one = _s(mode: ProgressionMode.reps, reps: 1);
_expectTarget(targetAfterFailure(one), 20, 1);
});
});
group('double progression', () {
const mode = ProgressionMode.doubleProgression;
test('below n: +1 rep', () {
_expectTarget(targetAfterSuccess(_s(mode: mode, reps: 11)), 20, 12);
});
test('at n: +2.5 kg and back to m', () {
_expectTarget(targetAfterSuccess(_s(mode: mode, reps: 12)), 22.5, 6);
});
test('above n (switched in at 30 reps) still promotes', () {
_expectTarget(targetAfterSuccess(_s(mode: mode, reps: 30)), 22.5, 6);
});
test('at n on the weight cap keeps adding reps', () {
final s = _s(mode: mode, reps: 12, weight: 27.5);
_expectTarget(targetAfterSuccess(s), 27.5, 13);
});
test('failure above m removes a rep', () {
_expectTarget(targetAfterFailure(_s(mode: mode, reps: 9)), 20, 8);
});
test('failure at m is the exact inverse of a step up', () {
final s = _s(mode: mode, reps: 6);
final down = targetAfterFailure(s);
_expectTarget(down, 17.5, 12);
final back = targetAfterSuccess(
s.copyWith(weight: down.weight, reps: down.reps),
);
_expectTarget(back, 20, 6);
});
test('failure at m with no weight left stays put', () {
_expectTarget(
targetAfterFailure(_s(mode: mode, reps: 6, weight: 0)),
0,
6,
);
});
});
group('describeTargetChange', () {
final from = _s(mode: ProgressionMode.weight, weight: 20, reps: 8);
test('weight and reps', () {
expect(
describeTargetChange(from, const ProgressionTarget(22.5, 6)),
'22.5 kg × 6',
);
});
test('weight only drops a trailing .0', () {
expect(
describeTargetChange(from, const ProgressionTarget(25, 8)),
'25 kg',
);
});
test('reps only', () {
expect(
describeTargetChange(from, const ProgressionTarget(20, 9)),
'9 reps',
);
});
test('no change', () {
expect(
describeTargetChange(from, const ProgressionTarget(20, 8)),
'same',
);
});
test('toString names both fields', () {
expect(const ProgressionTarget(20, 8).toString(), contains('20'));
});
});
group('ExerciseState', () {
test('initial copies the plan and the plan warmup', () {
const ex = Exercise(
name: 'Situp',
sets: 3,
reps: 30,
weight: 10,
maxWeight: 10,
hasWarmup: false,
);
final s = ExerciseState.initial(ex);
expect(s.weight, 10);
expect(s.reps, 30);
expect(s.maxWeight, 10);
expect(s.hasWarmup, isFalse);
expect(s.mode, ProgressionMode.weight);
expect((s.repsHigh, s.repsLow), (kDefaultRepsHigh, kDefaultRepsLow));
expect((s.successThreshold, s.failThreshold), (3, 2));
});
test('copyWith replaces each field and keeps the rest', () {
final s = _s(mode: ProgressionMode.weight);
final c = s.copyWith(
weight: 1,
reps: 2,
successStreak: 3,
failStreak: 4,
successThreshold: 5,
failThreshold: 1,
mode: ProgressionMode.reps,
repsHigh: 20,
repsLow: 10,
hasWarmup: false,
);
expect(c.name, 'X');
expect(c.maxWeight, 27.5);
expect((c.weight, c.reps, c.successStreak, c.failStreak), (1, 2, 3, 4));
expect((c.successThreshold, c.failThreshold), (5, 1));
expect(
(c.mode, c.repsHigh, c.repsLow, c.hasWarmup),
(ProgressionMode.reps, 20, 10, false),
);
final same = s.copyWith();
expect(
(same.weight, same.reps, same.mode, same.hasWarmup),
(20, 8, ProgressionMode.weight, true),
);
});
});
}

View File

@ -112,9 +112,3 @@ Future<void> longPressReal(WidgetTester tester, Finder f) async {
/// no longer says anything; `active` is the discriminator. /// no longer says anything; `active` is the discriminator.
bool restRunning(WidgetTester tester) => bool restRunning(WidgetTester tester) =>
tester.widget<BreakBanner>(find.byType(BreakBanner)).active; tester.widget<BreakBanner>(find.byType(BreakBanner)).active;
/// Seconds left on the rest strip. The strip carries no label any more, so
/// "which rest is this" is read from the length: a success or warmup rest
/// starts at 180, a failed set's at 300.
int restSecs(WidgetTester tester) =>
tester.widget<BreakBanner>(find.byType(BreakBanner)).breakRemaining;

View File

@ -1,153 +0,0 @@
// The PER EXERCISE section: each row opens the workout tile's settings sheet,
// edits persist as they happen, and closing the sheet pushes to Firebase.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/screens/settings_screen.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
import '../fake_secure_storage.dart';
const _situp = 'Situp exercise settings';
void main() {
late int pushes;
late ProgressionSyncResult pushResult;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
pushes = 0;
pushResult = const ProgressionSyncResult(changed: true, reason: 'pushed');
});
Future<void> pumpSettings(WidgetTester tester) async {
await tester.runAsync(() async {
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: SettingsScreen(
firebaseFactory: () async => null,
accountLoader: () async => null,
sessionProbe: () async => false,
storageChecker: () async => false,
progressionPuller: () async =>
const ProgressionSyncResult(changed: false, reason: 'stub'),
progressionPusher: () async {
pushes++;
return pushResult;
},
),
),
);
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
await tester.scrollUntilVisible(find.bySemanticsLabel(_situp), 200);
await tester.pumpAndSettle();
}
Future<void> openSitup(WidgetTester tester) async {
await tester.tap(find.bySemanticsLabel(_situp));
await tester.pumpAndSettle();
expect(find.byType(ExerciseSettingsSheet), findsOneWidget);
}
/// Dismisses the sheet and lets the push (a real future) complete.
Future<void> closeSheet(WidgetTester tester) async {
Navigator.of(tester.element(find.byType(ExerciseSettingsSheet))).pop();
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 300)),
);
await tester.pumpAndSettle();
}
Future<ExerciseState> storedSitup(WidgetTester tester) async => (await tester
.runAsync(() => StorageService.instance.getExerciseState('Situp')))!;
testWidgets('each row summarises its exercise', (tester) async {
await pumpSettings(tester);
// Situp is the one plan exercise without a warmup.
expect(
find.text('kg · ↑3 ↓2 · rest 3:00 / 5:00 · no warmup'),
findsOneWidget,
);
});
testWidgets('a double-progression row names its rep range', (tester) async {
await tester.runAsync(() async {
final s = (await StorageService.instance.getExerciseState('Situp'))!;
await StorageService.instance.setExerciseSettings(
s.copyWith(
mode: ProgressionMode.doubleProgression,
repsHigh: 40,
repsLow: 25,
),
);
});
await pumpSettings(tester);
expect(find.textContaining('25→40 reps · ↑3 ↓2'), findsOneWidget);
});
testWidgets('edits persist, show on the row, and push once on close', (
tester,
) async {
await pumpSettings(tester);
await openSitup(tester);
await tester.runAsync(() async {
await tester.tap(find.bySemanticsLabel('Success rest up'));
await Future<void>.delayed(const Duration(milliseconds: 200));
});
await tester.pump();
await tester.tap(find.text('Reps'));
await tester.pump();
await tester.tap(find.text('Pause'));
await tester.pump();
await closeSheet(tester);
expect(pushes, 1);
final s = await storedSitup(tester);
expect(s.restSuccessSecs, 195);
expect(s.mode, ProgressionMode.reps);
expect(s.pausedUntil, isNotNull);
expect(find.textContaining('reps · ↑3 ↓2 · rest 3:15 / 5:00'), findsOne);
expect(find.textContaining('Paused — back on'), findsOneWidget);
expect(find.byType(SnackBar), findsNothing);
});
testWidgets('closing without an edit pushes nothing', (tester) async {
await pumpSettings(tester);
await openSitup(tester);
await closeSheet(tester);
expect(pushes, 0);
});
testWidgets('a push that did not happen says so', (tester) async {
pushResult = const ProgressionSyncResult(
changed: false,
reason: 'no Firebase account on this device',
);
await pumpSettings(tester);
await openSitup(tester);
await tester.tap(find.bySemanticsLabel('Fail rest down'));
await tester.pump();
await closeSheet(tester);
expect(pushes, 1);
expect(
find.text(
'Saved on this phone, not synced: no Firebase account on this device',
),
findsOneWidget,
);
});
}

View File

@ -98,6 +98,61 @@ void main() {
}, },
); );
testWidgets('changing a success threshold persists it', (tester) async {
await _pump(tester, _wrap());
// Scroll to the section header first: the threshold rows below it are not
// built at all until then, so a `.first` finder for the label would throw
// "Bad state: No element" before it could match anything.
await tester.scrollUntilVisible(find.text('PROGRESSION THRESHOLDS'), 200);
await tester.pumpAndSettle();
final label = find.text('↑ Increase after N successes').first;
await tester.scrollUntilVisible(
label,
300,
scrollable: find.byType(Scrollable),
);
// The circles (1-5) live in the same Row as the label; tap the "5" circle.
final row = find.ancestor(of: label, matching: find.byType(Row)).first;
final five = find.descendant(of: row, matching: find.text('5')).first;
// The row can sit below the 800x600 test fold — bring the circle fully in.
await tester.ensureVisible(five);
await tester.pumpAndSettle();
// _onThresholdChanged awaits a DB write, so drive it on the real loop.
await tester.runAsync(() async {
await tester.tap(five);
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
final states = await tester.runAsync(
() => StorageService.instance.getAllExerciseStates(),
);
expect(states!.any((s) => s.successThreshold == 5), isTrue);
// Also exercise the fail-threshold path (onFailChanged closure).
final failLabel = find.text('↓ Decrease after N failures').first;
await tester.ensureVisible(failLabel);
await tester.pumpAndSettle();
final failRow = find
.ancestor(of: failLabel, matching: find.byType(Row))
.first;
final failFour = find
.descendant(of: failRow, matching: find.text('4'))
.first;
await tester.ensureVisible(failFour);
await tester.pumpAndSettle();
await tester.runAsync(() async {
await tester.tap(failFour);
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
final states2 = await tester.runAsync(
() => StorageService.instance.getAllExerciseStates(),
);
expect(states2!.any((s) => s.failThreshold == 4), isTrue);
});
testWidgets('reps change is debounced then written to storage', ( testWidgets('reps change is debounced then written to storage', (
tester, tester,
) async { ) async {

View File

@ -79,6 +79,17 @@ void main() {
), ),
); );
testWidgets('threshold circles show values 1-5', (tester) async {
await _pump(tester, _wrap());
// The threshold cards sit below WEIGHTS and TARGET REPS, past the test
// viewport's fold, so they are not built until scrolled to.
await tester.scrollUntilVisible(find.text('PROGRESSION THRESHOLDS'), 200);
await tester.pumpAndSettle();
for (int i = 1; i <= 5; i++) {
expect(find.text('$i'), findsWidgets);
}
});
testWidgets('Reset dialog shows on tap and cancels', (tester) async { testWidgets('Reset dialog shows on tap and cancels', (tester) async {
await _pump(tester, _wrap()); await _pump(tester, _wrap());
await tester.tap(find.text('Reset defaults')); await tester.tap(find.text('Reset defaults'));

View File

@ -84,16 +84,18 @@ void main() {
expect(find.text('Settings'), findsOneWidget); expect(find.text('Settings'), findsOneWidget);
}); });
testWidgets('shows WEIGHTS, TARGET REPS and PER EXERCISE', (tester) async { testWidgets('shows WEIGHTS, TARGET REPS and PROGRESSION THRESHOLDS', (
tester,
) async {
await _pump(tester, _wrap()); await _pump(tester, _wrap());
expect(find.text('WEIGHTS'), findsOneWidget); expect(find.text('WEIGHTS'), findsOneWidget);
// TARGET REPS and the per-exercise list below it are off-screen at the test // TARGET REPS and the thresholds below it are off-screen at the test
// viewport height, so scroll them into view rather than asserting on // viewport height, so scroll them into view rather than asserting on
// whatever happens to be built. // whatever happens to be built.
await tester.scrollUntilVisible(find.text('TARGET REPS'), 200); await tester.scrollUntilVisible(find.text('TARGET REPS'), 200);
expect(find.text('TARGET REPS'), findsOneWidget); expect(find.text('TARGET REPS'), findsOneWidget);
await tester.scrollUntilVisible(find.text('PER EXERCISE'), 200); await tester.scrollUntilVisible(find.text('PROGRESSION THRESHOLDS'), 200);
expect(find.text('PER EXERCISE'), findsOneWidget); expect(find.text('PROGRESSION THRESHOLDS'), findsOneWidget);
}); });
testWidgets('increment reps button increases the target reps', ( testWidgets('increment reps button increases the target reps', (
@ -106,7 +108,10 @@ void main() {
expect(find.text('30 reps'), findsOneWidget); expect(find.text('30 reps'), findsOneWidget);
final plus = find.descendant( final plus = find.descendant(
of: find of: find
.ancestor(of: find.text('30 reps'), matching: find.byType(Row)) .ancestor(
of: find.text('30 reps'),
matching: find.byType(Row),
)
.first, .first,
matching: find.byIcon(Icons.add), matching: find.byIcon(Icons.add),
); );
@ -158,6 +163,9 @@ void main() {
await tester.tap(find.byIcon(Icons.remove).first); await tester.tap(find.byIcon(Icons.remove).first);
await tester.pump(); await tester.pump();
expect(find.textContaining('${before - kWeightIncrement}kg'), findsWidgets); expect(
find.textContaining('${before - kWeightIncrement}kg'),
findsWidgets,
);
}); });
} }

View File

@ -77,7 +77,7 @@ void main() {
await pumpWorkout(tester, wrapWorkout(savedState: savedWithBreak(90))); await pumpWorkout(tester, wrapWorkout(savedState: savedWithBreak(90)));
expect(restRunning(tester), isTrue); expect(restRunning(tester), isTrue);
expect(restSecs(tester), inInclusiveRange(80, 90)); expect(find.textContaining('well done'), findsOneWidget);
expect( expect(
audio.resumedSources.where((s) => s.contains('break_end')), audio.resumedSources.where((s) => s.contains('break_end')),
isEmpty, isEmpty,

View File

@ -51,8 +51,8 @@ void main() {
await pumpWorkout(tester, wrapWorkout()); await pumpWorkout(tester, wrapWorkout());
await tapReal(tester, find.byType(RepCircle).first); await tapReal(tester, find.byType(RepCircle).first);
expect(restRunning(tester), isTrue); expect(restRunning(tester), isTrue);
// Success break (5 done >= 5 target): the 3-minute rest. // Success break (5 done >= 5 target).
expect(restSecs(tester), inInclusiveRange(175, 180)); expect(find.textContaining('well done'), findsOneWidget);
await tapReal(tester, find.text('Skip')); await tapReal(tester, find.text('Skip'));
expect(restRunning(tester), isFalse); expect(restRunning(tester), isFalse);
@ -60,9 +60,8 @@ void main() {
testWidgets('tapping warmup starts a warmup break', (tester) async { testWidgets('tapping warmup starts a warmup break', (tester) async {
await pumpWorkout(tester, wrapWorkout()); await pumpWorkout(tester, wrapWorkout());
await tapReal(tester, find.bySemanticsLabel(RegExp(r' warmup$')).first); await tapReal(tester, find.byIcon(Icons.fitness_center).first);
expect(restRunning(tester), isTrue); expect(find.textContaining('Warmup rest'), findsOneWidget);
expect(restSecs(tester), inInclusiveRange(175, 180));
}); });
testWidgets('re-tapping a set decrements reps and recomputes the break', ( testWidgets('re-tapping a set decrements reps and recomputes the break', (
@ -71,10 +70,10 @@ void main() {
await pumpWorkout(tester, wrapWorkout()); await pumpWorkout(tester, wrapWorkout());
final circle = find.byType(RepCircle).first; final circle = find.byType(RepCircle).first;
await tapReal(tester, circle); // done=5 -> success break await tapReal(tester, circle); // done=5 -> success break
expect(restSecs(tester), inInclusiveRange(175, 180)); expect(find.textContaining('well done'), findsOneWidget);
await tapReal(tester, circle); // done 5 -> 4, below target -> fail break await tapReal(tester, circle); // done 5 -> 4, below target -> fail break
expect(restSecs(tester), inInclusiveRange(295, 300)); expect(find.textContaining('keep going'), findsOneWidget);
}); });
testWidgets('long-pressing a set resets it and cancels its break', ( testWidgets('long-pressing a set resets it and cancels its break', (
@ -153,20 +152,18 @@ void main() {
testWidgets('changing a threshold in the workout persists it', ( testWidgets('changing a threshold in the workout persists it', (
tester, tester,
) async { ) async {
// A real exercise has a progression-state row, so the settings write // A real exercise has a progression-state row, so _onThresholdChanged's
// actually lands. // state-update branch runs (and the write actually lands).
final name = workoutA.first.name; final name = workoutA.first.name;
await pumpWorkout(tester, wrapWorkout(exercises: [workoutA.first])); await pumpWorkout(tester, wrapWorkout(exercises: [workoutA.first]));
await tapReal(tester, find.bySemanticsLabel('$name progression settings')); // The success stepper's "+" is the first Icons.add in the single tile.
await tester.pumpAndSettle(); await tapReal(tester, find.byIcon(Icons.add).first);
await tapReal(tester, find.bySemanticsLabel('Wins needed up'));
final state = await tester.runAsync( final state = await tester.runAsync(
() => StorageService.instance.getExerciseState(name), () => StorageService.instance.getExerciseState(name),
); );
expect(state!.successThreshold, 4); // default 3 -> +1 expect(state!.successThreshold, 4); // default 3 -> +1
expect(find.textContaining('0/4'), findsOneWidget);
}); });
testWidgets('restores an in-progress break and finishes it', (tester) async { testWidgets('restores an in-progress break and finishes it', (tester) async {

View File

@ -16,7 +16,6 @@ import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/sandbox/sandbox.dart'; import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/storage_service.dart'; import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/widgets/break_banner.dart'; import 'package:workout_app/widgets/break_banner.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
import 'package:workout_app/widgets/exercise_tile.dart'; import 'package:workout_app/widgets/exercise_tile.dart';
import 'package:workout_app/widgets/rep_circle.dart'; import 'package:workout_app/widgets/rep_circle.dart';
@ -116,8 +115,7 @@ void main() {
expect(find.byType(Scrollable), findsNothing); expect(find.byType(Scrollable), findsNothing);
expect(tester.getSize(find.byType(BreakBanner)).height, BreakBanner.height); expect(tester.getSize(find.byType(BreakBanner)).height, BreakBanner.height);
expect(restRunning(tester), isFalse); expect(restRunning(tester), isFalse);
// No label on the strip any more: the countdown alone says it. expect(find.text('Rest'), findsOneWidget);
expect(find.textContaining('Rest'), findsNothing);
expect(find.text('00:00'), findsOneWidget); expect(find.text('00:00'), findsOneWidget);
await _shot(tester, 'idle'); await _shot(tester, 'idle');
@ -130,59 +128,6 @@ void main() {
await tapReal(tester, find.text('Skip')); await tapReal(tester, find.text('Skip'));
expect(restRunning(tester), isFalse); expect(restRunning(tester), isFalse);
expect(tileRects(), idle); expect(tileRects(), idle);
// The settings sheet: opens over the column, fits without scrolling,
// and editing it moves nothing underneath.
await tapReal(
tester,
find.bySemanticsLabel('Dumbbell Romanian Deadlift progression settings'),
);
await tester.pumpAndSettle();
expect(find.byType(ExerciseSettingsSheet), findsOneWidget);
final sheetIdle = tester.getRect(find.byType(ExerciseSettingsSheet));
await tapReal(tester, find.text('Reps→kg'));
expect(tester.getRect(find.byType(ExerciseSettingsSheet)), sheetIdle);
await tapReal(tester, find.text('Warmup set'));
expect(tester.getRect(find.byType(ExerciseSettingsSheet)), sheetIdle);
// The sheet scrolls only as a fallback for a short screen; on the phone
// everything, rest rows included, fits with nothing to scroll.
final sheetScroll = tester.state<ScrollableState>(
find.descendant(
of: find.byType(ExerciseSettingsSheet),
matching: find.byType(Scrollable),
),
);
expect(sheetScroll.position.maxScrollExtent, 0);
await _shot(tester, 'sheet');
Navigator.of(tester.element(find.byType(ExerciseSettingsSheet))).pop();
await tester.pumpAndSettle();
expect(find.text('6→12'), findsOneWidget);
expect(
find.bySemanticsLabel('Dumbbell Romanian Deadlift warmup').hitTestable(),
findsNothing,
);
expect(tileRects(), idle);
await _shot(tester, 'double_no_warmup');
// Every set recorded: filled cards, Finish enabled, same geometry.
for (var i = 0; i < find.byType(RepCircle).evaluate().length; i++) {
if (restRunning(tester)) await tapReal(tester, find.text('Skip'));
final circle = tester.widget<RepCircle>(find.byType(RepCircle).at(i));
if (!circle.tapped) await tapReal(tester, find.byType(RepCircle).at(i));
}
expect(
tester
.widgetList<RepCircle>(find.byType(RepCircle))
.every((c) => c.tapped),
isTrue,
);
expect(
tester.widget<BreakBanner>(find.byType(BreakBanner)).canFinish,
true,
);
expect(tileRects(), idle);
await _shot(tester, 'all_done');
}); });
testWidgets('landscape would need the scale floor; portrait is locked', ( testWidgets('landscape would need the scale floor; portrait is locked', (
@ -217,6 +162,7 @@ void main() {
}); });
await pumpWorkout(tester, wrapWorkout(type: 'B', exercises: workoutB)); await pumpWorkout(tester, wrapWorkout(type: 'B', exercises: workoutB));
await tapReal(tester, find.byType(RepCircle).first); await tapReal(tester, find.byType(RepCircle).first);
expect(find.text('Rest (7 s — sandbox)'), findsOneWidget);
expect(find.text('00:07'), findsOneWidget); expect(find.text('00:07'), findsOneWidget);
}); });
} }

View File

@ -1,153 +0,0 @@
// An exercise on an injury pause: no sets to tap, Finish does not wait for
// it, the notification skips it, and it is recorded as FAILED.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/break_intent.dart';
import 'package:workout_app/services/break_intent_queue.dart';
import 'package:workout_app/services/break_intent_store.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/widgets/break_banner.dart';
import 'package:workout_app/widgets/rep_circle.dart';
import 'package:workout_app/widgets/workout_summary_dialog.dart';
import '../fake_audio_platform.dart';
import '../fake_break_service.dart';
import '../fake_secure_storage.dart';
import '_workout_screen_test_fixtures.dart';
// Real plan names, so each has a progression-state row to pause.
const _lunge = Exercise(name: 'Dumbbell Lunge', sets: 2, reps: 5, weight: 10);
const _situp = Exercise(name: 'Situp', sets: 2, reps: 5, weight: 5);
Future<void> _pause(String name) async {
final s = (await StorageService.instance.getExerciseState(name))!;
await StorageService.instance.setExerciseSettings(
s.copyWith(pausedUntil: pauseEnd(DateTime.now(), 14), failThreshold: 1),
);
}
void main() {
late FakeForegroundBreakClient client;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
client = FakeForegroundBreakClient();
});
Future<void> pumpPausedSitup(WidgetTester tester) async {
await tester.runAsync(() => _pause('Situp'));
await pumpWorkout(
tester,
wrapWorkout(exercises: const [_lunge, _situp], breakClient: client),
);
}
testWidgets('the paused exercise shows no sets and says so', (tester) async {
await pumpPausedSitup(tester);
expect(find.byType(RepCircle), findsNWidgets(_lunge.sets));
expect(find.textContaining('Paused — back on'), findsOneWidget);
});
testWidgets('Finish unlocks without it, and it is recorded as failed', (
tester,
) async {
await pumpPausedSitup(tester);
for (var s = 0; s < _lunge.sets; s++) {
if (restRunning(tester)) await tapReal(tester, find.text('Skip'));
await tapReal(tester, find.byType(RepCircle).at(s));
}
expect(
tester.widget<BreakBanner>(find.byType(BreakBanner)).canFinish,
isTrue,
);
// The notification never offers the paused exercise's sets.
expect(client.pushed.last.setsRemaining, 0);
await tester.runAsync(() async {
await tester.tap(find.widgetWithText(TextButton, 'Finish'));
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump();
await tester.tap(find.widgetWithText(TextButton, 'Finish').last);
await Future<void>.delayed(const Duration(milliseconds: 800));
await tester.pump();
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(find.byType(WorkoutSummaryDialog), findsOneWidget);
expect(find.text('Situp: ✗'), findsOneWidget);
final situp = await tester.runAsync(
() => StorageService.instance.getExerciseState('Situp'),
);
// failThreshold 1: the one "failure" already stepped the weight down.
expect(situp!.weight, 7.5);
});
testWidgets('pausing mid-rest ends that exercise\'s rest', (tester) async {
await pumpWorkout(
tester,
wrapWorkout(exercises: const [_lunge, _situp], breakClient: client),
);
await tapReal(tester, find.byType(RepCircle).first);
expect(restRunning(tester), isTrue);
await tapReal(
tester,
find.bySemanticsLabel('Dumbbell Lunge progression settings'),
);
await tester.pumpAndSettle();
await tapReal(tester, find.text('Pause'));
expect(restRunning(tester), isFalse);
expect(find.text('Resume'), findsOneWidget);
// Resuming brings the sets back; the tap made before the pause stays.
await tapReal(tester, find.text('Resume'));
Navigator.of(tester.element(find.text('Pause'))).pop();
await tester.pumpAndSettle();
expect(find.byType(RepCircle), findsNWidgets(4));
expect(tester.widget<RepCircle>(find.byType(RepCircle).first).tapped, true);
});
testWidgets('a notification "done" on a paused exercise is dropped', (
tester,
) async {
await pumpPausedSitup(tester);
// Nothing inside the paused exercise is offered as next.
expect(client.pushed.last.nextExName, 'Dumbbell Lunge');
expect(client.pushed.last.setsRemaining, _lunge.sets);
// A stale press aimed at Situp's first set must not record it.
await tester.runAsync(
() => BreakIntentQueue(PrefsBreakIntentStore()).enqueue(
kind: BreakIntentKind.done,
exIdx: 1,
setIdx: 0,
now: DateTime.now(),
),
);
await tester.runAsync(() async {
client.onNudge!();
await Future<void>.delayed(const Duration(milliseconds: 400));
});
await tester.pump();
final saved = await tester.runAsync(
() => StorageService.instance.loadActiveSession(),
);
// Applying it would have tapped the set and saved the session.
expect(saved, isNull);
});
}

View File

@ -1,78 +0,0 @@
// Rest lengths come from the exercise's own settings: warmup, success and
// fail rests, and the fail rest the notification's `−1 rep` re-cuts to.
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/widgets/rep_circle.dart';
import '../fake_audio_platform.dart';
import '../fake_break_service.dart';
import '../fake_secure_storage.dart';
import '_workout_screen_test_fixtures.dart';
// Real plan names, so each has a progression-state row to hold its rests.
const _lunge = Exercise(name: 'Dumbbell Lunge', sets: 3, reps: 5, weight: 10);
const _row = Exercise(name: 'Dumbbell Row', sets: 3, reps: 5, weight: 20);
void main() {
late FakeForegroundBreakClient client;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeSecureStorage();
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
client = FakeForegroundBreakClient();
});
Future<void> pumpWithLungeRests(WidgetTester tester) async {
await tester.runAsync(() async {
final s = (await StorageService.instance.getExerciseState(_lunge.name))!;
await StorageService.instance.setExerciseSettings(
s.copyWith(restSuccessSecs: 200, restFailSecs: 250, restWarmupSecs: 90),
);
});
await pumpWorkout(
tester,
wrapWorkout(exercises: const [_lunge, _row], breakClient: client),
);
}
testWidgets('the warmup rest is the exercise\'s own', (tester) async {
await pumpWithLungeRests(tester);
await tapReal(tester, find.bySemanticsLabel('Dumbbell Lunge warmup'));
expect(restSecs(tester), inInclusiveRange(85, 90));
});
testWidgets('success and fail rests are the exercise\'s own', (tester) async {
await pumpWithLungeRests(tester);
final circle = find.byType(RepCircle).first;
await tapReal(tester, circle); // target hit -> success rest
expect(restSecs(tester), inInclusiveRange(195, 200));
// The notification carries the fail rest for a `−1 rep` press.
expect(client.pushed.last.breakFailSecs, 250);
await tapReal(tester, circle); // one rep short -> fail rest
expect(restSecs(tester), inInclusiveRange(245, 250));
});
testWidgets('an exercise left at defaults keeps 3:00 and 5:00', (
tester,
) async {
await pumpWithLungeRests(tester);
final rowFirstSet = find.byType(RepCircle).at(_lunge.sets);
await tapReal(tester, rowFirstSet);
expect(restSecs(tester), inInclusiveRange(175, 180));
expect(client.pushed.last.breakFailSecs, 300);
});
}

View File

@ -123,13 +123,12 @@ void main() {
testWidgets('− 1 rep stretches the rest from 3 minutes to 5', (tester) async { testWidgets('− 1 rep stretches the rest from 3 minutes to 5', (tester) async {
await pump(tester, saved: savedWithBreak(170)); await pump(tester, saved: savedWithBreak(170));
expect(restSecs(tester), lessThanOrEqualTo(170)); expect(find.textContaining('well done'), findsOneWidget);
await seed([(BreakIntentKind.minusRep, 0, 0)]); await seed([(BreakIntentKind.minusRep, 0, 0)]);
await nudge(tester); await nudge(tester);
// Re-cut to 300 from the same start: 10 s in, so about 290 left. expect(find.textContaining('keep going'), findsOneWidget);
expect(restSecs(tester), inInclusiveRange(280, 290));
expect(lastPushed().breakDurationSecs, 300); expect(lastPushed().breakDurationSecs, 300);
}); });

View File

@ -35,16 +35,9 @@ void main() {
installFakeAudioPlatform(); installFakeAudioPlatform();
}); });
testWidgets('has no app bar: no workout type, no elapsed clock', ( testWidgets('shows Workout A in app bar', (tester) async {
tester,
) async {
// Dropped 2026-09-27 for room: Reset/Finish live in the rest strip.
await pumpWorkout(tester, wrapWorkout()); await pumpWorkout(tester, wrapWorkout());
expect(find.byType(AppBar), findsNothing); expect(find.textContaining('Workout A'), findsOneWidget);
expect(find.textContaining('Workout A'), findsNothing);
// The strip's idle countdown is the only 00:00 on screen.
expect(find.text('00:00'), findsOneWidget);
expect(find.byType(SafeArea), findsWidgets);
}); });
testWidgets('shows exercise tiles for all exercises', (tester) async { testWidgets('shows exercise tiles for all exercises', (tester) async {
@ -135,4 +128,16 @@ void main() {
await tester.tap(find.text('Cancel')); await tester.tap(find.text('Cancel'));
await tester.pump(); await tester.pump();
}); });
testWidgets('elapsed timer shows time in app bar', (tester) async {
await pumpWorkout(tester, wrapWorkout());
// The idle rest strip shows 00:00 too; the app bar's clock carries the
// workout type in the same string.
expect(find.textContaining('Workout A · 00:00'), findsOneWidget);
});
testWidgets('B workout type shows in app bar', (tester) async {
await pumpWorkout(tester, wrapWorkout(type: 'B'));
expect(find.textContaining('Workout B'), findsOneWidget);
});
} }

View File

@ -1,56 +0,0 @@
// Shared harness for the BreakTaskHandler tests: an in-memory intent store
// and a snapshot builder with every field defaulted.
import 'package:workout_app/models/break_snapshot.dart';
import 'package:workout_app/services/break_intent_store.dart';
/// A [BreakIntentStore] backed by two maps.
class MemIntentStore implements BreakIntentStore {
final ints = <String, int>{};
final lists = <String, List<String>>{};
@override
Future<int> readInt(String key) async => ints[key] ?? 0;
@override
Future<void> writeInt(String key, int value) async => ints[key] = value;
@override
Future<List<String>> readStringList(String key) async =>
lists[key] ?? const [];
@override
Future<void> writeStringList(String key, List<String> value) async =>
lists[key] = List.of(value);
}
/// A snapshot map as the UI sends it, with every field defaulted.
Map<String, Object?> snapMap({
int breakEndMs = 0,
int breakDurationSecs = 180,
int breakFailSecs = 300,
int nextExIdx = 0,
int nextSetIdx = 1,
int lastExIdx = 0,
int lastSetIdx = 0,
int breakForExIdx = 0,
int breakForSetIdx = 0,
int setsRemaining = 4,
}) => BreakSnapshot(
workoutType: 'A',
breakEndMs: breakEndMs,
breakDurationSecs: breakDurationSecs,
breakFailSecs: breakFailSecs,
breakLabel: 'Rest (3 min — well done!)',
breakForExIdx: breakForExIdx,
breakForSetIdx: breakForSetIdx,
nextExIdx: nextExIdx,
nextSetIdx: nextSetIdx,
nextExName: 'Squat',
nextSetNumber: nextSetIdx + 1,
nextTotalSets: 5,
nextReps: 5,
nextWeight: 40,
lastExIdx: lastExIdx,
lastSetIdx: lastSetIdx,
setsRemaining: setsRemaining,
).toMap();

View File

@ -18,7 +18,6 @@ BreakSnapshot snap({
workoutType: 'A', workoutType: 'A',
breakEndMs: breakEndMs, breakEndMs: breakEndMs,
breakDurationSecs: breakDurationSecs, breakDurationSecs: breakDurationSecs,
breakFailSecs: 300,
breakLabel: 'Rest', breakLabel: 'Rest',
breakForExIdx: 0, breakForExIdx: 0,
breakForSetIdx: 1, breakForSetIdx: 1,
@ -41,9 +40,7 @@ void main() {
test('shows the countdown in the title, which Android shows collapsed', () { test('shows the countdown in the title, which Android shows collapsed', () {
final copy = BreakNotificationText.render( final copy = BreakNotificationText.render(
snap( snap(
breakEndMs: now breakEndMs: now.add(const Duration(seconds: 107)).millisecondsSinceEpoch,
.add(const Duration(seconds: 107))
.millisecondsSinceEpoch,
breakDurationSecs: 180, breakDurationSecs: 180,
), ),
now, now,
@ -55,9 +52,7 @@ void main() {
test('says the break is over once the deadline has passed', () { test('says the break is over once the deadline has passed', () {
final copy = BreakNotificationText.render( final copy = BreakNotificationText.render(
snap( snap(
breakEndMs: now breakEndMs: now.subtract(const Duration(seconds: 5)).millisecondsSinceEpoch,
.subtract(const Duration(seconds: 5))
.millisecondsSinceEpoch,
breakDurationSecs: 180, breakDurationSecs: 180,
), ),
now, now,

View File

@ -31,7 +31,6 @@ const _snapshot = BreakSnapshot(
workoutType: 'A', workoutType: 'A',
breakEndMs: 0, breakEndMs: 0,
breakDurationSecs: 0, breakDurationSecs: 0,
breakFailSecs: 300,
breakLabel: '', breakLabel: '',
breakForExIdx: -1, breakForExIdx: -1,
breakForSetIdx: -1, breakForSetIdx: -1,
@ -63,14 +62,12 @@ void main() {
Future<BreakServiceStartResult> start() => Future<BreakServiceStartResult> start() =>
controller.start(_snapshot, onDrainNudge: () {}); controller.start(_snapshot, onDrainNudge: () {});
test( test('starts and reports success when the permission is already held',
'starts and reports success when the permission is already held',
() async { () async {
expect(await start(), BreakServiceStartResult.started); expect(await start(), BreakServiceStartResult.started);
expect(controller.isStarted, isTrue); expect(controller.isStarted, isTrue);
expect(client.calls, ['init', 'hasPermission', 'listen', 'start']); expect(client.calls, ['init', 'hasPermission', 'listen', 'start']);
}, });
);
test('asks for the permission when it is not held yet', () async { test('asks for the permission when it is not held yet', () async {
client.permissionGranted = false; client.permissionGranted = false;
@ -89,25 +86,21 @@ void main() {
expect(controller.isStarted, isTrue); expect(controller.isStarted, isTrue);
}); });
test( test('reports failure and stops listening when the service refuses to start',
'reports failure and stops listening when the service refuses to start',
() async { () async {
client.startSucceeds = false; client.startSucceeds = false;
expect(await start(), BreakServiceStartResult.failed); expect(await start(), BreakServiceStartResult.failed);
expect(controller.isStarted, isFalse); expect(controller.isStarted, isFalse);
expect(client.calls.last, 'unlisten'); expect(client.calls.last, 'unlisten');
}, });
);
test( test('does nothing at all on a platform with no foreground service',
'does nothing at all on a platform with no foreground service',
() async { () async {
client.isSupported = false; client.isSupported = false;
expect(await start(), BreakServiceStartResult.unsupported); expect(await start(), BreakServiceStartResult.unsupported);
expect(client.calls, isEmpty); expect(client.calls, isEmpty);
expect(controller.isStarted, isFalse); expect(controller.isStarted, isFalse);
}, });
);
test('push is a no-op until the service has started', () async { test('push is a no-op until the service has started', () async {
await controller.push(_snapshot); await controller.push(_snapshot);
@ -190,8 +183,7 @@ void main() {
expect(client.calls, contains('stop')); expect(client.calls, contains('stop'));
}); });
test( test('leaves a service alone while its workout is still in progress',
'leaves a service alone while its workout is still in progress',
() async { () async {
client.running = true; client.running = true;
final stopped = await stopStaleBreakService( final stopped = await stopStaleBreakService(
@ -200,16 +192,12 @@ void main() {
); );
expect(stopped, isFalse); expect(stopped, isFalse);
expect(client.calls, isNot(contains('stop'))); expect(client.calls, isNot(contains('stop')));
}, });
);
test('does nothing when no service is running', () async { test('does nothing when no service is running', () async {
client.running = false; client.running = false;
expect( expect(
await stopStaleBreakService( await stopStaleBreakService(client, hasActiveWorkout: () async => false),
client,
hasActiveWorkout: () async => false,
),
isFalse, isFalse,
); );
expect(client.calls, isNot(contains('stop'))); expect(client.calls, isNot(contains('stop')));
@ -220,10 +208,7 @@ void main() {
..isSupported = false ..isSupported = false
..running = true; ..running = true;
expect( expect(
await stopStaleBreakService( await stopStaleBreakService(client, hasActiveWorkout: () async => false),
client,
hasActiveWorkout: () async => false,
),
isFalse, isFalse,
); );
expect(client.calls, isEmpty); expect(client.calls, isEmpty);

View File

@ -7,23 +7,70 @@ import 'package:workout_app/services/break_service_port.dart';
import 'package:workout_app/services/break_task_handler.dart'; import 'package:workout_app/services/break_task_handler.dart';
import '../fake_break_service.dart'; import '../fake_break_service.dart';
import '_break_task_handler_fixtures.dart';
class _MemStore implements BreakIntentStore {
final ints = <String, int>{};
final lists = <String, List<String>>{};
@override
Future<int> readInt(String key) async => ints[key] ?? 0;
@override
Future<void> writeInt(String key, int value) async => ints[key] = value;
@override
Future<List<String>> readStringList(String key) async =>
lists[key] ?? const [];
@override
Future<void> writeStringList(String key, List<String> value) async =>
lists[key] = List.of(value);
}
void main() { void main() {
final now = DateTime(2026, 9, 12, 14); final now = DateTime(2026, 9, 12, 14);
late FakeBreakServicePort port; late FakeBreakServicePort port;
late MemIntentStore store; late _MemStore store;
late BreakIntentQueue queue; late BreakIntentQueue queue;
late BreakTaskHandler handler; late BreakTaskHandler handler;
setUp(() { setUp(() {
port = FakeBreakServicePort(); port = FakeBreakServicePort();
store = MemIntentStore(); store = _MemStore();
queue = BreakIntentQueue(store); queue = BreakIntentQueue(store);
handler = BreakTaskHandler(port, queue); handler = BreakTaskHandler(port, queue);
}); });
Map<String, Object?> snapMap({
int breakEndMs = 0,
int breakDurationSecs = 180,
int nextExIdx = 0,
int nextSetIdx = 1,
int lastExIdx = 0,
int lastSetIdx = 0,
int breakForExIdx = 0,
int breakForSetIdx = 0,
int setsRemaining = 4,
}) => BreakSnapshot(
workoutType: 'A',
breakEndMs: breakEndMs,
breakDurationSecs: breakDurationSecs,
breakLabel: 'Rest (3 min — well done!)',
breakForExIdx: breakForExIdx,
breakForSetIdx: breakForSetIdx,
nextExIdx: nextExIdx,
nextSetIdx: nextSetIdx,
nextExName: 'Squat',
nextSetNumber: nextSetIdx + 1,
nextTotalSets: 5,
nextReps: 5,
nextWeight: 40,
lastExIdx: lastExIdx,
lastSetIdx: lastSetIdx,
setsRemaining: setsRemaining,
).toMap();
Future<List<BreakIntent>> queued() async { Future<List<BreakIntent>> queued() async {
final raw = await store.readStringList(BreakIntentQueue.intentsKey); final raw = await store.readStringList(BreakIntentQueue.intentsKey);
return [for (final e in raw) BreakIntent.tryDecode(e)!]; return [for (final e in raw) BreakIntent.tryDecode(e)!];
@ -93,8 +140,7 @@ void main() {
expect(port.nudges, 1); expect(port.nudges, 1);
}); });
test( test('− 1 rep targets the set recorded last, resolved at press time',
'− 1 rep targets the set recorded last, resolved at press time',
() async { () async {
await handler.start(snapMap(lastExIdx: 2, lastSetIdx: 3), now); await handler.start(snapMap(lastExIdx: 2, lastSetIdx: 3), now);
await handler.pressButton(BreakNotificationAction.minusRep, now); await handler.pressButton(BreakNotificationAction.minusRep, now);
@ -103,31 +149,25 @@ void main() {
expect(intents.single.kind, BreakIntentKind.minusRep); expect(intents.single.kind, BreakIntentKind.minusRep);
expect(intents.single.exIdx, 2); expect(intents.single.exIdx, 2);
expect(intents.single.setIdx, 3); expect(intents.single.setIdx, 3);
}, });
);
test('− 1 rep stretches a running rest to the exercise\'s failure ' test('− 1 rep stretches a running rest to the failure length', () async {
'length', () async { final endMs = now.add(const Duration(seconds: 120)).millisecondsSinceEpoch;
final endMs = now
.add(const Duration(seconds: 120))
.millisecondsSinceEpoch;
await handler.start( await handler.start(
snapMap(breakEndMs: endMs, breakDurationSecs: 180, breakFailSecs: 270), snapMap(breakEndMs: endMs, breakDurationSecs: 180),
now, now,
); );
await handler.pressButton(BreakNotificationAction.minusRep, now); await handler.pressButton(BreakNotificationAction.minusRep, now);
final s = handler.snapshot!; final s = handler.snapshot!;
// The exercise's own fail rest from the snapshot, not a fixed 5 min. expect(s.breakDurationSecs, 300);
expect(s.breakDurationSecs, 270); expect(s.breakLabel, contains('5 min'));
// No "5 min — keep going!" any more: the countdown says it. // Re-cut from the original start: 60s in, so 240s left of 300.
expect(s.breakLabel, 'Rest');
// Re-cut from the original start: 60s in, so 210s left of 270.
expect( expect(
DateTime.fromMillisecondsSinceEpoch( DateTime.fromMillisecondsSinceEpoch(s.breakEndMs)
s.breakEndMs, .difference(now)
).difference(now).inSeconds, .inSeconds,
210, 240,
); );
}); });
@ -140,14 +180,12 @@ void main() {
expect(handler.snapshot!.hasBreak, isFalse); expect(handler.snapshot!.hasBreak, isFalse);
}); });
test( test('Done on the last set stops the service instead of carrying on',
'Done on the last set stops the service instead of carrying on',
() async { () async {
await handler.start(snapMap(setsRemaining: 1), now); await handler.start(snapMap(setsRemaining: 1), now);
await handler.pressButton(BreakNotificationAction.done, now); await handler.pressButton(BreakNotificationAction.done, now);
expect(port.stopped, isTrue); expect(port.stopped, isTrue);
}, });
);
test('ignores presses that no longer refer to anything', () async { test('ignores presses that no longer refer to anything', () async {
await handler.start( await handler.start(

View File

@ -1,113 +0,0 @@
// The progression-mode, warmup, pause and rest fields on a Firebase progression
// record: pushed, pulled back, and read leniently from records written
// before they existed.
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import '_progression_test_fixtures.dart';
Map<String, dynamic> _payload(FakeStore store, String name) =>
Record.fromJson(
jsonDecode(store.files[ProgressionSyncService.pathForExercise(name)]!)
as Map<String, dynamic>,
).fields['payload']!.$1
as Map<String, dynamic>;
void main() {
late FakeStore store;
late ProgressionSyncService sync;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
store = FakeStore();
sync = ProgressionSyncService(firebaseFactory: () async => store);
StorageService.resetForTesting();
await StorageService.init();
});
test(
'a record from before modes existed restores with the defaults',
() async {
seedRemote(store, 'Situp', weight: 5, reps: 31, maxWeight: 10);
seedRemote(store, 'Dumbbell Row', weight: 27.5, reps: 6);
await sync.pullProgression();
final situp = (await StorageService.instance.getExerciseState('Situp'))!;
expect(situp.mode, ProgressionMode.weight);
expect((situp.repsHigh, situp.repsLow), (12, 6));
// Missing has_warmup = the plan's default, never a blanket "on".
expect(situp.hasWarmup, isFalse);
expect(situp.pausedUntil, isNull);
expect(
(situp.restSuccessSecs, situp.restFailSecs, situp.restWarmupSecs),
(180, 300, 180),
);
final row = (await StorageService.instance.getExerciseState(
'Dumbbell Row',
))!;
expect(row.hasWarmup, isTrue);
},
);
test(
'mode, rep range, warmup, pause and rests survive a push and a pull',
() async {
final storage = StorageService.instance;
final situp = (await storage.getExerciseState('Situp'))!;
await storage.setExerciseSettings(
situp.copyWith(
mode: ProgressionMode.doubleProgression,
repsHigh: 20,
repsLow: 10,
hasWarmup: true,
pausedUntil: DateTime(2026, 10, 11),
restSuccessSecs: 150,
restFailSecs: 240,
restWarmupSecs: 90,
),
);
await markSynced();
await sync.pushProgression();
final pushed = _payload(store, 'Situp');
expect(pushed['progression_mode'], 'double');
expect((pushed['reps_high'], pushed['reps_low']), (20, 10));
expect(pushed['has_warmup'], isTrue);
expect(pushed['paused_until'], '2026-10-11');
expect(
(
pushed['rest_success_secs'],
pushed['rest_fail_secs'],
pushed['rest_warmup_secs'],
),
(150, 240, 90),
);
expect(_payload(store, 'Dumbbell Row')['paused_until'], isNull);
// A reinstall: fresh database, same Firebase.
StorageService.resetForTesting();
await StorageService.init();
await sync.pullProgression();
final back = (await StorageService.instance.getExerciseState('Situp'))!;
expect(back.mode, ProgressionMode.doubleProgression);
expect((back.repsHigh, back.repsLow), (20, 10));
expect(back.hasWarmup, isTrue);
expect(back.pausedUntil, DateTime(2026, 10, 11));
expect(
(back.restSuccessSecs, back.restFailSecs, back.restWarmupSecs),
(150, 240, 90),
);
},
);
}

View File

@ -1,179 +0,0 @@
// Progression modes, the per-exercise warmup toggle, and the v3 -> v4
// schema upgrade that added both.
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/storage_service.dart';
StorageService get _svc => StorageService.instance;
/// Builds a database exactly as a v3 install left it: the v3 schema, a
/// finished workout from today, and a workout in progress.
Future<void> _writeV3Database(String path) async {
final db = await databaseFactory.openDatabase(
path,
options: OpenDatabaseOptions(
version: 3,
onCreate: (db, _) async {
await db.execute(
'CREATE TABLE exercise_state (name TEXT PRIMARY KEY, '
'weight REAL NOT NULL, reps INTEGER NOT NULL, '
'success_streak INTEGER NOT NULL DEFAULT 0, '
'fail_streak INTEGER NOT NULL DEFAULT 0, max_weight REAL NOT NULL, '
'success_threshold INTEGER NOT NULL DEFAULT 3, '
'fail_threshold INTEGER NOT NULL DEFAULT 2)',
);
await db.execute(
'CREATE TABLE workout_history (id INTEGER PRIMARY KEY '
'AUTOINCREMENT, date TEXT NOT NULL, workout_type TEXT NOT NULL, '
'duration_seconds INTEGER NOT NULL, succeeded INTEGER NOT NULL, '
'json TEXT NOT NULL)',
);
await db.execute(
'CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)',
);
await db.execute(
'CREATE TABLE active_session (id INTEGER PRIMARY KEY '
'CHECK (id = 1), json TEXT NOT NULL)',
);
},
),
);
for (final ex in [...workoutA, ...workoutB]) {
await db.insert('exercise_state', {
'name': ex.name,
'weight': 17.5,
'reps': 9,
'success_streak': 2,
'fail_streak': 1,
'max_weight': ex.maxWeight,
'success_threshold': 5,
'fail_threshold': 4,
}, conflictAlgorithm: ConflictAlgorithm.replace);
}
await db.insert('workout_history', {
'date': '2026-09-27',
'workout_type': 'A',
'duration_seconds': 4000,
'succeeded': 1,
'json': '{"workoutType":"A"}',
});
await db.insert('settings', {'key': 'last_workout_type', 'value': 'A'});
await db.insert('active_session', {'id': 1, 'json': jsonEncode(_session)});
await db.close();
}
const _session = {
'workoutType': 'B',
'startTimeMs': 1790516739892,
'tapped': [
[true, true, true, true, true],
[true, true, true, true, true],
[true, true, true, true, false],
[false, false, false],
],
'doneReps': [
[9, 9, 9, 9, 9],
[12, 12, 12, 12, 12],
[12, 12, 12, 12, 12],
[31, 31, 31],
],
'warmupTapped': [true, true, true, false],
};
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
});
group('v3 -> v4 upgrade', () {
late Directory dir;
setUp(() async {
dir = await Directory.systemTemp.createTemp('mw_v4');
final file = p.join(dir.path, 'v3.db');
await _writeV3Database(file);
StorageService.resetForTesting(dbPath: file);
await StorageService.init();
});
tearDown(() => dir.delete(recursive: true));
test('keeps a workout in progress byte for byte', () async {
expect(await _svc.loadActiveSession(), _session);
});
test("keeps today's finished workout and the history marker", () async {
expect(await _svc.getLastWorkoutDate(), DateTime(2026, 9, 27));
expect(await _svc.getNextWorkoutType(), 'B');
expect(await _svc.looksFreshlyInstalled(), isFalse);
});
test('keeps progression and gives every row weight mode', () async {
for (final ex in [...workoutA, ...workoutB]) {
final s = (await _svc.getExerciseState(ex.name))!;
expect(
(s.weight, s.reps, s.successStreak, s.failStreak),
(17.5, 9, 2, 1),
);
expect((s.successThreshold, s.failThreshold), (5, 4));
expect(s.mode, ProgressionMode.weight);
expect((s.repsHigh, s.repsLow), (kDefaultRepsHigh, kDefaultRepsLow));
// NULL column -> the plan's default: Situp stays warmup-free.
expect(s.hasWarmup, ex.hasWarmup, reason: ex.name);
}
});
});
test('v4 -> v5 (the phone today) keeps settings and adds no pause', () async {
final dir = await Directory.systemTemp.createTemp('mw_v5');
addTearDown(() => dir.delete(recursive: true));
final file = p.join(dir.path, 'v4.db');
await _writeV3Database(file);
// Upgrade to exactly v4 the way the v4 build did, and set a mode there.
final v4 = await databaseFactory.openDatabase(
file,
options: OpenDatabaseOptions(
version: 4,
onUpgrade: (db, _, _) async {
await db.execute(
"ALTER TABLE exercise_state ADD COLUMN progression_mode TEXT "
"NOT NULL DEFAULT 'weight'",
);
await db.execute(
'ALTER TABLE exercise_state ADD COLUMN reps_high INTEGER '
'NOT NULL DEFAULT 12',
);
await db.execute(
'ALTER TABLE exercise_state ADD COLUMN reps_low INTEGER '
'NOT NULL DEFAULT 6',
);
await db.execute(
'ALTER TABLE exercise_state ADD COLUMN has_warmup INTEGER',
);
},
),
);
await v4.update('exercise_state', {
'progression_mode': 'double',
'has_warmup': 0,
}, where: "name = 'Situp'");
await v4.close();
StorageService.resetForTesting(dbPath: file);
await StorageService.init();
final situp = (await _svc.getExerciseState('Situp'))!;
expect(situp.mode, ProgressionMode.doubleProgression);
expect(situp.hasWarmup, isFalse);
expect(situp.pausedUntil, isNull);
expect(await _svc.getLastWorkoutDate(), DateTime(2026, 9, 27));
});
}

View File

@ -55,11 +55,6 @@ void main() {
expect(st, isNotNull); expect(st, isNotNull);
expect(st!.successThreshold, 3); expect(st!.successThreshold, 3);
expect(st.failThreshold, 2); expect(st.failThreshold, 2);
// … and the <6 block added the rest columns at the old fixed lengths.
expect(
(st.restSuccessSecs, st.restFailSecs, st.restWarmupSecs),
(180, 300, 180),
);
await dir.delete(recursive: true); await dir.delete(recursive: true);
}); });

View File

@ -1,128 +0,0 @@
// Per-exercise settings writes and progression per mode, through storage.
// Split from storage_service_modes_test.dart for the 250-line cap.
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/storage_service.dart';
StorageService get _svc => StorageService.instance;
final _yesterday = DateTime.now().subtract(const Duration(days: 1));
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
});
group('setExerciseSettings', () {
test('persists mode, rep range, warmup and thresholds', () async {
final name = workoutA.first.name;
final s = (await _svc.getExerciseState(name))!;
await _svc.setExerciseSettings(
s.copyWith(
mode: ProgressionMode.doubleProgression,
repsHigh: 15,
repsLow: 8,
hasWarmup: false,
successThreshold: 1,
failThreshold: 4,
),
);
final after = (await _svc.getExerciseState(name))!;
expect(after.mode, ProgressionMode.doubleProgression);
expect((after.repsHigh, after.repsLow), (15, 8));
expect(after.hasWarmup, isFalse);
expect((after.successThreshold, after.failThreshold), (1, 4));
// The target itself is untouched until the next finished workout.
expect((after.weight, after.reps), (s.weight, s.reps));
});
test('persists a pause and its resume', () async {
final s = (await _svc.getExerciseState('Situp'))!;
await _svc.setExerciseSettings(
s.copyWith(pausedUntil: DateTime(2026, 10, 11)),
);
expect(
(await _svc.getExerciseState('Situp'))!.pausedUntil,
DateTime(2026, 10, 11),
);
await _svc.setExerciseSettings(s.copyWith(resume: true));
expect((await _svc.getExerciseState('Situp'))!.pausedUntil, isNull);
});
test('reaches the workout through getCurrentExercises', () async {
final name = workoutA.first.name;
final s = (await _svc.getExerciseState(name))!;
await _svc.setExerciseSettings(s.copyWith(hasWarmup: false));
final exercises = await _svc.getCurrentExercises('A');
expect(exercises.first.hasWarmup, isFalse);
expect(exercises[1].hasWarmup, isTrue);
});
});
group('applyProgression per mode', () {
Future<ExerciseState> run(
ProgressionMode mode, {
required bool success,
required int reps,
DateTime? last,
}) async {
final name = workoutA.first.name;
final s = (await _svc.getExerciseState(name))!;
await _svc.setExerciseSettings(
s.copyWith(mode: mode, successThreshold: 1, failThreshold: 1),
);
await _svc.setExerciseReps(name, reps);
await _svc.setExerciseWeight(name, 10);
await _svc.applyProgression(
succeededExercises: {name: success},
lastWorkoutDate: last ?? _yesterday,
);
return (await _svc.getExerciseState(name))!;
}
test('reps: success adds a rep', () async {
final s = await run(ProgressionMode.reps, success: true, reps: 10);
expect((s.weight, s.reps, s.successStreak), (10, 11, 0));
});
test('reps: failure removes a rep', () async {
final s = await run(ProgressionMode.reps, success: false, reps: 10);
expect((s.weight, s.reps, s.failStreak), (10, 9, 0));
});
test('double: success at n moves up in weight and back to m', () async {
final s = await run(
ProgressionMode.doubleProgression,
success: true,
reps: 12,
);
expect((s.weight, s.reps), (12.5, 6));
});
test('double: failure at m moves down in weight and up to n', () async {
final s = await run(
ProgressionMode.doubleProgression,
success: false,
reps: 6,
);
expect((s.weight, s.reps), (7.5, 12));
});
test('a week off is one regression step in the active mode', () async {
final s = await run(
ProgressionMode.reps,
success: true,
reps: 10,
last: DateTime.now().subtract(const Duration(days: 9)),
);
expect((s.weight, s.reps, s.successStreak, s.failStreak), (10, 9, 0, 0));
});
});
}

View File

@ -8,51 +8,64 @@ Widget _wrap(Widget child) => MaterialApp(
home: Scaffold(body: child), home: Scaffold(body: child),
); );
BreakBanner _banner({
bool active = true,
int breakRemaining = 90,
VoidCallback? onSkip,
bool finished = false,
bool canFinish = false,
VoidCallback? onReset,
VoidCallback? onFinish,
}) => BreakBanner(
active: active,
breakRemaining: breakRemaining,
onSkip: onSkip ?? () {},
finished: finished,
canFinish: canFinish,
onReset: onReset ?? () {},
onFinish: onFinish ?? () {},
);
Visibility _slotOf(WidgetTester tester, String text) =>
tester.widget<Visibility>(
find.ancestor(of: find.text(text), matching: find.byType(Visibility)),
);
void main() { void main() {
group('BreakBanner', () { group('BreakBanner', () {
testWidgets('shows only the formatted time — no label', (tester) async { testWidgets('displays label and formatted time', (tester) async {
await tester.pumpWidget(_wrap(_banner())); await tester.pumpWidget(
_wrap(
BreakBanner(
active: true,
breakRemaining: 90,
breakLabel: 'Rest',
onSkip: () {},
),
),
);
expect(find.text('Rest'), findsOneWidget);
expect(find.text('01:30'), findsOneWidget); expect(find.text('01:30'), findsOneWidget);
expect(find.textContaining('Rest'), findsNothing);
}); });
testWidgets('formats time below one minute correctly', (tester) async { testWidgets('formats time below one minute correctly', (tester) async {
await tester.pumpWidget(_wrap(_banner(breakRemaining: 5))); await tester.pumpWidget(
_wrap(
BreakBanner(
active: true,
breakRemaining: 5,
breakLabel: 'Warmup rest',
onSkip: () {},
),
),
);
expect(find.text('00:05'), findsOneWidget); expect(find.text('00:05'), findsOneWidget);
}); });
testWidgets('skip button calls onSkip', (tester) async { testWidgets('skip button calls onSkip', (tester) async {
var skipped = false; var skipped = false;
await tester.pumpWidget(_wrap(_banner(onSkip: () => skipped = true))); await tester.pumpWidget(
_wrap(
BreakBanner(
active: true,
breakRemaining: 60,
breakLabel: 'Rest',
onSkip: () => skipped = true,
),
),
);
await tester.tap(find.text('Skip')); await tester.tap(find.text('Skip'));
expect(skipped, isTrue); expect(skipped, isTrue);
}); });
testWidgets('keeps its height and hides Skip while idle', (tester) async { testWidgets('keeps its height and hides Skip while idle', (tester) async {
await tester.pumpWidget(_wrap(_banner(active: false, breakRemaining: 0))); await tester.pumpWidget(
_wrap(
BreakBanner(
active: false,
breakRemaining: 0,
breakLabel: 'Rest',
onSkip: () {},
),
),
);
expect( expect(
tester.getSize(find.byType(BreakBanner)).height, tester.getSize(find.byType(BreakBanner)).height,
BreakBanner.height, BreakBanner.height,
@ -60,43 +73,25 @@ void main() {
expect(find.text('00:00'), findsOneWidget); expect(find.text('00:00'), findsOneWidget);
// Skip keeps its space (nothing may move when a rest starts) but is // Skip keeps its space (nothing may move when a rest starts) but is
// neither visible nor tappable. // neither visible nor tappable.
final skip = _slotOf(tester, 'Skip'); final skip = tester.widget<Visibility>(
find.ancestor(of: find.text('Skip'), matching: find.byType(Visibility)),
);
expect(skip.visible, isFalse); expect(skip.visible, isFalse);
expect(skip.maintainSize, isTrue); expect(skip.maintainSize, isTrue);
}); });
testWidgets('Reset calls onReset', (tester) async { testWidgets('zero seconds formats as 00:00', (tester) async {
var reset = false;
await tester.pumpWidget(_wrap(_banner(onReset: () => reset = true)));
await tester.tap(find.text('Reset'));
expect(reset, isTrue);
});
testWidgets('Finish is disabled until every set is done', (tester) async {
var finished = 0;
await tester.pumpWidget(_wrap(_banner(onFinish: () => finished++)));
await tester.tap(find.text('Finish'));
expect(finished, 0);
await tester.pumpWidget( await tester.pumpWidget(
_wrap(_banner(canFinish: true, onFinish: () => finished++)), _wrap(
BreakBanner(
active: true,
breakRemaining: 0,
breakLabel: 'Rest',
onSkip: () {},
),
),
); );
await tester.tap(find.text('Finish')); expect(find.text('00:00'), findsOneWidget);
expect(finished, 1);
});
testWidgets('a finished workout hides Reset and Finish, space kept', (
tester,
) async {
await tester.pumpWidget(_wrap(_banner()));
final finishAt = tester.getRect(find.text('Finish'));
await tester.pumpWidget(_wrap(_banner(finished: true)));
for (final label in ['Reset', 'Finish']) {
final slot = _slotOf(tester, label);
expect(slot.visible, isFalse, reason: label);
expect(slot.maintainSize, isTrue, reason: label);
}
expect(tester.getRect(find.text('Finish')), finishAt);
}); });
}); });
} }

View File

@ -1,186 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
final _base = ExerciseState.initial(workoutA.first);
Future<List<ExerciseState>> _pump(
WidgetTester tester, [
ExerciseState? state,
]) async {
final edits = <ExerciseState>[];
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: Scaffold(
body: ExerciseSettingsSheet(
state: state ?? _base,
onChanged: edits.add,
),
),
),
);
return edits;
}
Future<void> _tapLabel(WidgetTester tester, String label) async {
await tester.tap(find.bySemanticsLabel(label));
await tester.pump();
}
void main() {
testWidgets('switching mode reports it and keeps the sheet height', (
tester,
) async {
final edits = await _pump(tester);
final before = tester.getSize(find.byType(ExerciseSettingsSheet));
expect(find.textContaining('+2.5 kg per step'), findsOneWidget);
await tester.tap(find.text('Reps'));
await tester.pump();
expect(edits.last.mode, ProgressionMode.reps);
expect(find.textContaining('the weight never changes'), findsOneWidget);
await tester.tap(find.text('Reps→kg'));
await tester.pump();
expect(edits.last.mode, ProgressionMode.doubleProgression);
expect(find.textContaining('up to 12, then'), findsOneWidget);
expect(tester.getSize(find.byType(ExerciseSettingsSheet)), before);
});
testWidgets('the rep range row only takes input in double mode', (
tester,
) async {
await _pump(tester);
expect(find.bySemanticsLabel('Top reps up'), findsNothing);
await tester.tap(find.text('Reps→kg'));
await tester.pump();
expect(find.bySemanticsLabel('Top reps up'), findsOneWidget);
});
testWidgets('n and m step and never cross', (tester) async {
final edits = await _pump(
tester,
_base.copyWith(
mode: ProgressionMode.doubleProgression,
repsHigh: 7,
repsLow: 6,
),
);
// m cannot reach n, n cannot drop to m.
await _tapLabel(tester, 'Restart reps up');
await _tapLabel(tester, 'Top reps down');
expect(edits, isEmpty);
await _tapLabel(tester, 'Top reps up');
expect(edits.last.repsHigh, 8);
await _tapLabel(tester, 'Restart reps up');
expect(edits.last.repsLow, 7);
await _tapLabel(tester, 'Restart reps down');
expect(edits.last.repsLow, 6);
await _tapLabel(tester, 'Top reps down');
expect(edits.last.repsHigh, 7);
});
testWidgets('warmup switch and thresholds are reported', (tester) async {
final edits = await _pump(tester);
await tester.tap(find.text('Warmup set'));
await tester.pump();
expect(edits.last.hasWarmup, isFalse);
await _tapLabel(tester, 'Wins needed down');
expect(edits.last.successThreshold, 2);
await _tapLabel(tester, 'Fails allowed up');
expect(edits.last.failThreshold, 3);
// Every edit carries the earlier ones, not just its own field.
expect(edits.last.hasWarmup, isFalse);
});
testWidgets('rests step by 15 s as m:ss and stop at the bounds', (
tester,
) async {
final edits = await _pump(
tester,
_base.copyWith(restSuccessSecs: kMaxRestSecs, restFailSecs: kMinRestSecs),
);
expect(find.text('10:00'), findsOneWidget);
expect(find.text('0:30'), findsOneWidget);
// Already at the bounds: nothing to report.
await _tapLabel(tester, 'Success rest up');
await _tapLabel(tester, 'Fail rest down');
expect(edits, isEmpty);
await _tapLabel(tester, 'Success rest down');
expect(edits.last.restSuccessSecs, kMaxRestSecs - kRestStepSecs);
expect(find.text('9:45'), findsOneWidget);
await _tapLabel(tester, 'Fail rest up');
expect(edits.last.restFailSecs, kMinRestSecs + kRestStepSecs);
await _tapLabel(tester, 'Warmup rest down');
expect(edits.last.restWarmupSecs, kDefaultRestWarmupSecs - kRestStepSecs);
// Every edit carries the earlier ones.
expect(edits.last.restSuccessSecs, kMaxRestSecs - kRestStepSecs);
});
testWidgets('the warmup rest hides with the warmup, keeping the height', (
tester,
) async {
await _pump(tester);
final before = tester.getSize(find.byType(ExerciseSettingsSheet));
final warmupRest = find.bySemanticsLabel('Warmup rest up').hitTestable();
expect(warmupRest, findsOneWidget);
await tester.tap(find.text('Warmup set'));
await tester.pump();
expect(warmupRest, findsNothing);
expect(tester.getSize(find.byType(ExerciseSettingsSheet)), before);
});
testWidgets('pause length steps from 14 and sets the end date', (
tester,
) async {
final edits = await _pump(tester);
expect(find.text('$kDefaultPauseDays'), findsOneWidget);
await _tapLabel(tester, 'Pause days up');
await _tapLabel(tester, 'Pause days up');
await _tapLabel(tester, 'Pause days down');
await tester.tap(find.text('Pause'));
await tester.pump();
expect(
edits.last.pausedUntil,
pauseEnd(DateTime.now(), kDefaultPauseDays + 1),
);
expect(find.textContaining('Paused — back on'), findsOneWidget);
await tester.tap(find.text('Resume'));
await tester.pump();
expect(edits.last.pausedUntil, isNull);
expect(find.text('Pause'), findsOneWidget);
});
testWidgets('showExerciseSettingsSheet opens it as a bottom sheet', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: Builder(
builder: (context) => TextButton(
onPressed: () => showExerciseSettingsSheet(
context,
state: _base,
onChanged: (_) {},
),
child: const Text('open'),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.byType(BottomSheet), findsOneWidget);
expect(find.text(_base.name), findsOneWidget);
});
}

View File

@ -1,10 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/ui/theme.dart'; import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart'; import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/widgets/exercise_tile.dart'; import 'package:workout_app/widgets/exercise_tile.dart';
import 'package:workout_app/widgets/rep_circle.dart'; import 'package:workout_app/widgets/rep_circle.dart';
@ -15,32 +12,29 @@ Widget _wrap(Widget child) => MaterialApp(
const _exercise = Exercise(name: 'Squat', sets: 3, reps: 5, weight: 20.0); const _exercise = Exercise(name: 'Squat', sets: 3, reps: 5, weight: 20.0);
final _state = ExerciseState.initial(_exercise);
ExerciseTile _tile({ ExerciseTile _tile({
ExerciseState? state,
List<bool>? tapped, List<bool>? tapped,
List<int>? doneReps, List<int>? doneReps,
bool warmupTapped = false, bool warmupTapped = false,
int successThreshold = 3,
int failThreshold = 2,
void Function(int)? onTapCircle, void Function(int)? onTapCircle,
void Function(int)? onLongPressCircle, void Function(int)? onLongPressCircle,
VoidCallback? onTapWarmup, VoidCallback? onTapWarmup,
ValueChanged<ExerciseState>? onSettingsChanged, void Function(int, int)? onThresholdChanged,
}) => ExerciseTile( }) => ExerciseTile(
exercise: _exercise, exercise: _exercise,
state: state ?? _state,
tapped: tapped ?? [false, false, false], tapped: tapped ?? [false, false, false],
doneReps: doneReps ?? [5, 5, 5], doneReps: doneReps ?? [5, 5, 5],
warmupTapped: warmupTapped, warmupTapped: warmupTapped,
successThreshold: successThreshold,
failThreshold: failThreshold,
onTapCircle: onTapCircle ?? (_) {}, onTapCircle: onTapCircle ?? (_) {},
onLongPressCircle: onLongPressCircle ?? (_) {}, onLongPressCircle: onLongPressCircle ?? (_) {},
onTapWarmup: onTapWarmup ?? () {}, onTapWarmup: onTapWarmup ?? () {},
onSettingsChanged: onSettingsChanged ?? (_) {}, onThresholdChanged: onThresholdChanged ?? (_, __) {},
); );
Color _cardColor(WidgetTester tester) =>
tester.widget<Card>(find.byType(Card)).color!;
void main() { void main() {
group('ExerciseTile', () { group('ExerciseTile', () {
testWidgets('shows exercise name and weight info', (tester) async { testWidgets('shows exercise name and weight info', (tester) async {
@ -49,152 +43,120 @@ void main() {
expect(find.textContaining('3×5×20.0kg'), findsOneWidget); expect(find.textContaining('3×5×20.0kg'), findsOneWidget);
}); });
testWidgets('warmup is the first circle, with its weight', (tester) async { testWidgets('shows warmup weight', (tester) async {
await tester.pumpWidget(_wrap(_tile())); await tester.pumpWidget(_wrap(_tile()));
expect(find.text('W×6'), findsOneWidget); // warmupWeight for 20kg squat = 10kg (50%)
expect(find.text('${_exercise.warmupWeight}'), findsOneWidget); expect(
final warmup = tester.getRect(find.bySemanticsLabel('Squat warmup')); find.textContaining('${_exercise.warmupWeight}kg'),
final firstSet = tester.getRect(find.byType(RepCircle).first); findsOneWidget,
expect(warmup.left, lessThan(firstSet.left)); );
expect(warmup.height, firstSet.height);
}); });
testWidgets('calls onTapCircle when set circle tapped', (tester) async { testWidgets('calls onTapCircle when set circle tapped', (tester) async {
var tappedIdx = -1; var tappedIdx = -1;
await tester.pumpWidget(_wrap(_tile(onTapCircle: (i) => tappedIdx = i))); await tester.pumpWidget(
_wrap(_tile(onTapCircle: (i) => tappedIdx = i)),
);
// Tap the first RepCircle (index 0)
await tester.tap(find.byType(RepCircle).first); await tester.tap(find.byType(RepCircle).first);
expect(tappedIdx, 0); expect(tappedIdx, 0);
}); });
testWidgets('calls onLongPressCircle on long press', (tester) async { testWidgets('calls onLongPressCircle on long press', (tester) async {
var idx = -1; var idx = -1;
await tester.pumpWidget(_wrap(_tile(onLongPressCircle: (i) => idx = i))); await tester.pumpWidget(
_wrap(_tile(onLongPressCircle: (i) => idx = i)),
);
await tester.longPress(find.byType(RepCircle).first); await tester.longPress(find.byType(RepCircle).first);
expect(idx, 0); expect(idx, 0);
}); });
testWidgets('calls onTapWarmup once, then shows it done', (tester) async { testWidgets('calls onTapWarmup when warmup circle tapped', (tester) async {
var calls = 0; var called = false;
await tester.pumpWidget(_wrap(_tile(onTapWarmup: () => calls++))); await tester.pumpWidget(_wrap(_tile(onTapWarmup: () => called = true)));
await tester.tap(find.bySemanticsLabel('Squat warmup')); // The warmup circle is the GestureDetector wrapping the AnimatedContainer.
expect(calls, 1); // Find the warmup area by finding the fitness_center icon.
await tester.tap(find.byIcon(Icons.fitness_center));
await tester.pumpWidget( expect(called, isTrue);
_wrap(_tile(warmupTapped: true, onTapWarmup: () => calls++)),
);
await tester.pumpAndSettle();
await tester.tap(find.bySemanticsLabel('Squat warmup'));
expect(calls, 1, reason: 'a done warmup is not tappable again');
}); });
testWidgets('warmup off keeps its slot: nothing moves', (tester) async { testWidgets('header is green when all sets succeeded', (tester) async {
await tester.pumpWidget(_wrap(_tile()));
final setsWith = tester.getRect(find.byType(RepCircle).first);
final tileWith = tester.getSize(find.byType(ExerciseTile));
await tester.pumpWidget(
_wrap(_tile(state: _state.copyWith(hasWarmup: false))),
);
expect(find.bySemanticsLabel('Squat warmup').hitTestable(), findsNothing);
expect(tester.getRect(find.byType(RepCircle).first), setsWith);
expect(tester.getSize(find.byType(ExerciseTile)), tileWith);
});
testWidgets('card fill: green on success, red on a failed set', (
tester,
) async {
await tester.pumpWidget(_wrap(_tile()));
final idle = _cardColor(tester);
await tester.pumpWidget(
_wrap(_tile(tapped: [true, true, true], doneReps: [5, 5, 5])),
);
final green = _cardColor(tester);
expect(green, isNot(idle));
await tester.pumpWidget(
_wrap(_tile(tapped: [true, true, true], doneReps: [5, 5, 3])),
);
expect(_cardColor(tester), isNot(green));
expect(_cardColor(tester), isNot(idle));
});
testWidgets('progress line shows streaks and the next step each way', (
tester,
) async {
await tester.pumpWidget(
_wrap(_tile(state: _state.copyWith(successStreak: 2, failStreak: 1))),
);
expect(find.text('2/3 → 22.5 kg'), findsOneWidget);
expect(find.text('1/2 → 17.5 kg'), findsOneWidget);
await tester.pumpWidget(
_wrap(_tile(state: _state.copyWith(mode: ProgressionMode.reps))),
);
expect(find.text('0/3 → 6 reps'), findsOneWidget);
expect(find.text('0/2 → 4 reps'), findsOneWidget);
});
testWidgets('mode chip names the mode', (tester) async {
await tester.pumpWidget(_wrap(_tile()));
expect(find.text('kg'), findsOneWidget);
await tester.pumpWidget(
_wrap(_tile(state: _state.copyWith(mode: ProgressionMode.reps))),
);
expect(find.text('reps'), findsOneWidget);
await tester.pumpWidget( await tester.pumpWidget(
_wrap( _wrap(
_tile( _tile(
state: _state.copyWith(mode: ProgressionMode.doubleProgression),
),
),
);
expect(find.text('6→12'), findsOneWidget);
});
testWidgets('mode chip opens the sheet and reports edits', (tester) async {
final edits = <ExerciseState>[];
await tester.pumpWidget(_wrap(_tile(onSettingsChanged: edits.add)));
await tester.tap(find.bySemanticsLabel('Squat progression settings'));
await tester.pumpAndSettle();
expect(find.byType(ExerciseSettingsSheet), findsOneWidget);
await tester.tap(find.text('Reps'));
await tester.pump();
expect(edits.single.mode, ProgressionMode.reps);
});
testWidgets('paused: no circles, same height, never filled', (
tester,
) async {
await tester.pumpWidget(_wrap(_tile()));
final size = tester.getSize(find.byType(ExerciseTile));
final idle = _cardColor(tester);
final until = pauseEnd(DateTime.now(), 14);
await tester.pumpWidget(
_wrap(
_tile(
state: _state.copyWith(pausedUntil: until),
tapped: [true, true, true], tapped: [true, true, true],
doneReps: [5, 5, 5],
), ),
), ),
); );
expect(find.byType(RepCircle), findsNothing); // Just verify it renders without errors
expect(find.bySemanticsLabel('Squat warmup'), findsNothing); expect(find.byType(ExerciseTile), findsOneWidget);
expect(
find.textContaining('back on ${formatShortDate(until)}'),
findsOneWidget,
);
expect(tester.getSize(find.byType(ExerciseTile)), size);
expect(_cardColor(tester), idle);
}); });
testWidgets('an expired pause shows the sets again', (tester) async { testWidgets('header is red when all sets tapped but some failed', (
final past = DateTime.now().subtract(const Duration(days: 1)); tester,
) async {
await tester.pumpWidget( await tester.pumpWidget(
_wrap(_tile(state: _state.copyWith(pausedUntil: past))), _wrap(
_tile(
tapped: [true, true, true],
doneReps: [5, 5, 3],
),
),
); );
expect(find.byType(RepCircle), findsNWidgets(3)); expect(find.byType(ExerciseTile), findsOneWidget);
});
testWidgets('success threshold stepper increments', (tester) async {
var newSuccess = 0;
await tester.pumpWidget(
_wrap(
_tile(
successThreshold: 2,
onThresholdChanged: (s, _) => newSuccess = s,
),
),
);
// The first add icon belongs to the success stepper
final addIcons = find.byIcon(Icons.add);
await tester.tap(addIcons.first);
expect(newSuccess, 3);
});
testWidgets('fail threshold stepper decrements', (tester) async {
var newFail = 0;
await tester.pumpWidget(
_wrap(
_tile(
failThreshold: 3,
onThresholdChanged: (_, f) => newFail = f,
),
),
);
// The last remove icon belongs to the fail stepper
final removeIcons = find.byIcon(Icons.remove);
await tester.tap(removeIcons.last);
expect(newFail, 2);
});
testWidgets('stepper min/max clamps are respected', (tester) async {
var callCount = 0;
// successThreshold = 1 (at min), tapping minus should not fire
await tester.pumpWidget(
_wrap(
_tile(
successThreshold: 1,
failThreshold: 5,
onThresholdChanged: (_, __) => callCount++,
),
),
);
// First minus (success, at min 1) → no callback
await tester.tap(find.byIcon(Icons.remove).first);
expect(callCount, 0);
// Last add (fail, at max 5) → no callback
await tester.tap(find.byIcon(Icons.add).last);
expect(callCount, 0);
}); });
}); });
} }