Let the gym mode PageView follow the gym state

This commit is contained in:
Roland Geider
2026-10-08 17:02:53 +02:00
parent 23c99ba2ba
commit edb48cfe49
5 changed files with 289 additions and 30 deletions

View File

@@ -23,6 +23,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:material_ui/material_ui.dart';
import 'package:wger/core/build_safety.dart';
import 'package:wger/core/consts.dart';
import 'package:wger/core/errors.dart';
import 'package:wger/core/network/network_provider.dart';
import 'package:wger/core/widgets/error.dart';
@@ -132,8 +133,8 @@ class _GymModeState extends ConsumerState<GymMode> {
final rest = gymState.restDurationFor(slotPage);
out.add(
rest != null
? TimerCountdownWidget(_controller, rest.inSeconds)
: TimerWidget(_controller),
? TimerCountdownWidget(_controller, slotPage.uuid)
: TimerWidget(_controller, slotPage.uuid),
);
}
}
@@ -146,8 +147,35 @@ 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
void _followCurrentPage(int page) {
final shown = _controller.hasClients ? _controller.page?.round() : null;
if (shown == null || shown == page) {
return;
}
final resumed = WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed;
if (resumed && (page - shown).abs() == 1) {
_controller.animateToPage(
page,
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,
);
} else {
_controller.jumpToPage(page);
}
}
@override
Widget build(BuildContext context) {
ref.listen(gymStateProvider.select((s) => s.currentPage), (_, page) {
// clear() also resets the page, but the summary has to stay visible
if (ref.read(gymStateProvider).isInitialized) {
_followCurrentPage(page);
}
});
return FutureBuilder<int>(
future: _initData,
builder: (context, snapshot) {

View File

@@ -19,7 +19,6 @@
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/core/formatting/formatting.dart';
import 'package:wger/core/snackbar.dart';
import 'package:wger/core/widgets/core.dart';
@@ -387,7 +386,8 @@ class _LogFormWidgetState extends ConsumerState<LogFormWidget> {
}
// A failed write is intentionally left to propagate to the global
// error handler; the success path below is then skipped.
// error handler; the success path below is then skipped. The
// PageView follows the page change from the gym state.
await ref.read(gymStateProvider.notifier).logCurrentSet();
if (!context.mounted) {
return;
@@ -399,10 +399,6 @@ class _LogFormWidgetState extends ConsumerState<LogFormWidget> {
center: true,
duration: const Duration(seconds: 2),
);
widget.controller.nextPage(
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,
);
},
child: Text(i18n.save),
),

View File

@@ -16,7 +16,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'dart:math';
import 'package:clock/clock.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
@@ -25,24 +27,26 @@ import 'package:wger/features/routines/providers/gym_state_notifier.dart';
import 'package:wger/features/routines/widgets/gym_mode/navigation.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
class TimerWidget extends StatefulWidget {
/// Rest that counts up, from the rest start in the gym state
class TimerWidget extends ConsumerStatefulWidget {
final PageController _controller;
const TimerWidget(this._controller);
/// The timer page this widget renders
final String slotUuid;
const TimerWidget(this._controller, this.slotUuid);
@override
_TimerWidgetState createState() => _TimerWidgetState();
}
class _TimerWidgetState extends State<TimerWidget> {
late DateTime _startTime;
class _TimerWidgetState extends ConsumerState<TimerWidget> {
final _maxSeconds = 600;
late Timer _uiTimer;
@override
void initState() {
super.initState();
_startTime = DateTime.now();
_uiTimer = Timer.periodic(const Duration(seconds: 1), (_) {
// ignore: no-empty-block, avoid-empty-setstate
@@ -60,7 +64,15 @@ class _TimerWidgetState extends State<TimerWidget> {
@override
Widget build(BuildContext context) {
final elapsed = DateTime.now().difference(_startTime).inSeconds;
final gymState = ref.watch(gymStateProvider);
final slotPage = gymState.getSlotPageByUUID(widget.slotUuid);
if (slotPage == null) {
return Container();
}
// The rest only runs while this is the current page
final startedAt = gymState.currentPage == slotPage.pageIndex ? gymState.restStartedAt : null;
final elapsed = startedAt == null ? 0 : clock.now().difference(startedAt).inSeconds;
final displaySeconds = elapsed > _maxSeconds ? _maxSeconds : elapsed;
final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: displaySeconds));
@@ -86,29 +98,28 @@ class _TimerWidgetState extends State<TimerWidget> {
}
}
/// Rest that counts down to the rest end in the gym state
class TimerCountdownWidget extends ConsumerStatefulWidget {
final PageController _controller;
final int _seconds;
const TimerCountdownWidget(
this._controller,
this._seconds,
);
/// The timer page this widget renders
final String slotUuid;
const TimerCountdownWidget(this._controller, this.slotUuid);
@override
_TimerCountdownWidgetState createState() => _TimerCountdownWidgetState();
}
class _TimerCountdownWidgetState extends ConsumerState<TimerCountdownWidget> {
late DateTime _endTime;
late Timer _uiTimer;
bool _hasNotified = false;
/// The rest end the alert was played for, so each rest alerts once
DateTime? _alertedFor;
@override
void initState() {
super.initState();
_endTime = DateTime.now().add(Duration(seconds: widget._seconds));
_uiTimer = Timer.periodic(const Duration(seconds: 1), (_) {
// ignore: no-empty-block, avoid-empty-setstate
@@ -126,13 +137,23 @@ class _TimerCountdownWidgetState extends ConsumerState<TimerCountdownWidget> {
@override
Widget build(BuildContext context) {
final remaining = _endTime.difference(DateTime.now());
final remainingSeconds = remaining.inSeconds <= 0 ? 0 : remaining.inSeconds;
final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: remainingSeconds));
final gymState = ref.watch(gymStateProvider);
final slotPage = gymState.getSlotPageByUUID(widget.slotUuid);
if (slotPage == null) {
return Container();
}
// When countdown finishes, notify ONCE, and respect settings
if (remainingSeconds == 0 && !_hasNotified) {
// The rest only runs while this is the current page, the neighbours show
// their full length
final endsAt = gymState.currentPage == slotPage.pageIndex ? gymState.restEndsAt : null;
final remaining = endsAt == null
? gymState.restDurationFor(slotPage)!
: endsAt.difference(clock.now());
final remainingSeconds = max(0, remaining.inSeconds);
final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: remainingSeconds));
if (endsAt != null && remainingSeconds == 0 && _alertedFor != endsAt) {
_alertedFor = endsAt;
if (gymState.alertOnCountdownEnd) {
// Strongest built-in haptic on both platforms (iOS: full vibration,
// Android: LONG_PRESS). heavyImpact maps to a weak tick on Android.
@@ -141,9 +162,6 @@ class _TimerCountdownWidgetState extends ConsumerState<TimerCountdownWidget> {
// Not that this only works on desktop platforms
SystemSound.play(SystemSoundType.alert);
}
setState(() {
_hasNotified = true;
});
}
return Column(

View File

@@ -506,6 +506,74 @@ void main() {
});
});
/// Opens gym mode and walks to the first log page (start, overview, log)
Future<riverpod.ProviderContainer> openOnFirstLogPage(WidgetTester tester) async {
await tester.pumpWidget(renderGymMode());
await tester.pumpAndSettle();
await tester.tap(find.byType(TextButton));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.chevron_right));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.chevron_right));
await tester.pumpAndSettle();
expect(find.byType(LogPage), findsOneWidget);
return riverpod.ProviderScope.containerOf(tester.element(find.byType(PageView)));
}
testWidgets(
'the PageView follows page changes made in the gym state',
(WidgetTester tester) async {
await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async {
final container = await openOnFirstLogPage(tester);
final notifier = container.read(gymStateProvider.notifier);
PageController controller() => tester.widget<PageView>(find.byType(PageView)).controller!;
// One page, e.g. skipping the rest from a notification
await tester.tap(find.byIcon(Icons.chevron_right));
await tester.pumpAndSettle();
expect(find.byType(TimerCountdownWidget), findsOneWidget);
notifier.skipRest();
await tester.pumpAndSettle();
expect(find.byType(LogPage), findsOneWidget);
expect(controller().page, notifier.state.currentPage);
// Several pages at once
final sessionPage = notifier.state.pages.firstWhere((p) => p.type == PageType.session);
notifier.setCurrentPage(sessionPage.pageIndex);
await tester.pumpAndSettle();
expect(find.byType(SessionPage), findsOneWidget);
expect(controller().page, sessionPage.pageIndex);
});
},
semanticsEnabled: false,
);
testWidgets(
'saving a set moves on to the pause exactly once',
(WidgetTester tester) async {
// The gym state advances and the PageView follows it, the save button
// must not add a page change of its own
when(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {});
await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async {
final container = await openOnFirstLogPage(tester);
final logPage = container.read(gymStateProvider).currentPage;
await tester.tap(find.byKey(const ValueKey('save-log-button')));
await tester.pumpAndSettle();
expect(find.byType(TimerCountdownWidget), findsOneWidget);
expect(container.read(gymStateProvider).currentPage, logPage + 1);
expect(
tester.widget<PageView>(find.byType(PageView)).controller!.page,
logPage + 1,
);
});
},
semanticsEnabled: false,
);
testWidgets(
'resuming an interrupted session reopens the page it was left on',
(WidgetTester tester) async {

View File

@@ -0,0 +1,149 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:clock/clock.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.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:wger/features/routines/providers/gym_state.dart';
import 'package:wger/features/routines/providers/gym_state_notifier.dart';
import 'package:wger/features/routines/widgets/gym_mode/timer.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/l10n/localizations_delegates.dart';
import '../../../../../test_data/routines.dart';
void main() {
final now = DateTime.utc(2025, 3, 29, 14, 33);
late ProviderContainer container;
late GymStateNotifier notifier;
setUp(() {
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
container = ProviderContainer.test();
notifier = container.read(gymStateProvider.notifier);
final routine = getTestRoutine();
notifier.initData(routine, routine.days.first.id!, 1);
});
// In the fixture the first slot rests 120 s, the second has no rest time
SlotPageEntry timerPage({required bool withRestTime}) => notifier.state.pages
.expand((p) => p.slotPages)
.firstWhere(
(p) => p.type == SlotPageType.timer && (p.setConfigData!.restTime != null) == withRestTime,
);
Future<void> pumpTimer(WidgetTester tester, Widget timer) async {
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
locale: const Locale('en'),
localizationsDelegates: appLocalizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: Builder(
builder: (context) {
final controller = PageController();
return PageView(controller: controller, children: [timer]);
},
),
),
),
),
);
}
group('TimerCountdownWidget', () {
testWidgets('counts down to the rest end of the gym state', (tester) async {
final page = timerPage(withRestTime: true);
notifier.state = notifier.state.copyWith(
currentPage: page.pageIndex,
restStartedAt: now.subtract(const Duration(seconds: 75)),
restEndsAt: now.add(const Duration(seconds: 45)),
);
await withClock(Clock.fixed(now), () async {
await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid));
});
expect(find.text('0:45'), findsOneWidget);
});
testWidgets('a timer page that is not current shows its full rest', (tester) async {
// The rest end in the state belongs to the current page only
final page = timerPage(withRestTime: true);
notifier.state = notifier.state.copyWith(
currentPage: page.pageIndex + 1,
restEndsAt: now.add(const Duration(seconds: 45)),
);
await withClock(Clock.fixed(now), () async {
await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid));
});
expect(find.text('2:00'), findsOneWidget);
});
testWidgets('alerts once when the rest is over', (tester) async {
final calls = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
calls.add(call.method);
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
final page = timerPage(withRestTime: true);
notifier.state = notifier.state.copyWith(currentPage: page.pageIndex, restEndsAt: now);
await withClock(Clock.fixed(now), () async {
await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid));
// The widget repaints every second and keeps seeing the end
await tester.pump(const Duration(seconds: 3));
});
expect(calls.where((m) => m == 'HapticFeedback.vibrate'), hasLength(1));
});
});
group('TimerWidget', () {
testWidgets('counts up from the rest start of the gym state', (tester) async {
final page = timerPage(withRestTime: false);
notifier.state = notifier.state.copyWith(
currentPage: page.pageIndex,
restStartedAt: now.subtract(const Duration(seconds: 30)),
);
await withClock(Clock.fixed(now), () async {
await pumpTimer(tester, TimerWidget(PageController(), page.uuid));
});
expect(find.text('0:30'), findsOneWidget);
});
});
}