Keep gym mode page in the gym state only

This is a follow-up to #1431. While the behaviour existed before, the
PR made it potentially visible.
This commit is contained in:
Roland Geider committed 2026-12-01 19:29:09 +01:00
1 parent 5155a034b0
commit 5cc8f9c76c
13 files changed
+286 -90

No files matched your search

@@ -492,6 +492,42 @@ class GymStateNotifier extends _$GymStateNotifier {
startNewEntry();
}
/// Shows [page]. Every navigation from the UI goes through here or the
/// helpers below: the gym state owns the current page and the PageView only
/// follows it. Reaching the summary ends the workout.
void goTo(int page) {
setCurrentPage(page);
final reachedSummary = state.pages.any(
(p) => p.type == PageType.workoutSummary && p.pageIndex == page,
);
if (reachedSummary) {
_logger.finer('Summary reached, clearing gym state');
clear();
}
}
/// Moves on like saving a set does, skipping slots whose sets are all done
void nextPage() => goTo(state.getNextPageIndex(state.currentPage));
/// Steps back in routine order, completed slots included
void previousPage() {
if (state.currentPage > 0) {
goTo(state.currentPage - 1);
}
}
/// A swipe gesture settled on [page]. Only called once the PageView came to
/// rest, so a swipe that was pulled back reports nothing. Forward swipes
/// follow the workout progression, backward ones the routine order.
void swipedTo(int page) {
if (page == state.currentPage) {
return;
}
final forward = state.isInitialized && page > state.currentPage;
goTo(forward ? state.getNextPageIndex(state.currentPage) : page);
}
/// Seeds the log form of the current page with a fresh entry, also to log
/// another set on a page that was already logged.
Future<void> startNewEntry() async {
@@ -48,7 +48,6 @@ class ExerciseOverview extends ConsumerWidget {
children: [
NavigationHeader(
exercise.getTranslation(Localizations.localeOf(context).languageCode).name,
_controller,
),
Expanded(
child: SingleChildScrollView(
@@ -57,7 +57,13 @@ class GymMode extends ConsumerStatefulWidget {
class _GymModeState extends ConsumerState<GymMode> {
late Future<int> _initData;
bool _initialPageJumped = false;
bool _isUserScroll = false;
/// Whether the running scroll was started by a finger, the only page change
/// the PageView reports back to the gym state
bool _isUserDrag = false;
/// The page the running finger scroll started on
int? _dragStartPage;
late final PageController _controller;
late final GymModeVisibleNotifier _visibility;
@@ -168,16 +174,18 @@ class _GymModeState extends ConsumerState<GymMode> {
return out;
}
/// Shows [page] when the state moved without the PageView, e.g. after a
/// notification action or a logged set
/// Shows [page] of the gym state. The state owns the current page, the
/// PageView never writes it back except for a settled swipe, see build().
/// Compares the exact position, so a page change during a running
/// animation retargets it instead of being taken as already shown.
void _followCurrentPage(int page) {
final shown = _controller.hasClients ? _controller.page?.round() : null;
final shown = _controller.hasClients ? _controller.page : null;
if (shown == null || shown == page) {
return;
}
final resumed = WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed;
if (resumed && (page - shown).abs() == 1) {
if (resumed && (page - shown).abs() <= 1) {
_controller.animateToPage(
page,
duration: DEFAULT_ANIMATION_DURATION,
@@ -188,6 +196,33 @@ class _GymModeState extends ConsumerState<GymMode> {
}
}
/// Reports a swipe that moved to another page. Any other scroll that came
/// to rest leaves the gym state alone and the PageView goes back to its
/// page: a swipe pulled back, or a touch that caught a running page
/// animation, e.g. a second quick tap on the footer's next button.
void _onScrollEnd() {
final wasDrag = _isUserDrag;
_isUserDrag = false;
final landed = _controller.page?.round();
if (wasDrag && landed != null && landed != _dragStartPage) {
ref.read(gymStateProvider.notifier).swipedTo(landed);
return;
}
// After the frame, the scroll that ended may still be replaced by
// another one, e.g. a jump that interrupted an animation
WidgetsBinding.instance.addPostFrameCallback((_) {
// Gym mode may have been closed in the meantime
if (!mounted || _isUserDrag) {
return;
}
final gymState = ref.read(gymStateProvider);
if (gymState.isInitialized) {
_followCurrentPage(gymState.currentPage);
}
});
}
@override
Widget build(BuildContext context) {
ref.listen(gymStateProvider.select((s) => s.currentPage), (_, page) {
@@ -212,6 +247,9 @@ class _GymModeState extends ConsumerState<GymMode> {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!_initialPageJumped && _controller.hasClients) {
_controller.jumpToPage(initialPage);
// The PageView doesn't report page changes, so seed the page's
// log draft and rest timer here
ref.read(gymStateProvider.notifier).setCurrentPage(initialPage);
setState(() => _initialPageJumped = true);
}
});
@@ -221,35 +259,26 @@ class _GymModeState extends ConsumerState<GymMode> {
..._getContent(state),
];
// No onPageChanged: it fires halfway through a swipe and for every
// page an animation passes. A swipe is reported once it came to
// rest, everything else moves the gym state and the PageView follows.
return NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification.depth == 0) {
if (notification is ScrollStartNotification) {
_isUserScroll = notification.dragDetails != null;
} else if (notification is ScrollEndNotification) {
_isUserScroll = false;
if (notification.depth != 0) {
return false;
}
if (notification is ScrollStartNotification) {
_isUserDrag = notification.dragDetails != null;
if (_isUserDrag) {
_dragStartPage = _controller.page?.round();
}
} else if (notification is ScrollEndNotification) {
_onScrollEnd();
}
return false;
},
child: PageView(
controller: _controller,
onPageChanged: (page) {
final gymState = ref.read(gymStateProvider);
// Only forward gestures follow workout progression. Backward
// swipes and explicit menu jumps keep every page reachable.
final destination =
gymState.isInitialized && _isUserScroll && page > gymState.currentPage
? gymState.getNextPageIndex(gymState.currentPage)
: page;
ref.read(gymStateProvider.notifier).setCurrentPage(destination);
// Check if the last page is reached
if (destination == children.length - 1) {
widget._logger.finer('Last page reached, clearing gym state');
ref.read(gymStateProvider.notifier).clear();
}
},
children: children,
),
);
@@ -92,7 +92,6 @@ class LogPage extends ConsumerWidget {
children: [
NavigationHeader(
setConfigData.exercise.getTranslation(languageCode).name,
_controller,
),
Container(
@@ -24,13 +24,11 @@ import 'package:wger/features/routines/widgets/gym_mode/elapsed_time.dart';
import 'package:wger/features/routines/widgets/gym_mode/workout_menu.dart';
class NavigationHeader extends StatelessWidget {
final PageController _controller;
final String _title;
final bool showEndWorkoutButton;
const NavigationHeader(
this._title,
this._controller, {
this._title, {
this.showEndWorkoutButton = true,
super.key,
});
@@ -60,7 +58,7 @@ class NavigationHeader extends StatelessWidget {
onPressed: () {
showDialog(
context: context,
builder: (ctx) => WorkoutMenuDialog(_controller),
builder: (ctx) => const WorkoutMenuDialog(),
);
},
),
@@ -92,10 +90,16 @@ class NavigationFooter extends ConsumerWidget {
IconButton(
icon: const Icon(Icons.chevron_left),
onPressed: () {
_controller.previousPage(
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,
);
// On the summary the workout is already cleared and the gym
// state has no pages left to move through
if (!ref.read(gymStateProvider).isInitialized) {
_controller.previousPage(
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,
);
return;
}
ref.read(gymStateProvider.notifier).previousPage();
},
)
else
@@ -108,7 +112,7 @@ class NavigationFooter extends ConsumerWidget {
child: GestureDetector(
onTap: () => showDialog(
context: context,
builder: (ctx) => WorkoutMenuDialog(_controller, initialIndex: 1),
builder: (ctx) => const WorkoutMenuDialog(initialIndex: 1),
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 15),
@@ -122,13 +126,9 @@ class NavigationFooter extends ConsumerWidget {
if (showNext)
IconButton(
icon: const Icon(Icons.chevron_right),
onPressed: () {
ref
.read(gymStateProvider.notifier)
.setCurrentPage(
gymState.getNextPageIndex(gymState.currentPage),
);
},
// Reads the state on tap, not the one this build saw: a second tap
// can arrive before the rebuild
onPressed: () => ref.read(gymStateProvider.notifier).nextPage(),
)
else
const SizedBox(width: 48),
@@ -20,7 +20,6 @@ import 'package:clock/clock.dart';
import 'package:collection/collection.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:material_ui/material_ui.dart';
import 'package:wger/core/consts.dart';
import 'package:wger/core/date.dart';
import 'package:wger/core/widgets/async_value_widget.dart';
import 'package:wger/features/routines/models/session.dart';
@@ -47,7 +46,7 @@ class _SessionPageState extends ConsumerState<SessionPage> {
return Column(
children: [
NavigationHeader(i18n.workoutSession, widget._controller),
NavigationHeader(i18n.workoutSession),
Expanded(
child: AsyncValueWidget<List<WorkoutSession>>(
value: ref.watch(workoutSessionProvider),
@@ -86,10 +85,7 @@ class _SessionPageState extends ConsumerState<SessionPage> {
padding: const EdgeInsets.symmetric(horizontal: 15),
child: SessionForm(
gymState.routine.id,
onSaved: () => widget._controller.nextPage(
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,
),
onSaved: () => ref.read(gymStateProvider.notifier).nextPage(),
session: session,
),
),
@@ -299,7 +299,6 @@ class StartPage extends ConsumerWidget {
children: [
NavigationHeader(
AppLocalizations.of(context).todaysWorkout,
_controller,
showEndWorkoutButton: false,
),
@@ -361,11 +360,9 @@ class StartPage extends ConsumerWidget {
FilledButton(
child: Text(AppLocalizations.of(context).start),
onPressed: () {
ref.read(gymStateProvider.notifier).startWorkout();
_controller.nextPage(
duration: const Duration(milliseconds: 200),
curve: Curves.bounceIn,
);
ref.read(gymStateProvider.notifier)
..startWorkout()
..nextPage();
},
),
NavigationFooter(_controller, showPrevious: false, showElapsedTime: false),
@@ -82,7 +82,6 @@ class _WorkoutSummaryState extends ConsumerState<WorkoutSummary> {
children: [
NavigationHeader(
AppLocalizations.of(context).workoutCompleted,
widget._controller,
showEndWorkoutButton: false,
),
Expanded(
@@ -83,7 +83,6 @@ class _TimerWidgetState extends ConsumerState<TimerWidget> {
children: [
NavigationHeader(
AppLocalizations.of(context).pause,
widget._controller,
),
Expanded(
child: Column(
@@ -196,7 +195,6 @@ class _TimerCountdownWidgetState extends ConsumerState<TimerCountdownWidget> {
children: [
NavigationHeader(
AppLocalizations.of(context).pause,
widget._controller,
),
Expanded(
child: Column(
@@ -19,17 +19,15 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:material_ui/material_ui.dart';
import 'package:wger/core/consts.dart';
import 'package:wger/features/exercises/widgets/autocompleter.dart';
import 'package:wger/features/routines/providers/gym_state.dart';
import 'package:wger/features/routines/providers/gym_state_notifier.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
class WorkoutMenu extends StatelessWidget {
final PageController _controller;
final int initialIndex;
const WorkoutMenu(this._controller, {this.initialIndex = 0, super.key});
const WorkoutMenu({this.initialIndex = 0, super.key});
@override
Widget build(BuildContext context) {
@@ -47,8 +45,8 @@ class WorkoutMenu extends StatelessWidget {
Flexible(
child: TabBarView(
children: [
NavigationTab(_controller),
ProgressionTab(_controller),
const NavigationTab(),
ProgressionTab(),
],
),
),
@@ -59,9 +57,7 @@ class WorkoutMenu extends StatelessWidget {
}
class NavigationTab extends ConsumerWidget {
final PageController _controller;
const NavigationTab(this._controller);
const NavigationTab();
@override
Widget build(BuildContext context, WidgetRef ref) {
@@ -90,11 +86,7 @@ class NavigationTab extends ConsumerWidget {
),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_controller.animateToPage(
page.pageIndex,
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,
);
ref.read(gymStateProvider.notifier).goTo(page.pageIndex);
Navigator.of(context).pop();
},
);
@@ -107,9 +99,8 @@ class NavigationTab extends ConsumerWidget {
class ProgressionTab extends ConsumerStatefulWidget {
final _logger = Logger('ProgressionTab');
final PageController _controller;
ProgressionTab(this._controller, {super.key});
ProgressionTab({super.key});
@override
ConsumerState<ProgressionTab> createState() => _ProgressionTabState();
@@ -259,11 +250,7 @@ class _ProgressionTabState extends ConsumerState<ProgressionTab> {
Expanded(child: Container()),
IconButton(
onPressed: () {
widget._controller.animateToPage(
page.pageIndex,
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,
);
ref.read(gymStateProvider.notifier).goTo(page.pageIndex);
Navigator.of(context).pop();
},
icon: const Icon(Icons.chevron_right),
@@ -402,12 +389,10 @@ class ExerciseAddWidget extends ConsumerWidget {
}
class WorkoutMenuDialog extends ConsumerWidget {
final PageController controller;
final bool showEndWorkoutButton;
final int initialIndex;
const WorkoutMenuDialog(
this.controller, {
const WorkoutMenuDialog({
super.key,
this.showEndWorkoutButton = true,
this.initialIndex = 0,
@@ -421,12 +406,8 @@ class WorkoutMenuDialog extends ConsumerWidget {
? TextButton(
child: Text(AppLocalizations.of(context).endWorkout),
onPressed: () {
controller.animateToPage(
gymState.totalPages,
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,
);
// The summary is the last page
ref.read(gymStateProvider.notifier).goTo(gymState.totalPages - 1);
Navigator.of(context).pop();
},
)
@@ -440,7 +421,7 @@ class WorkoutMenuDialog extends ConsumerWidget {
contentPadding: EdgeInsets.zero,
content: SizedBox(
width: double.maxFinite,
child: WorkoutMenu(controller, initialIndex: initialIndex),
child: WorkoutMenu(initialIndex: initialIndex),
),
actions: [
?endWorkoutButton,
@@ -1754,6 +1754,79 @@ void main() {
});
});
group('GymStateNotifier navigation', () {
// Same page structure as in the getNextLogPage group below:
// start(0), slot 1 (1-7), slot 2 (8-14), session(15), summary(16)
List<PageEntry> slots() => notifier.state.pages.where((p) => p.type == PageType.set).toList();
void markDone(PageEntry slot) {
for (final log in slot.slotPages.where((p) => p.type == SlotPageType.log)) {
notifier.markSlotPageAsDone(log.key, isDone: true);
}
}
setUp(() {
notifier.state = notifier.state.copyWith(isInitialized: true);
});
test('nextPage skips a slot whose sets are all done', () {
markDone(slots()[1]);
notifier.setCurrentPage(7);
notifier.nextPage();
expect(notifier.state.currentPage, 15);
});
test('previousPage steps back into a completed slot', () {
markDone(slots()[0]);
notifier.setCurrentPage(8);
notifier.previousPage();
expect(notifier.state.currentPage, 7);
});
test('reaching the summary ends the workout', () {
notifier.goTo(15);
expect(notifier.state.isInitialized, isTrue);
notifier.goTo(16);
expect(notifier.state.isInitialized, isFalse);
expect(notifier.state.pages, isEmpty);
});
test('a forward swipe follows the workout progression', () {
markDone(slots()[1]);
notifier.setCurrentPage(7);
notifier.swipedTo(8);
expect(notifier.state.currentPage, 15);
});
test('a backward swipe follows the routine order', () {
markDone(slots()[0]);
notifier.setCurrentPage(8);
notifier.swipedTo(7);
expect(notifier.state.currentPage, 7);
});
test('a swipe back onto the current page keeps the edited draft', () {
// A pulled-back swipe settles where it started; reseeding the page
// would drop what the user typed
notifier.setCurrentPage(2);
container.read(gymLogProvider.notifier).setRepetitions(99);
notifier.swipedTo(2);
expect(container.read(gymLogProvider)!.repetitions, 99);
});
});
group('GymModeState.getNextLogPage', () {
// Page structure of the test routine (exercise + timer pages enabled):
// start(0)
@@ -713,6 +713,95 @@ void main() {
expect(notifier.state.currentPage, c.pageIndex);
}, semanticsEnabled: false);
}
PageController pageController(WidgetTester tester) =>
tester.widget<PageView>(find.byType(PageView)).controller!;
testWidgets('two quick taps on the forward button move two pages', (tester) async {
final container = await openWorkout(tester);
final notifier = container.read(gymStateProvider.notifier);
final [a, _, _] = slots(notifier);
notifier.setCurrentPage(a.pageIndex);
await tester.pumpAndSettle();
// The second tap lands before the first one rebuilt the footer
await tester.tap(find.byIcon(Icons.chevron_right));
await tester.tap(find.byIcon(Icons.chevron_right));
await tester.pumpAndSettle();
expect(notifier.state.currentPage, a.slotPages[2].pageIndex);
expect(pageController(tester).page, notifier.state.currentPage);
}, semanticsEnabled: false);
testWidgets('a touch that catches the page animation keeps the new page', (tester) async {
final container = await openWorkout(tester);
final notifier = container.read(gymStateProvider.notifier);
final [a, _, _] = slots(notifier);
notifier.setCurrentPage(a.pageIndex);
await tester.pumpAndSettle();
// The PageView only animates to a neighbouring page in the foreground
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.tap(find.byIcon(Icons.chevron_right));
await tester.pump(const Duration(milliseconds: 20));
// The footer sits inside the PageView: a second quick tap catches the
// running animation as a drag that ends where it started
final gesture = await tester.startGesture(const Offset(700, 180));
await gesture.moveBy(const Offset(-30, 0));
await tester.pump(const Duration(milliseconds: 16));
await gesture.moveBy(const Offset(30, 0));
await gesture.up();
await tester.pumpAndSettle();
expect(notifier.state.currentPage, a.slotPages[1].pageIndex);
expect(pageController(tester).page, notifier.state.currentPage);
}, semanticsEnabled: false);
testWidgets('a swipe pulled back before release stays on its page', (tester) async {
final container = await openWorkout(tester);
final notifier = container.read(gymStateProvider.notifier);
final [a, b, _] = slots(notifier);
markDone(notifier, b);
final rest = a.slotPages.last.pageIndex;
notifier.setCurrentPage(rest);
await tester.pumpAndSettle();
// Past the middle, where a page change used to be reported, and back
final gesture = await tester.startGesture(const Offset(700, 180));
for (var step = 0; step < 6; step++) {
await gesture.moveBy(const Offset(-100, 0));
await tester.pump(const Duration(milliseconds: 16));
}
for (var step = 0; step < 6; step++) {
await gesture.moveBy(const Offset(100, 0));
await tester.pump(const Duration(milliseconds: 16));
}
await gesture.up();
await tester.pumpAndSettle();
expect(notifier.state.currentPage, rest);
expect(pageController(tester).page, rest);
}, semanticsEnabled: false);
testWidgets('a jump through the menu starts no rest on the way', (tester) async {
final container = await openWorkout(tester);
final notifier = container.read(gymStateProvider.notifier);
final [a, b, _] = slots(notifier);
notifier.setCurrentPage(a.pageIndex);
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.menu));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(ListTile, 'Side raises'));
await tester.pumpAndSettle();
expect(notifier.state.currentPage, b.pageIndex);
final rests = a.slotPages.where((p) => p.type == SlotPageType.timer);
expect(rests, isNotEmpty);
for (final rest in rests) {
expect(notifier.state.progressOf(rest.key).timerStartedAt, isNull, reason: rest.key);
}
}, semanticsEnabled: false);
});
testWidgets(
@@ -57,7 +57,7 @@ void main() {
localizationsDelegates: appLocalizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: ProgressionTab(PageController()),
body: ProgressionTab(),
),
),
);