From 9e24714cbd15b2925a0a4a48b117dd705e034d69 Mon Sep 17 00:00:00 2001 From: Diya Hituvalli Date: Wed, 19 Nov 2025 14:32:02 -0500 Subject: [PATCH 01/48] Add user preference in settings to hide diet plan if not used --- ios/Flutter/ephemeral/flutter_lldb_helper.py | 32 ++++++++++++++++++++ ios/Flutter/ephemeral/flutter_lldbinit | 5 +++ lib/providers/user.dart | 17 +++++++++++ lib/screens/dashboard.dart | 12 +++++--- lib/widgets/core/settings.dart | 15 +++++++++ 5 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 ios/Flutter/ephemeral/flutter_lldb_helper.py create mode 100644 ios/Flutter/ephemeral/flutter_lldbinit diff --git a/ios/Flutter/ephemeral/flutter_lldb_helper.py b/ios/Flutter/ephemeral/flutter_lldb_helper.py new file mode 100644 index 000000000..a88caf99d --- /dev/null +++ b/ios/Flutter/ephemeral/flutter_lldb_helper.py @@ -0,0 +1,32 @@ +# +# Generated file, do not edit. +# + +import lldb + +def handle_new_rx_page(frame: lldb.SBFrame, bp_loc, extra_args, intern_dict): + """Intercept NOTIFY_DEBUGGER_ABOUT_RX_PAGES and touch the pages.""" + base = frame.register["x0"].GetValueAsAddress() + page_len = frame.register["x1"].GetValueAsUnsigned() + + # Note: NOTIFY_DEBUGGER_ABOUT_RX_PAGES will check contents of the + # first page to see if handled it correctly. This makes diagnosing + # misconfiguration (e.g. missing breakpoint) easier. + data = bytearray(page_len) + data[0:8] = b'IHELPED!' + + error = lldb.SBError() + frame.GetThread().GetProcess().WriteMemory(base, data, error) + if not error.Success(): + print(f'Failed to write into {base}[+{page_len}]', error) + return + +def __lldb_init_module(debugger: lldb.SBDebugger, _): + target = debugger.GetDummyTarget() + # Caveat: must use BreakpointCreateByRegEx here and not + # BreakpointCreateByName. For some reasons callback function does not + # get carried over from dummy target for the later. + bp = target.BreakpointCreateByRegex("^NOTIFY_DEBUGGER_ABOUT_RX_PAGES$") + bp.SetScriptCallbackFunction('{}.handle_new_rx_page'.format(__name__)) + bp.SetAutoContinue(True) + print("-- LLDB integration loaded --") diff --git a/ios/Flutter/ephemeral/flutter_lldbinit b/ios/Flutter/ephemeral/flutter_lldbinit new file mode 100644 index 000000000..e3ba6fbed --- /dev/null +++ b/ios/Flutter/ephemeral/flutter_lldbinit @@ -0,0 +1,5 @@ +# +# Generated file, do not edit. +# + +command script import --relative-to-command-file flutter_lldb_helper.py diff --git a/lib/providers/user.dart b/lib/providers/user.dart index 3765bfe26..24c2446d7 100644 --- a/lib/providers/user.dart +++ b/lib/providers/user.dart @@ -29,10 +29,13 @@ class UserProvider with ChangeNotifier { ThemeMode themeMode = ThemeMode.system; final WgerBaseProvider baseProvider; late SharedPreferencesAsync prefs; + bool hideNutrition = false; UserProvider(this.baseProvider, {SharedPreferencesAsync? prefs}) { this.prefs = prefs ?? PreferenceHelper.asyncPref; _loadThemeMode(); + _loadHideNutrition(); + } static const PROFILE_URL = 'userprofile'; @@ -67,6 +70,13 @@ class UserProvider with ChangeNotifier { notifyListeners(); } + Future _loadHideNutrition() async { + final val = await prefs.getBool('hideNutrition'); + hideNutrition = val ?? false; + notifyListeners(); + } + + // Change mode on switch button click void setThemeMode(ThemeMode mode) async { themeMode = mode; @@ -81,6 +91,12 @@ class UserProvider with ChangeNotifier { notifyListeners(); } + void setHideNutrition(bool value) async { + hideNutrition = value; + await prefs.setBool('hideNutrition', value); + notifyListeners(); + } + /// Fetch the current user's profile Future fetchAndSetProfile() async { final userData = await baseProvider.fetch(baseProvider.makeUrl(PROFILE_URL)); @@ -91,6 +107,7 @@ class UserProvider with ChangeNotifier { } } + /// Save the user's profile to the server Future saveProfile() async { await baseProvider.post( diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index 06bae73e0..e3ad1b7d3 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/widgets/core/app_bar.dart'; import 'package:wger/widgets/dashboard/calendar.dart'; @@ -24,6 +25,7 @@ import 'package:wger/widgets/dashboard/widgets/measurements.dart'; import 'package:wger/widgets/dashboard/widgets/nutrition.dart'; import 'package:wger/widgets/dashboard/widgets/routines.dart'; import 'package:wger/widgets/dashboard/widgets/weight.dart'; +import 'package:wger/providers/user.dart'; class DashboardScreen extends StatelessWidget { const DashboardScreen(); @@ -32,20 +34,22 @@ class DashboardScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final user = Provider.of(context); + return Scaffold( appBar: MainAppBar(AppLocalizations.of(context).labelDashboard), - body: const SingleChildScrollView( - padding: EdgeInsets.all(10), + body: SingleChildScrollView( + padding: const EdgeInsets.all(10), child: Column( children: [ DashboardRoutineWidget(), - DashboardNutritionWidget(), DashboardWeightWidget(), DashboardMeasurementWidget(), DashboardCalendarWidget(), + if (!user.hideNutrition) DashboardNutritionWidget(), ], ), ), ); } -} +} \ No newline at end of file diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index e310ab035..d2e233da5 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -23,6 +23,9 @@ import 'package:wger/screens/configure_plates_screen.dart'; import 'package:wger/widgets/core/settings/exercise_cache.dart'; import 'package:wger/widgets/core/settings/ingredient_cache.dart'; import 'package:wger/widgets/core/settings/theme.dart'; +import 'package:provider/provider.dart'; +import 'package:wger/providers/user.dart'; + class SettingsPage extends StatelessWidget { static String routeName = '/SettingsPage'; @@ -44,6 +47,18 @@ class SettingsPage extends StatelessWidget { const SettingsIngredientCache(), ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)), const SettingsTheme(), + Consumer( + builder: (context, user, _) { + return SwitchListTile( + title: const Text('Show nutrition section on dashboard'), + value: !user.hideNutrition, + onChanged: (v) { + Provider.of(context, listen: false) + .setHideNutrition(!v); + }, + ); + }, + ), ListTile( title: Text(i18n.selectAvailablePlates), onTap: () { From c0d04cbb11094b87a1c71c53606d9455d6670920 Mon Sep 17 00:00:00 2001 From: Diya Hituvalli Date: Mon, 8 Dec 2025 13:57:42 -0500 Subject: [PATCH 02/48] allow the users to hide / show all widgets in the home screen --- lib/providers/user.dart | 50 ++++++++++++++++++++++++++-------- lib/screens/dashboard.dart | 15 ++++++---- lib/widgets/core/settings.dart | 40 ++++++++++++++++++++++----- 3 files changed, 81 insertions(+), 24 deletions(-) diff --git a/lib/providers/user.dart b/lib/providers/user.dart index 24c2446d7..27f7516d5 100644 --- a/lib/providers/user.dart +++ b/lib/providers/user.dart @@ -17,6 +17,7 @@ */ import 'dart:async'; +import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -29,13 +30,23 @@ class UserProvider with ChangeNotifier { ThemeMode themeMode = ThemeMode.system; final WgerBaseProvider baseProvider; late SharedPreferencesAsync prefs; - bool hideNutrition = false; + // bool hideNutrition = false; + + // New: visibility state for dashboard widgets + Map dashboardWidgetVisibility = { + 'routines': true, + 'weight': true, + 'measurements': true, + 'calendar': true, + 'nutrition': true, + }; + + static const String PREFS_DASHBOARD_VISIBILITY = 'dashboardWidgetVisibility'; UserProvider(this.baseProvider, {SharedPreferencesAsync? prefs}) { this.prefs = prefs ?? PreferenceHelper.asyncPref; _loadThemeMode(); - _loadHideNutrition(); - + _loadDashboardVisibility(); } static const PROFILE_URL = 'userprofile'; @@ -69,13 +80,34 @@ class UserProvider with ChangeNotifier { notifyListeners(); } + Future _loadDashboardVisibility() async { + final jsonString = await prefs.getString(PREFS_DASHBOARD_VISIBILITY); + + if (jsonString != null) { + try { + final decoded = jsonDecode(jsonString) as Map; + dashboardWidgetVisibility = + decoded.map((k, v) => MapEntry(k, v as bool)); + } catch (_) { + // If parsing fails, keep defaults + } + } - Future _loadHideNutrition() async { - final val = await prefs.getBool('hideNutrition'); - hideNutrition = val ?? false; notifyListeners(); } + bool isDashboardWidgetVisible(String key) { + return dashboardWidgetVisibility[key] ?? true; + } + + Future setDashboardWidgetVisible(String key, bool visible) async { + dashboardWidgetVisibility[key] = visible; + await prefs.setString( + PREFS_DASHBOARD_VISIBILITY, + jsonEncode(dashboardWidgetVisibility), + ); + notifyListeners(); + } // Change mode on switch button click void setThemeMode(ThemeMode mode) async { @@ -91,12 +123,6 @@ class UserProvider with ChangeNotifier { notifyListeners(); } - void setHideNutrition(bool value) async { - hideNutrition = value; - await prefs.setBool('hideNutrition', value); - notifyListeners(); - } - /// Fetch the current user's profile Future fetchAndSetProfile() async { final userData = await baseProvider.fetch(baseProvider.makeUrl(PROFILE_URL)); diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index e3ad1b7d3..802a91e69 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -42,11 +42,16 @@ class DashboardScreen extends StatelessWidget { padding: const EdgeInsets.all(10), child: Column( children: [ - DashboardRoutineWidget(), - DashboardWeightWidget(), - DashboardMeasurementWidget(), - DashboardCalendarWidget(), - if (!user.hideNutrition) DashboardNutritionWidget(), + if (user.isDashboardWidgetVisible('routines')) + const DashboardRoutineWidget(), + if (user.isDashboardWidgetVisible('weight')) + const DashboardWeightWidget(), + if (user.isDashboardWidgetVisible('measurements')) + const DashboardMeasurementWidget(), + if (user.isDashboardWidgetVisible('calendar')) + const DashboardCalendarWidget(), + if (user.isDashboardWidgetVisible('nutrition')) + const DashboardNutritionWidget(), ], ), ), diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index d2e233da5..a0f551362 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -49,13 +49,39 @@ class SettingsPage extends StatelessWidget { const SettingsTheme(), Consumer( builder: (context, user, _) { - return SwitchListTile( - title: const Text('Show nutrition section on dashboard'), - value: !user.hideNutrition, - onChanged: (v) { - Provider.of(context, listen: false) - .setHideNutrition(!v); - }, + return Column( + children: [ + SwitchListTile( + title: const Text('Show routines on dashboard'), + value: user.isDashboardWidgetVisible('routines'), + onChanged: (v) => + user.setDashboardWidgetVisible('routines', v), + ), + SwitchListTile( + title: const Text('Show weight on dashboard'), + value: user.isDashboardWidgetVisible('weight'), + onChanged: (v) => + user.setDashboardWidgetVisible('weight', v), + ), + SwitchListTile( + title: const Text('Show measurements on dashboard'), + value: user.isDashboardWidgetVisible('measurements'), + onChanged: (v) => + user.setDashboardWidgetVisible('measurements', v), + ), + SwitchListTile( + title: const Text('Show calendar on dashboard'), + value: user.isDashboardWidgetVisible('calendar'), + onChanged: (v) => + user.setDashboardWidgetVisible('calendar', v), + ), + SwitchListTile( + title: const Text('Show nutrition on dashboard'), + value: user.isDashboardWidgetVisible('nutrition'), + onChanged: (v) => + user.setDashboardWidgetVisible('nutrition', v), + ), + ], ); }, ), From fa00cad40615c72c45eb0e3b761173fe924c8cf5 Mon Sep 17 00:00:00 2001 From: Diya Hituvalli Date: Mon, 8 Dec 2025 15:02:51 -0500 Subject: [PATCH 03/48] added test stubs --- test/core/settings_test.dart | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index 474603c92..b29346827 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -51,6 +51,11 @@ void main() { when(mockUserProvider.themeMode).thenReturn(ThemeMode.system); when(mockExerciseProvider.exercises).thenReturn(getTestExercises()); when(mockNutritionProvider.ingredients).thenReturn([ingredient1, ingredient2]); + when(mockUserProvider.isDashboardWidgetVisible('routines')).thenReturn(true); + when(mockUserProvider.isDashboardWidgetVisible('weight')).thenReturn(true); + when(mockUserProvider.isDashboardWidgetVisible('measurements')).thenReturn(true); + when(mockUserProvider.isDashboardWidgetVisible('calendar')).thenReturn(true); + when(mockUserProvider.isDashboardWidgetVisible('nutrition')).thenReturn(true); }); Widget createSettingsScreen({locale = 'en'}) { @@ -100,18 +105,24 @@ void main() { group('Theme settings', () { test('Default theme is system', () async { when(mockSharedPreferences.getBool(PREFS_USER_DARK_THEME)).thenAnswer((_) async => null); + when(mockSharedPreferences.getString('dashboardWidgetVisibility')) + .thenAnswer((_) async => null); final userProvider = await UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); expect(userProvider.themeMode, ThemeMode.system); }); test('Loads light theme', () async { when(mockSharedPreferences.getBool(PREFS_USER_DARK_THEME)).thenAnswer((_) async => false); + when(mockSharedPreferences.getString('dashboardWidgetVisibility')) + .thenAnswer((_) async => null); final userProvider = await UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); expect(userProvider.themeMode, ThemeMode.light); }); test('Saves theme to prefs', () { when(mockSharedPreferences.getBool(any)).thenAnswer((_) async => null); + when(mockSharedPreferences.getString('dashboardWidgetVisibility')) + .thenAnswer((_) async => null); final userProvider = UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); userProvider.setThemeMode(ThemeMode.dark); verify(mockSharedPreferences.setBool(PREFS_USER_DARK_THEME, true)).called(1); From 0d0a5d8e028193582a07672a166efdbe53a987ba Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 18 Dec 2025 12:20:22 +0100 Subject: [PATCH 04/48] Bump dependencies --- pubspec.lock | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 12156b986..6b29145d1 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -125,18 +125,18 @@ packages: dependency: transitive description: name: camera_android_camerax - sha256: "1f1d1ff65223c59018d58bdac5211417c2af60bcb469c9d26f928dd412eb91cf" + sha256: "474d8355961658d43f1c976e2fa1ca715505bea1adbd56df34c581aaa70ec41f" url: "https://pub.dev" source: hosted - version: "0.6.24+3" + version: "0.6.26+2" camera_avfoundation: dependency: transitive description: name: camera_avfoundation - sha256: "035b90c1e33c2efad7548f402572078f6e514d4f82be0a315cd6c6af7e855aa8" + sha256: "0efb057a1fecdbf9b697272fbf79afbd47ac0e7bd69b4d900d3f304b31d93bad" url: "https://pub.dev" source: hosted - version: "0.9.22+6" + version: "0.9.22+7" camera_platform_interface: dependency: transitive description: @@ -149,10 +149,10 @@ packages: dependency: transitive description: name: camera_web - sha256: "77e53acb64d9de8917424eeb32b5c7c73572d1e00954bbf54a1e609d79a751a2" + sha256: "3bc7bb1657a0f29c34116453c5d5e528c23efcf5e75aac0a3387cf108040bf65" url: "https://pub.dev" source: hosted - version: "0.3.5+1" + version: "0.3.5+2" carousel_slider: dependency: "direct main" description: @@ -667,10 +667,10 @@ packages: dependency: transitive description: name: image - sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928" + sha256: "51555e36056541237b15b57afc31a0f53d4f9aefd9bd00873a6dc0090e54e332" url: "https://pub.dev" source: hosted - version: "4.5.4" + version: "4.6.0" image_picker: dependency: "direct main" description: @@ -699,10 +699,10 @@ packages: dependency: transitive description: name: image_picker_ios - sha256: "997d100ce1dda5b1ba4085194c5e36c9f8a1fb7987f6a36ab677a344cd2dc986" + sha256: "956c16a42c0c708f914021666ffcd8265dde36e673c9fa68c81f7d085d9774ad" url: "https://pub.dev" source: hosted - version: "0.8.13+2" + version: "0.8.13+3" image_picker_linux: dependency: transitive description: @@ -976,10 +976,10 @@ packages: dependency: transitive description: name: path_provider_foundation - sha256: "97390a0719146c7c3e71b6866c34f1cde92685933165c1c671984390d2aca776" + sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4" url: "https://pub.dev" source: hosted - version: "2.4.4" + version: "2.5.1" path_provider_linux: dependency: transitive description: @@ -1176,18 +1176,18 @@ packages: dependency: "direct main" description: name: shared_preferences - sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" url: "https://pub.dev" source: hosted - version: "2.5.3" + version: "2.5.4" shared_preferences_android: dependency: transitive description: name: shared_preferences_android - sha256: "46a46fd64659eff15f4638bbe19de43f9483f0e0bf024a9fb6b3582064bacc7b" + sha256: "83af5c682796c0f7719c2bbf74792d113e40ae97981b8f266fa84574573556bc" url: "https://pub.dev" source: hosted - version: "2.4.17" + version: "2.4.18" shared_preferences_foundation: dependency: transitive description: @@ -1333,10 +1333,10 @@ packages: dependency: transitive description: name: sqlparser - sha256: "54eea43e36dd3769274c3108625f9ea1a382f8d2ac8b16f3e4589d9bd9b0e16c" + sha256: "162435ede92bcc793ea939fdc0452eef0a73d11f8ed053b58a89792fba749da5" url: "https://pub.dev" source: hosted - version: "0.42.0" + version: "0.42.1" stack_trace: dependency: transitive description: @@ -1565,18 +1565,18 @@ packages: dependency: transitive description: name: video_player_android - sha256: "3f7ef3fb7b29f510e58f4d56b6ffbc3463b1071f2cf56e10f8d25f5b991ed85b" + sha256: "8587f7b1e1ad7a7b8f7a7e153bd6de8607168f865f0bd983ef1f92efd3f4a02c" url: "https://pub.dev" source: hosted - version: "2.8.21" + version: "2.9.0" video_player_avfoundation: dependency: transitive description: name: video_player_avfoundation - sha256: "6bced1739cf1f96f03058118adb8ac0dd6f96aa1a1a6e526424ab92fd2a6a77d" + sha256: e4d33b79a064498c6eb3a6a492b6a5012573d4943c28d566caf1a6c0840fe78d url: "https://pub.dev" source: hosted - version: "2.8.7" + version: "2.8.8" video_player_platform_interface: dependency: transitive description: @@ -1605,10 +1605,10 @@ packages: dependency: transitive description: name: watcher - sha256: "592ab6e2892f67760543fb712ff0177f4ec76c031f02f5b4ff8d3fc5eb9fb61a" + sha256: f52385d4f73589977c80797e60fe51014f7f2b957b5e9a62c3f6ada439889249 url: "https://pub.dev" source: hosted - version: "1.1.4" + version: "1.2.0" web: dependency: transitive description: From b806a6b51ce471eacf64a32c9fac68bc9cf33905 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 18 Dec 2025 19:25:12 +0000 Subject: [PATCH 05/48] Bump aws-sdk-s3 from 1.176.0 to 1.208.0 in /ios Bumps [aws-sdk-s3](https://github.com/aws/aws-sdk-ruby) from 1.176.0 to 1.208.0. - [Release notes](https://github.com/aws/aws-sdk-ruby/releases) - [Changelog](https://github.com/aws/aws-sdk-ruby/blob/version-3/gems/aws-sdk-s3/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-ruby/commits) --- updated-dependencies: - dependency-name: aws-sdk-s3 dependency-version: 1.208.0 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- ios/Gemfile.lock | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/ios/Gemfile.lock b/ios/Gemfile.lock index 5447a46b1..b05f5052b 100644 --- a/ios/Gemfile.lock +++ b/ios/Gemfile.lock @@ -9,24 +9,28 @@ GEM public_suffix (>= 2.0.2, < 7.0) artifactory (3.0.17) atomos (0.1.3) - aws-eventstream (1.3.0) - aws-partitions (1.1018.0) - aws-sdk-core (3.214.0) + aws-eventstream (1.4.0) + aws-partitions (1.1196.0) + aws-sdk-core (3.240.0) aws-eventstream (~> 1, >= 1.3.0) aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) + base64 + bigdecimal jmespath (~> 1, >= 1.6.1) - aws-sdk-kms (1.96.0) - aws-sdk-core (~> 3, >= 3.210.0) + logger + aws-sdk-kms (1.118.0) + aws-sdk-core (~> 3, >= 3.239.1) aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.176.0) - aws-sdk-core (~> 3, >= 3.210.0) + aws-sdk-s3 (1.208.0) + aws-sdk-core (~> 3, >= 3.234.0) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) - aws-sigv4 (1.10.1) + aws-sigv4 (1.12.1) aws-eventstream (~> 1, >= 1.0.2) babosa (1.0.4) base64 (0.2.0) + bigdecimal (4.0.1) claide (1.1.0) colored (1.2) colored2 (3.1.2) @@ -157,6 +161,7 @@ GEM json (2.9.0) jwt (2.9.3) base64 + logger (1.7.0) mini_magick (4.13.2) mini_mime (1.1.5) multi_json (1.15.0) From 5d39ae5088e6a7f12a042bebd01a1baedcd0b02a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 20 Dec 2025 00:31:18 +0100 Subject: [PATCH 06/48] Start adding support for trophies --- lib/main.dart | 101 ++++++---- lib/models/trophies/trophy.dart | 66 +++++++ lib/models/trophies/trophy.g.dart | 72 +++++++ .../trophies/user_trophy_progression.dart | 64 ++++++ .../trophies/user_trophy_progression.g.dart | 63 ++++++ lib/models/workouts/session.g.dart | 22 ++- lib/providers/trophies.dart | 51 +++++ lib/providers/trophies.g.dart | 103 ++++++++++ lib/providers/wger_base_riverpod.dart | 31 +++ test/trophies/models/trophy_test.dart | 72 +++++++ .../models/user_trophy_progression_test.dart | 97 ++++++++++ test/trophies/trophies_provider_test.dart | 117 +++++++++++ .../trophies_provider_test.mocks.dart | 183 ++++++++++++++++++ 13 files changed, 998 insertions(+), 44 deletions(-) create mode 100644 lib/models/trophies/trophy.dart create mode 100644 lib/models/trophies/trophy.g.dart create mode 100644 lib/models/trophies/user_trophy_progression.dart create mode 100644 lib/models/trophies/user_trophy_progression.g.dart create mode 100644 lib/providers/trophies.dart create mode 100644 lib/providers/trophies.g.dart create mode 100644 lib/providers/wger_base_riverpod.dart create mode 100644 test/trophies/models/trophy_test.dart create mode 100644 test/trophies/models/user_trophy_progression_test.dart create mode 100644 test/trophies/trophies_provider_test.dart create mode 100644 test/trophies/trophies_provider_test.mocks.dart diff --git a/lib/main.dart b/lib/main.dart index 477618816..b36666c85 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2025 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -35,6 +35,7 @@ import 'package:wger/providers/measurement.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/routines.dart'; import 'package:wger/providers/user.dart'; +import 'package:wger/providers/wger_base_riverpod.dart'; import 'package:wger/screens/add_exercise_screen.dart'; import 'package:wger/screens/auth_screen.dart'; import 'package:wger/screens/configure_plates_screen.dart'; @@ -129,7 +130,7 @@ void main() async { }; // Application - runApp(const riverpod.ProviderScope(child: MainApp())); + runApp(const MainApp()); } class MainApp extends StatelessWidget { @@ -217,46 +218,60 @@ class MainApp extends StatelessWidget { ), ], child: Consumer( - builder: (ctx, auth, _) => Consumer( - builder: (ctx, user, _) => MaterialApp( - title: 'wger', - navigatorKey: navigatorKey, - theme: wgerLightTheme, - darkTheme: wgerDarkTheme, - highContrastTheme: wgerLightThemeHc, - highContrastDarkTheme: wgerDarkThemeHc, - themeMode: user.themeMode, - home: _getHomeScreen(auth), - routes: { - DashboardScreen.routeName: (ctx) => const DashboardScreen(), - FormScreen.routeName: (ctx) => const FormScreen(), - GalleryScreen.routeName: (ctx) => const GalleryScreen(), - GymModeScreen.routeName: (ctx) => const GymModeScreen(), - HomeTabsScreen.routeName: (ctx) => HomeTabsScreen(), - MeasurementCategoriesScreen.routeName: (ctx) => const MeasurementCategoriesScreen(), - MeasurementEntriesScreen.routeName: (ctx) => const MeasurementEntriesScreen(), - NutritionalPlansScreen.routeName: (ctx) => const NutritionalPlansScreen(), - NutritionalDiaryScreen.routeName: (ctx) => const NutritionalDiaryScreen(), - NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), - LogMealsScreen.routeName: (ctx) => const LogMealsScreen(), - LogMealScreen.routeName: (ctx) => const LogMealScreen(), - WeightScreen.routeName: (ctx) => const WeightScreen(), - RoutineScreen.routeName: (ctx) => const RoutineScreen(), - RoutineEditScreen.routeName: (ctx) => const RoutineEditScreen(), - WorkoutLogsScreen.routeName: (ctx) => const WorkoutLogsScreen(), - RoutineListScreen.routeName: (ctx) => const RoutineListScreen(), - ExercisesScreen.routeName: (ctx) => const ExercisesScreen(), - ExerciseDetailScreen.routeName: (ctx) => const ExerciseDetailScreen(), - AddExerciseScreen.routeName: (ctx) => const AddExerciseScreen(), - AboutPage.routeName: (ctx) => const AboutPage(), - SettingsPage.routeName: (ctx) => const SettingsPage(), - LogOverviewPage.routeName: (ctx) => const LogOverviewPage(), - ConfigurePlatesScreen.routeName: (ctx) => const ConfigurePlatesScreen(), - }, - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - ), - ), + builder: (ctx, auth, _) { + final baseInstance = WgerBaseProvider(Provider.of(ctx, listen: false)); + + return Consumer( + builder: (ctx, user, _) => riverpod.ProviderScope( + overrides: [ + wgerBaseProvider.overrideWithValue(baseInstance), + ], + child: riverpod.Consumer( + builder: (rpCtx, ref, _) { + return MaterialApp( + title: 'wger', + navigatorKey: navigatorKey, + theme: wgerLightTheme, + darkTheme: wgerDarkTheme, + highContrastTheme: wgerLightThemeHc, + highContrastDarkTheme: wgerDarkThemeHc, + themeMode: user.themeMode, + home: _getHomeScreen(auth), + routes: { + DashboardScreen.routeName: (ctx) => const DashboardScreen(), + FormScreen.routeName: (ctx) => const FormScreen(), + GalleryScreen.routeName: (ctx) => const GalleryScreen(), + GymModeScreen.routeName: (ctx) => const GymModeScreen(), + HomeTabsScreen.routeName: (ctx) => HomeTabsScreen(), + MeasurementCategoriesScreen.routeName: (ctx) => + const MeasurementCategoriesScreen(), + MeasurementEntriesScreen.routeName: (ctx) => const MeasurementEntriesScreen(), + NutritionalPlansScreen.routeName: (ctx) => const NutritionalPlansScreen(), + NutritionalDiaryScreen.routeName: (ctx) => const NutritionalDiaryScreen(), + NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), + LogMealsScreen.routeName: (ctx) => const LogMealsScreen(), + LogMealScreen.routeName: (ctx) => const LogMealScreen(), + WeightScreen.routeName: (ctx) => const WeightScreen(), + RoutineScreen.routeName: (ctx) => const RoutineScreen(), + RoutineEditScreen.routeName: (ctx) => const RoutineEditScreen(), + WorkoutLogsScreen.routeName: (ctx) => const WorkoutLogsScreen(), + RoutineListScreen.routeName: (ctx) => const RoutineListScreen(), + ExercisesScreen.routeName: (ctx) => const ExercisesScreen(), + ExerciseDetailScreen.routeName: (ctx) => const ExerciseDetailScreen(), + AddExerciseScreen.routeName: (ctx) => const AddExerciseScreen(), + AboutPage.routeName: (ctx) => const AboutPage(), + SettingsPage.routeName: (ctx) => const SettingsPage(), + LogOverviewPage.routeName: (ctx) => const LogOverviewPage(), + ConfigurePlatesScreen.routeName: (ctx) => const ConfigurePlatesScreen(), + }, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + ); + }, + ), + ), + ); + }, ), ); } diff --git a/lib/models/trophies/trophy.dart b/lib/models/trophies/trophy.dart new file mode 100644 index 000000000..d58f5512a --- /dev/null +++ b/lib/models/trophies/trophy.dart @@ -0,0 +1,66 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:json_annotation/json_annotation.dart'; + +part 'trophy.g.dart'; + +enum TrophyType { time, volume, count, sequence, date, pr, other } + +@JsonSerializable() +class Trophy { + @JsonKey(required: true) + final int id; + + @JsonKey(required: true) + final String uuid; + + @JsonKey(required: true) + final String name; + + @JsonKey(required: true) + final String description; + + @JsonKey(required: true) + final String image; + + @JsonKey(required: true, name: 'trophy_type') + final TrophyType type; + + @JsonKey(required: true, name: 'is_hidden') + final bool isHidden; + + @JsonKey(required: true, name: 'is_progressive') + final bool isProgressive; + + Trophy({ + required this.id, + required this.uuid, + required this.name, + required this.description, + required this.image, + required this.type, + required this.isHidden, + required this.isProgressive, + }); + + // Boilerplate + factory Trophy.fromJson(Map json) => _$TrophyFromJson(json); + + Map toJson() => _$TrophyToJson(this); +} diff --git a/lib/models/trophies/trophy.g.dart b/lib/models/trophies/trophy.g.dart new file mode 100644 index 000000000..aba73ac10 --- /dev/null +++ b/lib/models/trophies/trophy.g.dart @@ -0,0 +1,72 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'trophy.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +Trophy _$TrophyFromJson(Map json) { + $checkKeys( + json, + requiredKeys: const [ + 'id', + 'uuid', + 'name', + 'description', + 'image', + 'trophy_type', + 'is_hidden', + 'is_progressive', + ], + ); + return Trophy( + id: (json['id'] as num).toInt(), + uuid: json['uuid'] as String, + name: json['name'] as String, + description: json['description'] as String, + image: json['image'] as String, + type: $enumDecode(_$TrophyTypeEnumMap, json['trophy_type']), + isHidden: json['is_hidden'] as bool, + isProgressive: json['is_progressive'] as bool, + ); +} + +Map _$TrophyToJson(Trophy instance) => { + 'id': instance.id, + 'uuid': instance.uuid, + 'name': instance.name, + 'description': instance.description, + 'image': instance.image, + 'trophy_type': _$TrophyTypeEnumMap[instance.type]!, + 'is_hidden': instance.isHidden, + 'is_progressive': instance.isProgressive, +}; + +const _$TrophyTypeEnumMap = { + TrophyType.time: 'time', + TrophyType.volume: 'volume', + TrophyType.count: 'count', + TrophyType.sequence: 'sequence', + TrophyType.date: 'date', + TrophyType.pr: 'pr', + TrophyType.other: 'other', +}; diff --git a/lib/models/trophies/user_trophy_progression.dart b/lib/models/trophies/user_trophy_progression.dart new file mode 100644 index 000000000..e84104a97 --- /dev/null +++ b/lib/models/trophies/user_trophy_progression.dart @@ -0,0 +1,64 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:json_annotation/json_annotation.dart'; +import 'package:wger/helpers/json.dart'; +import 'package:wger/models/trophies/trophy.dart'; + +part 'user_trophy_progression.g.dart'; + +@JsonSerializable() +class UserTrophyProgression { + @JsonKey(required: true) + final Trophy trophy; + + @JsonKey(required: true, name: 'is_earned') + final bool isEarned; + + @JsonKey(required: true, name: 'earned_at', fromJson: utcIso8601ToLocalDate) + final DateTime earnedAt; + + /// Progress towards earning the trophy (0-100%) + @JsonKey(required: true) + final num progress; + + @JsonKey(required: true, name: 'current_value', fromJson: stringToNumNull) + num? currentValue; + + @JsonKey(required: true, name: 'target_value', fromJson: stringToNumNull) + num? targetValue; + + @JsonKey(required: true, name: 'progress_display') + String? progressDisplay; + + UserTrophyProgression({ + required this.trophy, + required this.isEarned, + required this.earnedAt, + required this.progress, + required this.currentValue, + required this.targetValue, + this.progressDisplay, + }); + + // Boilerplate + factory UserTrophyProgression.fromJson(Map json) => + _$UserTrophyProgressionFromJson(json); + + Map toJson() => _$UserTrophyProgressionToJson(this); +} diff --git a/lib/models/trophies/user_trophy_progression.g.dart b/lib/models/trophies/user_trophy_progression.g.dart new file mode 100644 index 000000000..ac23b913f --- /dev/null +++ b/lib/models/trophies/user_trophy_progression.g.dart @@ -0,0 +1,63 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'user_trophy_progression.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +UserTrophyProgression _$UserTrophyProgressionFromJson( + Map json, +) { + $checkKeys( + json, + requiredKeys: const [ + 'trophy', + 'is_earned', + 'earned_at', + 'progress', + 'current_value', + 'target_value', + 'progress_display', + ], + ); + return UserTrophyProgression( + trophy: Trophy.fromJson(json['trophy'] as Map), + isEarned: json['is_earned'] as bool, + earnedAt: utcIso8601ToLocalDate(json['earned_at'] as String), + progress: json['progress'] as num, + currentValue: stringToNumNull(json['current_value'] as String?), + targetValue: stringToNumNull(json['target_value'] as String?), + progressDisplay: json['progress_display'] as String?, + ); +} + +Map _$UserTrophyProgressionToJson( + UserTrophyProgression instance, +) => { + 'trophy': instance.trophy, + 'is_earned': instance.isEarned, + 'earned_at': instance.earnedAt.toIso8601String(), + 'progress': instance.progress, + 'current_value': instance.currentValue, + 'target_value': instance.targetValue, + 'progress_display': instance.progressDisplay, +}; diff --git a/lib/models/workouts/session.g.dart b/lib/models/workouts/session.g.dart index ac78029df..9e3a52f74 100644 --- a/lib/models/workouts/session.g.dart +++ b/lib/models/workouts/session.g.dart @@ -1,3 +1,21 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + // GENERATED CODE - DO NOT MODIFY BY HAND part of 'session.dart'; @@ -23,7 +41,9 @@ WorkoutSession _$WorkoutSessionFromJson(Map json) { id: (json['id'] as num?)?.toInt(), dayId: (json['day'] as num?)?.toInt(), routineId: (json['routine'] as num?)?.toInt(), - impression: json['impression'] == null ? 2 : int.parse(json['impression'] as String), + impression: json['impression'] == null + ? DEFAULT_IMPRESSION + : int.parse(json['impression'] as String), notes: json['notes'] as String? ?? '', timeStart: stringToTimeNull(json['time_start'] as String?), timeEnd: stringToTimeNull(json['time_end'] as String?), diff --git a/lib/providers/trophies.dart b/lib/providers/trophies.dart new file mode 100644 index 000000000..77a3a1bc6 --- /dev/null +++ b/lib/providers/trophies.dart @@ -0,0 +1,51 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/helpers/consts.dart'; +import 'package:wger/models/trophies/trophy.dart'; +import 'package:wger/models/trophies/user_trophy_progression.dart'; +import 'package:wger/providers/wger_base_riverpod.dart'; + +part 'trophies.g.dart'; + +@riverpod +Future> trophies(Ref ref) async { + const trophiesPath = 'trophy'; + + final baseProvider = ref.read(wgerBaseProvider); + + final trophyData = await baseProvider.fetchPaginated( + baseProvider.makeUrl(trophiesPath, query: {'limit': API_MAX_PAGE_SIZE}), + ); + + return trophyData.map((e) => Trophy.fromJson(e)).toList(); +} + +@riverpod +Future> trophyProgression(Ref ref) async { + const userTrophyProgressionPath = 'trophy/progress'; + + final baseProvider = ref.read(wgerBaseProvider); + + final trophyData = await baseProvider.fetchPaginated( + baseProvider.makeUrl(userTrophyProgressionPath, query: {'limit': API_MAX_PAGE_SIZE}), + ); + + return trophyData.map((e) => UserTrophyProgression.fromJson(e)).toList(); +} diff --git a/lib/providers/trophies.g.dart b/lib/providers/trophies.g.dart new file mode 100644 index 000000000..b9b825d51 --- /dev/null +++ b/lib/providers/trophies.g.dart @@ -0,0 +1,103 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'trophies.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(trophies) +const trophiesProvider = TrophiesProvider._(); + +final class TrophiesProvider + extends $FunctionalProvider>, List, FutureOr>> + with $FutureModifier>, $FutureProvider> { + const TrophiesProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'trophiesProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$trophiesHash(); + + @$internal + @override + $FutureProviderElement> $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr> create(Ref ref) { + return trophies(ref); + } +} + +String _$trophiesHash() => r'44dd5e9a820f4e37599daac2a49a9358386758a8'; + +@ProviderFor(trophyProgression) +const trophyProgressionProvider = TrophyProgressionProvider._(); + +final class TrophyProgressionProvider + extends + $FunctionalProvider< + AsyncValue>, + List, + FutureOr> + > + with + $FutureModifier>, + $FutureProvider> { + const TrophyProgressionProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'trophyProgressionProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$trophyProgressionHash(); + + @$internal + @override + $FutureProviderElement> $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr> create(Ref ref) { + return trophyProgression(ref); + } +} + +String _$trophyProgressionHash() => r'444caf04f3d0a7845e840d452e4b4a822b59df9b'; diff --git a/lib/providers/wger_base_riverpod.dart b/lib/providers/wger_base_riverpod.dart new file mode 100644 index 000000000..0c73cbd23 --- /dev/null +++ b/lib/providers/wger_base_riverpod.dart @@ -0,0 +1,31 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 - 2025 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 . + */ + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/providers/auth.dart'; +import 'package:wger/providers/base_provider.dart'; + +/// Central provider that maps an existing [AuthProvider] (from the provider package) +/// to a [WgerBaseProvider] used by repositories. +/// +/// Usage: ref.watch(wgerBaseProvider(authProvider)) +final wgerBaseProvider = Provider((ref) { + throw UnimplementedError( + 'Override wgerBaseProvider in a ProviderScope with your existing WgerBaseProvider instance', + ); +}); diff --git a/test/trophies/models/trophy_test.dart b/test/trophies/models/trophy_test.dart new file mode 100644 index 000000000..3285b589b --- /dev/null +++ b/test/trophies/models/trophy_test.dart @@ -0,0 +1,72 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/models/trophies/trophy.dart'; + +void main() { + group('Trophy model', () { + final sampleJson = { + 'id': 1, + 'uuid': '550e8400-e29b-41d4-a716-446655440000', + 'name': 'First Steps', + 'description': 'Awarded for the first workout', + 'image': 'https://example.org/trophy.png', + 'trophy_type': 'count', + 'is_hidden': false, + 'is_progressive': true, + }; + + test('fromJson creates valid Trophy instance', () { + final trophy = Trophy.fromJson(sampleJson); + + expect(trophy.id, 1); + expect(trophy.uuid, '550e8400-e29b-41d4-a716-446655440000'); + expect(trophy.name, 'First Steps'); + expect(trophy.description, 'Awarded for the first workout'); + expect(trophy.image, 'https://example.org/trophy.png'); + expect(trophy.type, TrophyType.count); + expect(trophy.isHidden, isFalse); + expect(trophy.isProgressive, isTrue); + }); + + test('toJson returns expected map', () { + final trophy = Trophy( + id: 2, + uuid: '00000000-0000-0000-0000-000000000000', + name: 'Progressor', + description: 'Progressive trophy', + image: 'https://example.org/prog.png', + type: TrophyType.time, + isHidden: true, + isProgressive: false, + ); + + final json = trophy.toJson(); + + expect(json['id'], 2); + expect(json['uuid'], '00000000-0000-0000-0000-000000000000'); + expect(json['name'], 'Progressor'); + expect(json['description'], 'Progressive trophy'); + expect(json['image'], 'https://example.org/prog.png'); + expect(json['trophy_type'], 'time'); + expect(json['is_hidden'], true); + expect(json['is_progressive'], false); + }); + }); +} diff --git a/test/trophies/models/user_trophy_progression_test.dart b/test/trophies/models/user_trophy_progression_test.dart new file mode 100644 index 000000000..ccbb1d06a --- /dev/null +++ b/test/trophies/models/user_trophy_progression_test.dart @@ -0,0 +1,97 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/models/trophies/trophy.dart'; +import 'package:wger/models/trophies/user_trophy_progression.dart'; + +void main() { + group('UserTrophyProgression model', () { + final trophyJson = { + 'id': 1, + 'uuid': '550e8400-e29b-41d4-a716-446655440000', + 'name': 'First Steps', + 'description': 'Awarded for the first workout', + 'image': 'https://example.org/trophy.png', + 'trophy_type': 'count', + 'is_hidden': false, + 'is_progressive': true, + }; + + final trophyProgressionJson = { + 'trophy': trophyJson, + 'is_earned': false, + 'earned_at': '2020-01-02T15:04:05Z', + 'progress': 42.5, + 'current_value': '12.5', + 'target_value': '100', + 'progress_display': '12.5/100', + }; + + test('fromJson creates valid UserTrophyProgression instance', () { + final utp = UserTrophyProgression.fromJson(trophyProgressionJson); + + expect(utp.trophy.id, 1); + expect(utp.trophy.uuid, '550e8400-e29b-41d4-a716-446655440000'); + expect(utp.isEarned, isFalse); + + final expectedEarnedAt = DateTime.parse('2020-01-02T15:04:05Z').toLocal(); + expect(utp.earnedAt, expectedEarnedAt); + + expect(utp.progress, 42.5); + expect(utp.currentValue, 12.5); + expect(utp.targetValue, 100); + expect(utp.progressDisplay, '12.5/100'); + }); + + test('toJson returns expected map', () { + final trophy = Trophy( + id: 2, + uuid: '00000000-0000-0000-0000-000000000000', + name: 'Progressor', + description: 'Progressive trophy', + image: 'https://example.org/prog.png', + type: TrophyType.time, + isHidden: true, + isProgressive: false, + ); + + final earnedAt = DateTime.parse('2020-01-02T15:04:05Z').toLocal(); + + final utp = UserTrophyProgression( + trophy: trophy, + isEarned: true, + earnedAt: earnedAt, + progress: 75, + currentValue: 75, + targetValue: 100, + progressDisplay: '75/100', + ); + + final json = utp.toJson(); + + expect(json['trophy'], same(trophy)); + expect(json['is_earned'], true); + expect(json['earned_at'], earnedAt.toIso8601String()); + expect(json['progress'], 75); + expect(json['current_value'], 75); + expect(json['target_value'], 100); + expect(json['progress_display'], '75/100'); + }); + }); +} diff --git a/test/trophies/trophies_provider_test.dart b/test/trophies/trophies_provider_test.dart new file mode 100644 index 000000000..279afcc2b --- /dev/null +++ b/test/trophies/trophies_provider_test.dart @@ -0,0 +1,117 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/trophies.dart'; +import 'package:wger/providers/wger_base_riverpod.dart'; + +import 'trophies_provider_test.mocks.dart'; + +const trophyJson = { + 'id': 1, + 'uuid': '550e8400-e29b-41d4-a716-446655440000', + 'name': 'First Steps', + 'description': 'Awarded for the first workout', + 'image': 'https://example.org/trophy.png', + 'trophy_type': 'count', + 'is_hidden': false, + 'is_progressive': true, +}; + +@GenerateMocks([WgerBaseProvider]) +void main() { + group('Trophies providers', () { + test('trophies provider returns list of Trophy models', () async { + // Arrange + final mockBase = MockWgerBaseProvider(); + when(mockBase.fetchPaginated(any)).thenAnswer((_) async => [trophyJson]); + when( + mockBase.makeUrl( + any, + id: anyNamed('id'), + objectMethod: anyNamed('objectMethod'), + query: anyNamed('query'), + ), + ).thenReturn(Uri.parse('https://example.org/trophies')); + + final container = ProviderContainer.test( + overrides: [ + wgerBaseProvider.overrideWithValue(mockBase), + ], + ); + + // Act + final result = await container.read(trophiesProvider.future); + + // Assert + expect(result, isA()); + expect(result, hasLength(1)); + final trophy = result.first; + expect(trophy.id, 1); + expect(trophy.name, 'First Steps'); + expect(trophy.type.toString(), contains('count')); + }); + + test('trophyProgression provider returns list of UserTrophyProgression models', () async { + // Arrange + final progressionJson = { + 'trophy': trophyJson, + 'is_earned': true, + 'earned_at': '2020-01-02T15:04:05Z', + 'progress': 42.5, + 'current_value': '12.5', + 'target_value': '100', + 'progress_display': '12.5/100', + }; + + final mockBase = MockWgerBaseProvider(); + when(mockBase.fetchPaginated(any)).thenAnswer((_) async => [progressionJson]); + when( + mockBase.makeUrl( + any, + id: anyNamed('id'), + objectMethod: anyNamed('objectMethod'), + query: anyNamed('query'), + ), + ).thenReturn(Uri.parse('https://example.org/user_progressions')); + final container = ProviderContainer.test( + overrides: [ + wgerBaseProvider.overrideWithValue(mockBase), + ], + ); + + // Act + final result = await container.read(trophyProgressionProvider.future); + + // Assert + expect(result, isA()); + expect(result, hasLength(1)); + final p = result.first; + expect(p.isEarned, isTrue); + expect(p.progress, 42.5); + expect(p.currentValue, 12.5); + expect(p.progressDisplay, '12.5/100'); + + verify(mockBase.fetchPaginated(any)).called(1); + }); + }); +} diff --git a/test/trophies/trophies_provider_test.mocks.dart b/test/trophies/trophies_provider_test.mocks.dart new file mode 100644 index 000000000..dec2b6168 --- /dev/null +++ b/test/trophies/trophies_provider_test.mocks.dart @@ -0,0 +1,183 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/trophies/trophies_provider_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:http/http.dart' as _i3; +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/providers/auth.dart' as _i2; +import 'package:wger/providers/base_provider.dart' as _i4; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { + _FakeClient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeUri_2 extends _i1.SmartFake implements Uri { + _FakeUri_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { + _FakeResponse_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +/// A class which mocks [WgerBaseProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { + MockWgerBaseProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthProvider get auth => + (super.noSuchMethod( + Invocation.getter(#auth), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), + ) + as _i2.AuthProvider); + + @override + _i3.Client get client => + (super.noSuchMethod( + Invocation.getter(#client), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), + ) + as _i3.Client); + + @override + set auth(_i2.AuthProvider? value) => super.noSuchMethod( + Invocation.setter(#auth, value), + returnValueForMissingStub: null, + ); + + @override + set client(_i3.Client? value) => super.noSuchMethod( + Invocation.setter(#client, value), + returnValueForMissingStub: null, + ); + + @override + Map getDefaultHeaders({bool? includeAuth = false}) => + (super.noSuchMethod( + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), + returnValue: {}, + ) + as Map); + + @override + Uri makeUrl( + String? path, { + int? id, + String? objectMethod, + Map? query, + }) => + (super.noSuchMethod( + Invocation.method( + #makeUrl, + [path], + {#id: id, #objectMethod: objectMethod, #query: query}, + ), + returnValue: _FakeUri_2( + this, + Invocation.method( + #makeUrl, + [path], + {#id: id, #objectMethod: objectMethod, #query: query}, + ), + ), + ) + as Uri); + + @override + _i5.Future fetch(Uri? uri) => + (super.noSuchMethod( + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future> fetchPaginated(Uri? uri) => + (super.noSuchMethod( + Invocation.method(#fetchPaginated, [uri]), + returnValue: _i5.Future>.value([]), + ) + as _i5.Future>); + + @override + _i5.Future> post(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future> patch( + Map? data, + Uri? uri, + ) => + (super.noSuchMethod( + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => + (super.noSuchMethod( + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), + ), + ), + ) + as _i5.Future<_i3.Response>); +} From b9fd061d3359dee34e7d7a1b08532e97173dbd12 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 20 Dec 2025 02:06:08 +0100 Subject: [PATCH 07/48] Add dashboard widget and rework the provider --- lib/models/trophies/user_trophy.dart | 57 ++++++++++++++ lib/models/trophies/user_trophy.g.dart | 53 +++++++++++++ lib/providers/trophies.dart | 73 ++++++++++++----- lib/providers/trophies.g.dart | 86 ++++++++++++--------- lib/screens/dashboard.dart | 5 +- lib/widgets/dashboard/widgets/trophies.dart | 65 ++++++++++++++++ test/trophies/trophies_provider_test.dart | 25 ++---- 7 files changed, 290 insertions(+), 74 deletions(-) create mode 100644 lib/models/trophies/user_trophy.dart create mode 100644 lib/models/trophies/user_trophy.g.dart create mode 100644 lib/widgets/dashboard/widgets/trophies.dart diff --git a/lib/models/trophies/user_trophy.dart b/lib/models/trophies/user_trophy.dart new file mode 100644 index 000000000..81cb51e39 --- /dev/null +++ b/lib/models/trophies/user_trophy.dart @@ -0,0 +1,57 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:json_annotation/json_annotation.dart'; +import 'package:wger/helpers/json.dart'; + +import 'trophy.dart'; + +part 'user_trophy.g.dart'; + +/// A trophy awarded to a user for achieving a specific milestone. + +@JsonSerializable() +class UserTrophy { + @JsonKey(required: true) + final int id; + + @JsonKey(required: true) + final Trophy trophy; + + @JsonKey(required: true, name: 'earned_at', fromJson: utcIso8601ToLocalDate) + final DateTime earnedAt; + + @JsonKey(required: true) + final num progress; + + @JsonKey(required: true, name: 'is_notified') + final bool isNotified; + + UserTrophy({ + required this.id, + required this.trophy, + required this.earnedAt, + required this.progress, + required this.isNotified, + }); + + // Boilerplate + factory UserTrophy.fromJson(Map json) => _$UserTrophyFromJson(json); + + Map toJson() => _$UserTrophyToJson(this); +} diff --git a/lib/models/trophies/user_trophy.g.dart b/lib/models/trophies/user_trophy.g.dart new file mode 100644 index 000000000..62d85ac31 --- /dev/null +++ b/lib/models/trophies/user_trophy.g.dart @@ -0,0 +1,53 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'user_trophy.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +UserTrophy _$UserTrophyFromJson(Map json) { + $checkKeys( + json, + requiredKeys: const [ + 'id', + 'trophy', + 'earned_at', + 'progress', + 'is_notified', + ], + ); + return UserTrophy( + id: (json['id'] as num).toInt(), + trophy: Trophy.fromJson(json['trophy'] as Map), + earnedAt: utcIso8601ToLocalDate(json['earned_at'] as String), + progress: json['progress'] as num, + isNotified: json['is_notified'] as bool, + ); +} + +Map _$UserTrophyToJson(UserTrophy instance) => { + 'id': instance.id, + 'trophy': instance.trophy, + 'earned_at': instance.earnedAt.toIso8601String(), + 'progress': instance.progress, + 'is_notified': instance.isNotified, +}; diff --git a/lib/providers/trophies.dart b/lib/providers/trophies.dart index 77a3a1bc6..13ee1df7a 100644 --- a/lib/providers/trophies.dart +++ b/lib/providers/trophies.dart @@ -19,33 +19,70 @@ import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/models/trophies/trophy.dart'; +import 'package:wger/models/trophies/user_trophy.dart'; import 'package:wger/models/trophies/user_trophy_progression.dart'; import 'package:wger/providers/wger_base_riverpod.dart'; +import 'base_provider.dart'; + part 'trophies.g.dart'; -@riverpod -Future> trophies(Ref ref) async { - const trophiesPath = 'trophy'; +class TrophyRepository { + final WgerBaseProvider base; + final trophiesPath = 'trophy'; + final userTrophiesPath = 'user-trophy'; + final userTrophyProgressionPath = 'trophy/progress'; - final baseProvider = ref.read(wgerBaseProvider); + TrophyRepository(this.base); - final trophyData = await baseProvider.fetchPaginated( - baseProvider.makeUrl(trophiesPath, query: {'limit': API_MAX_PAGE_SIZE}), - ); + Future> fetchTrophies() async { + final url = base.makeUrl(trophiesPath, query: {'limit': API_MAX_PAGE_SIZE}); + final trophyData = await base.fetchPaginated(url); + return trophyData.map((e) => Trophy.fromJson(e)).toList(); + } - return trophyData.map((e) => Trophy.fromJson(e)).toList(); + Future> fetchUserTrophies() async { + final url = base.makeUrl(userTrophiesPath, query: {'limit': API_MAX_PAGE_SIZE}); + final trophyData = await base.fetchPaginated(url); + return trophyData.map((e) => UserTrophy.fromJson(e)).toList(); + } + + Future> fetchProgression() async { + final url = base.makeUrl(userTrophyProgressionPath, query: {'limit': API_MAX_PAGE_SIZE}); + final data = await base.fetchPaginated(url); + return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); + } + + List filterByType(List list, TrophyType type) => + list.where((t) => t.type == type).toList(); } @riverpod -Future> trophyProgression(Ref ref) async { - const userTrophyProgressionPath = 'trophy/progress'; - - final baseProvider = ref.read(wgerBaseProvider); - - final trophyData = await baseProvider.fetchPaginated( - baseProvider.makeUrl(userTrophyProgressionPath, query: {'limit': API_MAX_PAGE_SIZE}), - ); - - return trophyData.map((e) => UserTrophyProgression.fromJson(e)).toList(); +TrophyRepository trophyRepository(Ref ref) { + final base = ref.read(wgerBaseProvider); + return TrophyRepository(base); +} + +@Riverpod(keepAlive: true) +final class TrophyStateNotifier extends _$TrophyStateNotifier { + @override + void build() {} + + /// Fetch all available trophies + Future> fetchTrophies() async { + final repo = ref.read(trophyRepositoryProvider); + return repo.fetchTrophies(); + } + + /// Fetch trophies awarded to the user + Future> fetchUserTrophies() async { + final repo = ref.read(trophyRepositoryProvider); + return repo.fetchUserTrophies(); + } + + /// Fetch trophy progression for the user + Future> fetchTrophyProgression() async { + final repo = ref.read(trophyRepositoryProvider); + return repo.fetchProgression(); + } } diff --git a/lib/providers/trophies.g.dart b/lib/providers/trophies.g.dart index b9b825d51..04df81d63 100644 --- a/lib/providers/trophies.g.dart +++ b/lib/providers/trophies.g.dart @@ -27,77 +27,89 @@ part of 'trophies.dart'; // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint, type=warning -@ProviderFor(trophies) -const trophiesProvider = TrophiesProvider._(); +@ProviderFor(trophyRepository) +const trophyRepositoryProvider = TrophyRepositoryProvider._(); -final class TrophiesProvider - extends $FunctionalProvider>, List, FutureOr>> - with $FutureModifier>, $FutureProvider> { - const TrophiesProvider._() +final class TrophyRepositoryProvider + extends $FunctionalProvider + with $Provider { + const TrophyRepositoryProvider._() : super( from: null, argument: null, retry: null, - name: r'trophiesProvider', + name: r'trophyRepositoryProvider', isAutoDispose: true, dependencies: null, $allTransitiveDependencies: null, ); @override - String debugGetCreateSourceHash() => _$trophiesHash(); + String debugGetCreateSourceHash() => _$trophyRepositoryHash(); @$internal @override - $FutureProviderElement> $createElement( - $ProviderPointer pointer, - ) => $FutureProviderElement(pointer); + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); @override - FutureOr> create(Ref ref) { - return trophies(ref); + TrophyRepository create(Ref ref) { + return trophyRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(TrophyRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); } } -String _$trophiesHash() => r'44dd5e9a820f4e37599daac2a49a9358386758a8'; +String _$trophyRepositoryHash() => r'0699f0c0f7f324f3ba9b21420d9845a3e3096b61'; -@ProviderFor(trophyProgression) -const trophyProgressionProvider = TrophyProgressionProvider._(); +@ProviderFor(TrophyStateNotifier) +const trophyStateProvider = TrophyStateNotifierProvider._(); -final class TrophyProgressionProvider - extends - $FunctionalProvider< - AsyncValue>, - List, - FutureOr> - > - with - $FutureModifier>, - $FutureProvider> { - const TrophyProgressionProvider._() +final class TrophyStateNotifierProvider extends $NotifierProvider { + const TrophyStateNotifierProvider._() : super( from: null, argument: null, retry: null, - name: r'trophyProgressionProvider', - isAutoDispose: true, + name: r'trophyStateProvider', + isAutoDispose: false, dependencies: null, $allTransitiveDependencies: null, ); @override - String debugGetCreateSourceHash() => _$trophyProgressionHash(); + String debugGetCreateSourceHash() => _$trophyStateNotifierHash(); @$internal @override - $FutureProviderElement> $createElement( - $ProviderPointer pointer, - ) => $FutureProviderElement(pointer); + TrophyStateNotifier create() => TrophyStateNotifier(); - @override - FutureOr> create(Ref ref) { - return trophyProgression(ref); + /// {@macro riverpod.override_with_value} + Override overrideWithValue(void value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); } } -String _$trophyProgressionHash() => r'444caf04f3d0a7845e840d452e4b4a822b59df9b'; +String _$trophyStateNotifierHash() => r'e5c8f2a9477b8f7e5efe4e9ba23765f951627a9f'; + +abstract class _$TrophyStateNotifier extends $Notifier { + void build(); + @$mustCallSuper + @override + void runBuild() { + build(); + final ref = this.ref as $Ref; + final element = + ref.element as $ClassProviderElement, void, Object?, Object?>; + element.handleValue(ref, null); + } +} diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index 3be5a4b4c..0a7143086 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2020 - 2025 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 @@ -26,6 +26,8 @@ import 'package:wger/widgets/dashboard/widgets/nutrition.dart'; import 'package:wger/widgets/dashboard/widgets/routines.dart'; import 'package:wger/widgets/dashboard/widgets/weight.dart'; +import '../widgets/dashboard/widgets/trophies.dart'; + class DashboardScreen extends StatelessWidget { const DashboardScreen({super.key}); @@ -48,6 +50,7 @@ class DashboardScreen extends StatelessWidget { } final items = [ + const DashboardTrophiesWidget(), const DashboardRoutineWidget(), const DashboardNutritionWidget(), const DashboardWeightWidget(), diff --git a/lib/widgets/dashboard/widgets/trophies.dart b/lib/widgets/dashboard/widgets/trophies.dart new file mode 100644 index 000000000..9d2087c76 --- /dev/null +++ b/lib/widgets/dashboard/widgets/trophies.dart @@ -0,0 +1,65 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2020 - 2025 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/providers/trophies.dart'; +import 'package:wger/widgets/core/progress_indicator.dart'; + +class DashboardTrophiesWidget extends ConsumerWidget { + const DashboardTrophiesWidget(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final provider = ref.watch(trophyStateProvider.notifier); + + return FutureBuilder( + future: provider.fetchUserTrophies(), + builder: (context, asyncSnapshot) { + if (asyncSnapshot.connectionState != ConnectionState.done) { + return const Card( + child: BoxedProgressIndicator(), + ); + } + + return Card( + child: Column( + children: [ + ListTile( + title: Text( + 'Trophies', + style: Theme.of(context).textTheme.headlineSmall, + ), + ), + + ...(asyncSnapshot.data ?? []).map( + (userTrophy) => ListTile( + leading: CircleAvatar( + backgroundImage: NetworkImage(userTrophy.trophy.image), + ), + title: Text(userTrophy.trophy.name), + subtitle: Text(userTrophy.trophy.description, overflow: TextOverflow.ellipsis), + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/test/trophies/trophies_provider_test.dart b/test/trophies/trophies_provider_test.dart index 279afcc2b..5f159b940 100644 --- a/test/trophies/trophies_provider_test.dart +++ b/test/trophies/trophies_provider_test.dart @@ -16,13 +16,11 @@ * along with this program. If not, see . */ -import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/trophies.dart'; -import 'package:wger/providers/wger_base_riverpod.dart'; import 'trophies_provider_test.mocks.dart'; @@ -39,8 +37,8 @@ const trophyJson = { @GenerateMocks([WgerBaseProvider]) void main() { - group('Trophies providers', () { - test('trophies provider returns list of Trophy models', () async { + group('Trophy repository', () { + test('fetches list of trophies', () async { // Arrange final mockBase = MockWgerBaseProvider(); when(mockBase.fetchPaginated(any)).thenAnswer((_) async => [trophyJson]); @@ -52,15 +50,10 @@ void main() { query: anyNamed('query'), ), ).thenReturn(Uri.parse('https://example.org/trophies')); - - final container = ProviderContainer.test( - overrides: [ - wgerBaseProvider.overrideWithValue(mockBase), - ], - ); + final repository = TrophyRepository(mockBase); // Act - final result = await container.read(trophiesProvider.future); + final result = await repository.fetchTrophies(); // Assert expect(result, isA()); @@ -71,7 +64,7 @@ void main() { expect(trophy.type.toString(), contains('count')); }); - test('trophyProgression provider returns list of UserTrophyProgression models', () async { + test('fetches list of user trophy progression', () async { // Arrange final progressionJson = { 'trophy': trophyJson, @@ -93,14 +86,10 @@ void main() { query: anyNamed('query'), ), ).thenReturn(Uri.parse('https://example.org/user_progressions')); - final container = ProviderContainer.test( - overrides: [ - wgerBaseProvider.overrideWithValue(mockBase), - ], - ); + final repository = TrophyRepository(mockBase); // Act - final result = await container.read(trophyProgressionProvider.future); + final result = await repository.fetchProgression(); // Assert expect(result, isA()); From 9e4897f51605c518e066f2e504dc874608006adf Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 20 Dec 2025 17:55:22 +0100 Subject: [PATCH 08/48] Add smoke test for DashboardTrophiesWidget --- lib/widgets/dashboard/widgets/trophies.dart | 109 +++++++++++++--- test/test_data/trophies.dart | 76 +++++++++++ .../trophies_provider_test.dart | 0 .../trophies_provider_test.mocks.dart | 2 +- .../dashboard_trophies_widget_test.dart | 59 +++++++++ .../dashboard_trophies_widget_test.mocks.dart | 123 ++++++++++++++++++ .../gym_mode/log_page_test.mocks.dart | 18 --- 7 files changed, 349 insertions(+), 38 deletions(-) create mode 100644 test/test_data/trophies.dart rename test/trophies/{ => provider}/trophies_provider_test.dart (100%) rename test/trophies/{ => provider}/trophies_provider_test.mocks.dart (98%) create mode 100644 test/trophies/widgets/dashboard_trophies_widget_test.dart create mode 100644 test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart diff --git a/lib/widgets/dashboard/widgets/trophies.dart b/lib/widgets/dashboard/widgets/trophies.dart index 9d2087c76..c17df4aeb 100644 --- a/lib/widgets/dashboard/widgets/trophies.dart +++ b/lib/widgets/dashboard/widgets/trophies.dart @@ -18,6 +18,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/models/trophies/trophy.dart'; import 'package:wger/providers/trophies.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; @@ -32,30 +33,46 @@ class DashboardTrophiesWidget extends ConsumerWidget { future: provider.fetchUserTrophies(), builder: (context, asyncSnapshot) { if (asyncSnapshot.connectionState != ConnectionState.done) { - return const Card( - child: BoxedProgressIndicator(), - ); + return const Card(child: BoxedProgressIndicator()); } - return Card( - child: Column( - children: [ - ListTile( - title: Text( - 'Trophies', - style: Theme.of(context).textTheme.headlineSmall, - ), - ), + final userTrophies = asyncSnapshot.data ?? []; - ...(asyncSnapshot.data ?? []).map( - (userTrophy) => ListTile( - leading: CircleAvatar( - backgroundImage: NetworkImage(userTrophy.trophy.image), + return Card( + color: Colors.transparent, + shadowColor: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ListTile( + // title: Text( + // 'Trophies', + // style: Theme.of(context).textTheme.headlineSmall, + // ), + // ), + if (userTrophies.isEmpty) + Padding( + padding: const EdgeInsets.all(16.0), + child: Text('No trophies yet', style: Theme.of(context).textTheme.bodyMedium), + ) + else + SizedBox( + height: 140, + child: ListView.separated( + padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), + scrollDirection: Axis.horizontal, + itemCount: userTrophies.length, + separatorBuilder: (context, index) => const SizedBox(width: 12), + itemBuilder: (context, index) { + final userTrophy = userTrophies[index]; + + return SizedBox( + width: 220, + child: TrophyCard(trophy: userTrophy.trophy), + ); + }, ), - title: Text(userTrophy.trophy.name), - subtitle: Text(userTrophy.trophy.description, overflow: TextOverflow.ellipsis), ), - ), ], ), ); @@ -63,3 +80,57 @@ class DashboardTrophiesWidget extends ConsumerWidget { ); } } + +class TrophyCard extends StatelessWidget { + const TrophyCard({ + super.key, + required this.trophy, + }); + + final Trophy trophy; + + @override + Widget build(BuildContext context) { + return Card.filled( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 30, + backgroundImage: NetworkImage(trophy.image), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + trophy.name, + style: Theme.of(context).textTheme.titleMedium, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 4), + Text( + trophy.description, + style: Theme.of(context).textTheme.bodySmall, + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/test/test_data/trophies.dart b/test/test_data/trophies.dart new file mode 100644 index 000000000..698e26a56 --- /dev/null +++ b/test/test_data/trophies.dart @@ -0,0 +1,76 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:wger/models/trophies/trophy.dart'; +import 'package:wger/models/trophies/user_trophy.dart'; +import 'package:wger/models/trophies/user_trophy_progression.dart'; + +List getTestTrophies() { + return [ + Trophy( + id: 1, + uuid: '31a71d9a-bf26-4f18-b82f-afefe6f50df2', + name: 'New Year, New Me', + description: 'Work out on January 1st', + image: 'https://example.com/5362e55b-eaf1-4e34-9ef8-661538a3bdd9.png', + type: TrophyType.date, + isHidden: false, + isProgressive: false, + ), + Trophy( + id: 2, + uuid: 'b605b6a1-953d-41fb-87c9-a2f88b5f5907', + name: 'Unstoppable', + description: 'Maintain a 30-day workout streak', + image: 'https://example.com/b605b6a1-953d-41fb-87c9-a2f88b5f5907.png', + type: TrophyType.sequence, + isHidden: false, + isProgressive: true, + ), + ]; +} + +List getUserTrophyProgression() { + final trophies = getTestTrophies(); + + return [ + UserTrophyProgression( + trophy: trophies[0], + progress: 100, + isEarned: true, + earnedAt: DateTime(2025, 12, 20), + currentValue: null, + targetValue: null, + progressDisplay: null, + ), + ]; +} + +List getUserTrophies() { + final trophies = getTestTrophies(); + + return [ + UserTrophy( + id: 4, + earnedAt: DateTime(2025, 12, 20), + isNotified: true, + progress: 100, + trophy: trophies[0], + ), + ]; +} diff --git a/test/trophies/trophies_provider_test.dart b/test/trophies/provider/trophies_provider_test.dart similarity index 100% rename from test/trophies/trophies_provider_test.dart rename to test/trophies/provider/trophies_provider_test.dart diff --git a/test/trophies/trophies_provider_test.mocks.dart b/test/trophies/provider/trophies_provider_test.mocks.dart similarity index 98% rename from test/trophies/trophies_provider_test.mocks.dart rename to test/trophies/provider/trophies_provider_test.mocks.dart index dec2b6168..bebf3d1d2 100644 --- a/test/trophies/trophies_provider_test.mocks.dart +++ b/test/trophies/provider/trophies_provider_test.mocks.dart @@ -17,7 +17,7 @@ */ // Mocks generated by Mockito 5.4.6 from annotations -// in wger/test/trophies/trophies_provider_test.dart. +// in wger/test/trophies/provider/trophies_provider_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.dart b/test/trophies/widgets/dashboard_trophies_widget_test.dart new file mode 100644 index 000000000..7c6a92b46 --- /dev/null +++ b/test/trophies/widgets/dashboard_trophies_widget_test.dart @@ -0,0 +1,59 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:network_image_mock/network_image_mock.dart'; +import 'package:wger/providers/trophies.dart'; +import 'package:wger/widgets/dashboard/widgets/trophies.dart'; + +import '../../test_data/trophies.dart'; +import 'dashboard_trophies_widget_test.mocks.dart'; + +@GenerateMocks([TrophyRepository]) +void main() { + testWidgets('DashboardTrophiesWidget shows trophies', (WidgetTester tester) async { + // Arrange + final mockRepository = MockTrophyRepository(); + when(mockRepository.fetchUserTrophies()).thenAnswer((_) async => getUserTrophies()); + + // Act + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + trophyRepositoryProvider.overrideWithValue(mockRepository), + ], + child: const MaterialApp( + home: Scaffold( + body: DashboardTrophiesWidget(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Assert + // expect(find.text('Trophies'), findsOneWidget); + expect(find.text('New Year, New Me'), findsOneWidget); + }); + }); +} diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart b/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart new file mode 100644 index 000000000..1c8f3bdec --- /dev/null +++ b/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart @@ -0,0 +1,123 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/trophies/widgets/dashboard_trophies_widget_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:mockito/src/dummies.dart' as _i4; +import 'package:wger/models/trophies/trophy.dart' as _i6; +import 'package:wger/models/trophies/user_trophy.dart' as _i7; +import 'package:wger/models/trophies/user_trophy_progression.dart' as _i8; +import 'package:wger/providers/base_provider.dart' as _i2; +import 'package:wger/providers/trophies.dart' as _i3; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +/// A class which mocks [TrophyRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { + MockTrophyRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.WgerBaseProvider get base => + (super.noSuchMethod( + Invocation.getter(#base), + returnValue: _FakeWgerBaseProvider_0( + this, + Invocation.getter(#base), + ), + ) + as _i2.WgerBaseProvider); + + @override + String get trophiesPath => + (super.noSuchMethod( + Invocation.getter(#trophiesPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#trophiesPath), + ), + ) + as String); + + @override + String get userTrophiesPath => + (super.noSuchMethod( + Invocation.getter(#userTrophiesPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#userTrophiesPath), + ), + ) + as String); + + @override + String get userTrophyProgressionPath => + (super.noSuchMethod( + Invocation.getter(#userTrophyProgressionPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#userTrophyProgressionPath), + ), + ) + as String); + + @override + _i5.Future> fetchTrophies() => + (super.noSuchMethod( + Invocation.method(#fetchTrophies, []), + returnValue: _i5.Future>.value(<_i6.Trophy>[]), + ) + as _i5.Future>); + + @override + _i5.Future> fetchUserTrophies() => + (super.noSuchMethod( + Invocation.method(#fetchUserTrophies, []), + returnValue: _i5.Future>.value( + <_i7.UserTrophy>[], + ), + ) + as _i5.Future>); + + @override + _i5.Future> fetchProgression() => + (super.noSuchMethod( + Invocation.method(#fetchProgression, []), + returnValue: _i5.Future>.value( + <_i8.UserTrophyProgression>[], + ), + ) + as _i5.Future>); + + @override + List<_i6.Trophy> filterByType(List<_i6.Trophy>? list, _i6.TrophyType? type) => + (super.noSuchMethod( + Invocation.method(#filterByType, [list, type]), + returnValue: <_i6.Trophy>[], + ) + as List<_i6.Trophy>); +} diff --git a/test/widgets/routines/gym_mode/log_page_test.mocks.dart b/test/widgets/routines/gym_mode/log_page_test.mocks.dart index 500c61d8d..e9105c48d 100644 --- a/test/widgets/routines/gym_mode/log_page_test.mocks.dart +++ b/test/widgets/routines/gym_mode/log_page_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/widgets/routines/gym_mode/log_page_test.dart. // Do not manually edit this file. From 36a3e7ef4aaa9f2cb696a1b10ee9a93d16eaef85 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 20 Dec 2025 19:53:55 +0100 Subject: [PATCH 09/48] Add overview page for the trophies --- lib/helpers/json.dart | 10 +- lib/l10n/app_en.arb | 1 + lib/main.dart | 2 + lib/models/trophies/user_trophy.g.dart | 18 -- .../trophies/user_trophy_progression.dart | 7 +- .../trophies/user_trophy_progression.g.dart | 22 +- lib/models/workouts/session.g.dart | 18 -- lib/models/workouts/slot_data.g.dart | 18 -- lib/providers/gym_state.g.dart | 18 -- lib/providers/trophies.dart | 12 +- lib/providers/trophies.g.dart | 18 -- lib/screens/trophy_screen.dart | 39 ++++ lib/widgets/dashboard/widgets/trophies.dart | 78 +++---- lib/widgets/trophies/trophies_overview.dart | 198 ++++++++++++++++++ test/core/validators_test.mocks.dart | 29 +-- test/test_data/trophies.dart | 9 + .../trophies_provider_test.mocks.dart | 18 -- .../widgets/trophies_overview_test.dart | 60 ++++++ 18 files changed, 387 insertions(+), 188 deletions(-) create mode 100644 lib/screens/trophy_screen.dart create mode 100644 lib/widgets/trophies/trophies_overview.dart create mode 100644 test/trophies/widgets/trophies_overview_test.dart diff --git a/lib/helpers/json.dart b/lib/helpers/json.dart index 91cd0756c..b0202ca3e 100644 --- a/lib/helpers/json.dart +++ b/lib/helpers/json.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2025 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 @@ -70,6 +70,14 @@ DateTime utcIso8601ToLocalDate(String dateTime) { return DateTime.parse(dateTime).toLocal(); } +DateTime? utcIso8601ToLocalDateNull(String? dateTime) { + if (dateTime == null) { + return null; + } + + return utcIso8601ToLocalDate(dateTime); +} + /* * Converts a time to a date object. * Needed e.g. when the wger api only sends a time but no date information. diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 003c43ea6..335df77c9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -175,6 +175,7 @@ "slotEntryTypeTut": "Time under Tension", "slotEntryTypeIso": "Isometric hold", "slotEntryTypeJump": "Jump", + "trophies": "Trophies", "routines": "Routines", "newRoutine": "New routine", "noRoutines": "You have no routines", diff --git a/lib/main.dart b/lib/main.dart index b36666c85..0eda236e4 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -58,6 +58,7 @@ import 'package:wger/screens/routine_list_screen.dart'; import 'package:wger/screens/routine_logs_screen.dart'; import 'package:wger/screens/routine_screen.dart'; import 'package:wger/screens/splash_screen.dart'; +import 'package:wger/screens/trophy_screen.dart'; import 'package:wger/screens/update_app_screen.dart'; import 'package:wger/screens/weight_screen.dart'; import 'package:wger/theme/theme.dart'; @@ -263,6 +264,7 @@ class MainApp extends StatelessWidget { SettingsPage.routeName: (ctx) => const SettingsPage(), LogOverviewPage.routeName: (ctx) => const LogOverviewPage(), ConfigurePlatesScreen.routeName: (ctx) => const ConfigurePlatesScreen(), + TrophyScreen.routeName: (ctx) => const TrophyScreen(), }, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, diff --git a/lib/models/trophies/user_trophy.g.dart b/lib/models/trophies/user_trophy.g.dart index 62d85ac31..3208ebf67 100644 --- a/lib/models/trophies/user_trophy.g.dart +++ b/lib/models/trophies/user_trophy.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'user_trophy.dart'; diff --git a/lib/models/trophies/user_trophy_progression.dart b/lib/models/trophies/user_trophy_progression.dart index e84104a97..6cf115ba2 100644 --- a/lib/models/trophies/user_trophy_progression.dart +++ b/lib/models/trophies/user_trophy_progression.dart @@ -30,19 +30,22 @@ class UserTrophyProgression { @JsonKey(required: true, name: 'is_earned') final bool isEarned; - @JsonKey(required: true, name: 'earned_at', fromJson: utcIso8601ToLocalDate) - final DateTime earnedAt; + @JsonKey(required: true, name: 'earned_at', fromJson: utcIso8601ToLocalDateNull) + final DateTime? earnedAt; /// Progress towards earning the trophy (0-100%) @JsonKey(required: true) final num progress; + /// Current value towards the trophy goal (e.g., number of workouts completed) @JsonKey(required: true, name: 'current_value', fromJson: stringToNumNull) num? currentValue; + /// Target value to achieve the trophy goal @JsonKey(required: true, name: 'target_value', fromJson: stringToNumNull) num? targetValue; + /// Human-readable progress display (e.g., "3 / 10" or "51%") @JsonKey(required: true, name: 'progress_display') String? progressDisplay; diff --git a/lib/models/trophies/user_trophy_progression.g.dart b/lib/models/trophies/user_trophy_progression.g.dart index ac23b913f..de2a49e70 100644 --- a/lib/models/trophies/user_trophy_progression.g.dart +++ b/lib/models/trophies/user_trophy_progression.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'user_trophy_progression.dart'; @@ -42,7 +24,7 @@ UserTrophyProgression _$UserTrophyProgressionFromJson( return UserTrophyProgression( trophy: Trophy.fromJson(json['trophy'] as Map), isEarned: json['is_earned'] as bool, - earnedAt: utcIso8601ToLocalDate(json['earned_at'] as String), + earnedAt: utcIso8601ToLocalDateNull(json['earned_at'] as String?), progress: json['progress'] as num, currentValue: stringToNumNull(json['current_value'] as String?), targetValue: stringToNumNull(json['target_value'] as String?), @@ -55,7 +37,7 @@ Map _$UserTrophyProgressionToJson( ) => { 'trophy': instance.trophy, 'is_earned': instance.isEarned, - 'earned_at': instance.earnedAt.toIso8601String(), + 'earned_at': instance.earnedAt?.toIso8601String(), 'progress': instance.progress, 'current_value': instance.currentValue, 'target_value': instance.targetValue, diff --git a/lib/models/workouts/session.g.dart b/lib/models/workouts/session.g.dart index 9e3a52f74..bf061fa15 100644 --- a/lib/models/workouts/session.g.dart +++ b/lib/models/workouts/session.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'session.dart'; diff --git a/lib/models/workouts/slot_data.g.dart b/lib/models/workouts/slot_data.g.dart index 589b2b999..756717e67 100644 --- a/lib/models/workouts/slot_data.g.dart +++ b/lib/models/workouts/slot_data.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'slot_data.dart'; diff --git a/lib/providers/gym_state.g.dart b/lib/providers/gym_state.g.dart index 7596fa4be..1899e808d 100644 --- a/lib/providers/gym_state.g.dart +++ b/lib/providers/gym_state.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'gym_state.dart'; diff --git a/lib/providers/trophies.dart b/lib/providers/trophies.dart index 13ee1df7a..bf1104b2f 100644 --- a/lib/providers/trophies.dart +++ b/lib/providers/trophies.dart @@ -48,9 +48,15 @@ class TrophyRepository { } Future> fetchProgression() async { - final url = base.makeUrl(userTrophyProgressionPath, query: {'limit': API_MAX_PAGE_SIZE}); - final data = await base.fetchPaginated(url); - return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); + try { + final url = base.makeUrl(userTrophyProgressionPath); + final List data = await base.fetch(url); + return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); + } catch (e, stck) { + print('Error fetching trophy progression: $e'); + print(stck); + return []; + } } List filterByType(List list, TrophyType type) => diff --git a/lib/providers/trophies.g.dart b/lib/providers/trophies.g.dart index 04df81d63..81c827264 100644 --- a/lib/providers/trophies.g.dart +++ b/lib/providers/trophies.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'trophies.dart'; diff --git a/lib/screens/trophy_screen.dart b/lib/screens/trophy_screen.dart new file mode 100644 index 000000000..0cc3cc023 --- /dev/null +++ b/lib/screens/trophy_screen.dart @@ -0,0 +1,39 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/widgets/core/app_bar.dart'; +import 'package:wger/widgets/trophies/trophies_overview.dart'; + +class TrophyScreen extends StatelessWidget { + const TrophyScreen(); + + static const routeName = '/trophies'; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: EmptyAppBar(AppLocalizations.of(context).trophies), + body: WidescreenWrapper( + child: TrophiesOverview(), + ), + ); + } +} diff --git a/lib/widgets/dashboard/widgets/trophies.dart b/lib/widgets/dashboard/widgets/trophies.dart index c17df4aeb..b0e1bb623 100644 --- a/lib/widgets/dashboard/widgets/trophies.dart +++ b/lib/widgets/dashboard/widgets/trophies.dart @@ -20,6 +20,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/models/trophies/trophy.dart'; import 'package:wger/providers/trophies.dart'; +import 'package:wger/screens/trophy_screen.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; class DashboardTrophiesWidget extends ConsumerWidget { @@ -92,43 +93,48 @@ class TrophyCard extends StatelessWidget { @override Widget build(BuildContext context) { return Card.filled( - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - CircleAvatar( - radius: 30, - backgroundImage: NetworkImage(trophy.image), - ), - const SizedBox(width: 10), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - trophy.name, - style: Theme.of(context).textTheme.titleMedium, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - const SizedBox(height: 4), - Text( - trophy.description, - style: Theme.of(context).textTheme.bodySmall, - maxLines: 3, - overflow: TextOverflow.ellipsis, - ), - ], + child: InkWell( + onTap: () { + Navigator.of(context).pushNamed(TrophyScreen.routeName); + }, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 30, + backgroundImage: NetworkImage(trophy.image), ), - ), - ], - ), - ], + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + trophy.name, + style: Theme.of(context).textTheme.titleMedium, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 4), + Text( + trophy.description, + style: Theme.of(context).textTheme.bodySmall, + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + ], + ), ), ), ); diff --git a/lib/widgets/trophies/trophies_overview.dart b/lib/widgets/trophies/trophies_overview.dart new file mode 100644 index 000000000..2db561e72 --- /dev/null +++ b/lib/widgets/trophies/trophies_overview.dart @@ -0,0 +1,198 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/helpers/material.dart'; +import 'package:wger/models/trophies/user_trophy_progression.dart'; +import 'package:wger/providers/trophies.dart'; +import 'package:wger/widgets/core/progress_indicator.dart'; + +class TrophiesOverview extends ConsumerWidget { + const TrophiesOverview({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final notifier = ref.watch(trophyStateProvider.notifier); + + // Responsive grid: determine columns based on screen width + final width = MediaQuery.widthOf(context); + int crossAxisCount = 1; + if (width <= MATERIAL_XS_BREAKPOINT) { + crossAxisCount = 2; + } else if (width > MATERIAL_XS_BREAKPOINT && width < MATERIAL_MD_BREAKPOINT) { + crossAxisCount = 3; + } else if (width >= MATERIAL_MD_BREAKPOINT && width < MATERIAL_LG_BREAKPOINT) { + crossAxisCount = 4; + } else { + crossAxisCount = 5; + } + + return FutureBuilder>( + future: notifier.fetchTrophyProgression(), + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Card(child: BoxedProgressIndicator()); + } + + if (snapshot.hasError) { + return Center( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Text('Error loading trophies', style: Theme.of(context).textTheme.bodyLarge), + ), + ); + } + + final userTrophyProgression = snapshot.data ?? []; + + // If empty, show placeholder + if (userTrophyProgression.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Text( + 'No trophies yet', + style: Theme.of(context).textTheme.bodyLarge, + textAlign: TextAlign.center, + ), + ), + ); + } + + return RepaintBoundary( + child: GridView.builder( + padding: const EdgeInsets.all(12), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: crossAxisCount, + ), + key: const ValueKey('trophy-grid'), + itemCount: userTrophyProgression.length, + itemBuilder: (context, index) { + return _TrophyCardImage(userProgression: userTrophyProgression[index]); + }, + ), + ); + }, + ); + } +} + +class _TrophyCardImage extends StatelessWidget { + final UserTrophyProgression userProgression; + + const _TrophyCardImage({required this.userProgression}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + + final double progress = (userProgression.progress.toDouble() / 100.0).clamp(0.0, 1.0); + + return Opacity( + opacity: userProgression.isEarned ? 1.0 : 0.5, + child: Card( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide( + color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.18), + width: userProgression.isEarned ? 1.2 : 0, + ), + ), + child: Stack( + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 6.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox( + width: 70, + height: 70, + child: ClipOval( + child: Image.network( + userProgression.trophy.image, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) => Center( + child: Icon(Icons.emoji_events, size: 28, color: colorScheme.primary), + ), + ), + ), + ), + + Text( + userProgression.trophy.name, + style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600), + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 4), + + Text( + userProgression.trophy.description, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.textTheme.bodySmall?.color, + ), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 8), + + if (userProgression.trophy.isProgressive) + Tooltip( + message: 'Progress: ${userProgression.progressDisplay}', + child: SizedBox( + height: 6, + child: ClipRRect( + borderRadius: BorderRadius.circular(6), + child: LinearProgressIndicator( + value: progress, + minHeight: 6, + valueColor: AlwaysStoppedAnimation(colorScheme.primary), + backgroundColor: colorScheme.onSurface.withAlpha((0.06 * 255).round()), + ), + ), + ), + ), + ], + ), + ), + if (userProgression.isEarned) + Positioned( + top: 6, + right: 6, + child: Container( + width: 28, + height: 28, + decoration: const BoxDecoration( + color: Colors.green, + shape: BoxShape.circle, + ), + child: const Icon(Icons.check, size: 16, color: Colors.white), + ), + ), + ], + ), + ), + ); + } +} diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 8791d455c..389f1556e 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/core/validators_test.dart. // Do not manually edit this file. @@ -785,6 +767,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get trophies => + (super.noSuchMethod( + Invocation.getter(#trophies), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#trophies), + ), + ) + as String); + @override String get routines => (super.noSuchMethod( diff --git a/test/test_data/trophies.dart b/test/test_data/trophies.dart index 698e26a56..8fc13d286 100644 --- a/test/test_data/trophies.dart +++ b/test/test_data/trophies.dart @@ -58,6 +58,15 @@ List getUserTrophyProgression() { targetValue: null, progressDisplay: null, ), + UserTrophyProgression( + trophy: trophies[1], + progress: 40, + isEarned: false, + earnedAt: null, + currentValue: 12, + targetValue: 30, + progressDisplay: '12 / 30', + ), ]; } diff --git a/test/trophies/provider/trophies_provider_test.mocks.dart b/test/trophies/provider/trophies_provider_test.mocks.dart index bebf3d1d2..9830acb46 100644 --- a/test/trophies/provider/trophies_provider_test.mocks.dart +++ b/test/trophies/provider/trophies_provider_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/trophies/provider/trophies_provider_test.dart. // Do not manually edit this file. diff --git a/test/trophies/widgets/trophies_overview_test.dart b/test/trophies/widgets/trophies_overview_test.dart new file mode 100644 index 000000000..7d7d65aa2 --- /dev/null +++ b/test/trophies/widgets/trophies_overview_test.dart @@ -0,0 +1,60 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:network_image_mock/network_image_mock.dart'; +import 'package:wger/providers/trophies.dart'; +import 'package:wger/widgets/trophies/trophies_overview.dart'; + +import '../../test_data/trophies.dart'; +import 'dashboard_trophies_widget_test.mocks.dart'; + +@GenerateMocks([TrophyRepository]) +void main() { + testWidgets('TrophiesOverview shows trophies', (WidgetTester tester) async { + // Arrange + final mockRepository = MockTrophyRepository(); + when(mockRepository.fetchProgression()).thenAnswer((_) async => getUserTrophyProgression()); + + // Act + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + trophyRepositoryProvider.overrideWithValue(mockRepository), + ], + child: const MaterialApp( + home: Scaffold(body: TrophiesOverview()), + ), + ), + ); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('New Year, New Me'), findsOneWidget); + expect(find.text('Work out on January 1st'), findsOneWidget); + + expect(find.text('Unstoppable'), findsOneWidget); + expect(find.text('Maintain a 30-day workout streak'), findsOneWidget); + }); + }); +} From 0774571fbc87c116ca19f59345f5eb1a68bcbd7a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 20 Dec 2025 21:34:33 +0100 Subject: [PATCH 10/48] Fix test --- lib/providers/trophies.dart | 12 +++--------- test/trophies/provider/trophies_provider_test.dart | 13 +++---------- 2 files changed, 6 insertions(+), 19 deletions(-) diff --git a/lib/providers/trophies.dart b/lib/providers/trophies.dart index bf1104b2f..1da6eea39 100644 --- a/lib/providers/trophies.dart +++ b/lib/providers/trophies.dart @@ -48,15 +48,9 @@ class TrophyRepository { } Future> fetchProgression() async { - try { - final url = base.makeUrl(userTrophyProgressionPath); - final List data = await base.fetch(url); - return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); - } catch (e, stck) { - print('Error fetching trophy progression: $e'); - print(stck); - return []; - } + final url = base.makeUrl(userTrophyProgressionPath); + final List data = await base.fetch(url); + return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); } List filterByType(List list, TrophyType type) => diff --git a/test/trophies/provider/trophies_provider_test.dart b/test/trophies/provider/trophies_provider_test.dart index 5f159b940..456a806a5 100644 --- a/test/trophies/provider/trophies_provider_test.dart +++ b/test/trophies/provider/trophies_provider_test.dart @@ -77,15 +77,8 @@ void main() { }; final mockBase = MockWgerBaseProvider(); - when(mockBase.fetchPaginated(any)).thenAnswer((_) async => [progressionJson]); - when( - mockBase.makeUrl( - any, - id: anyNamed('id'), - objectMethod: anyNamed('objectMethod'), - query: anyNamed('query'), - ), - ).thenReturn(Uri.parse('https://example.org/user_progressions')); + when(mockBase.fetch(any)).thenAnswer((_) async => [progressionJson]); + when(mockBase.makeUrl(any)).thenReturn(Uri.parse('https://example.org/user_progressions')); final repository = TrophyRepository(mockBase); // Act @@ -100,7 +93,7 @@ void main() { expect(p.currentValue, 12.5); expect(p.progressDisplay, '12.5/100'); - verify(mockBase.fetchPaginated(any)).called(1); + verify(mockBase.fetch(any)).called(1); }); }); } From 536f18805b3abaa9cd4067d33bff805706d6aef7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 21 Dec 2025 20:40:20 +0100 Subject: [PATCH 11/48] Load context data for PR trophies This allows us to show for which sets the user achieved new PRs --- lib/l10n/app_en.arb | 1 + lib/models/trophies/user_trophy.dart | 5 + lib/models/trophies/user_trophy.g.dart | 5 + .../trophies/user_trophy_context_data.dart | 75 ++++++++++ .../trophies/user_trophy_context_data.g.dart | 50 +++++++ lib/providers/gym_state.dart | 2 +- lib/providers/gym_state.g.dart | 2 +- lib/providers/trophies.dart | 65 +++++++-- lib/providers/trophies.g.dart | 2 +- lib/widgets/routines/gym_mode/summary.dart | 43 ++++-- .../logs/exercises_expansion_card.dart | 22 ++- test/core/validators_test.mocks.dart | 11 ++ .../dashboard_trophies_widget_test.dart | 5 +- .../dashboard_trophies_widget_test.mocks.dart | 16 ++- .../widgets/trophies_overview_test.dart | 4 +- .../widgets/trophies_overview_test.mocks.dart | 131 ++++++++++++++++++ 16 files changed, 397 insertions(+), 42 deletions(-) create mode 100644 lib/models/trophies/user_trophy_context_data.dart create mode 100644 lib/models/trophies/user_trophy_context_data.g.dart create mode 100644 test/trophies/widgets/trophies_overview_test.mocks.dart diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 335df77c9..efce357f9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -263,6 +263,7 @@ }, "selectExercises": "If you want to do a superset you can search for several exercises, they will be grouped together", "@selectExercises": {}, + "personalRecords": "Personal records", "gymMode": "Gym mode", "@gymMode": { "description": "Label when starting the gym mode" diff --git a/lib/models/trophies/user_trophy.dart b/lib/models/trophies/user_trophy.dart index 81cb51e39..8e1e7a816 100644 --- a/lib/models/trophies/user_trophy.dart +++ b/lib/models/trophies/user_trophy.dart @@ -20,6 +20,7 @@ import 'package:json_annotation/json_annotation.dart'; import 'package:wger/helpers/json.dart'; import 'trophy.dart'; +import 'user_trophy_context_data.dart'; part 'user_trophy.g.dart'; @@ -42,12 +43,16 @@ class UserTrophy { @JsonKey(required: true, name: 'is_notified') final bool isNotified; + @JsonKey(required: true, name: 'context_data') + final ContextData? contextData; + UserTrophy({ required this.id, required this.trophy, required this.earnedAt, required this.progress, required this.isNotified, + this.contextData, }); // Boilerplate diff --git a/lib/models/trophies/user_trophy.g.dart b/lib/models/trophies/user_trophy.g.dart index 3208ebf67..97d9da440 100644 --- a/lib/models/trophies/user_trophy.g.dart +++ b/lib/models/trophies/user_trophy.g.dart @@ -15,6 +15,7 @@ UserTrophy _$UserTrophyFromJson(Map json) { 'earned_at', 'progress', 'is_notified', + 'context_data', ], ); return UserTrophy( @@ -23,6 +24,9 @@ UserTrophy _$UserTrophyFromJson(Map json) { earnedAt: utcIso8601ToLocalDate(json['earned_at'] as String), progress: json['progress'] as num, isNotified: json['is_notified'] as bool, + contextData: json['context_data'] == null + ? null + : ContextData.fromJson(json['context_data'] as Map), ); } @@ -32,4 +36,5 @@ Map _$UserTrophyToJson(UserTrophy instance) => . + * Copyright (c) 2025 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 . + */ + +import 'package:json_annotation/json_annotation.dart'; +import 'package:wger/helpers/json.dart'; + +part 'user_trophy_context_data.g.dart'; + +/// A trophy awarded to a user for achieving a specific milestone. + +@JsonSerializable() +class ContextData { + @JsonKey(required: true, name: 'log_id') + final int logId; + + @JsonKey(required: true, fromJson: utcIso8601ToLocalDate) + final DateTime date; + + @JsonKey(required: true, name: 'session_id') + final int sessionId; + + @JsonKey(required: true, name: 'exercise_id') + final int exerciseId; + + @JsonKey(required: true, name: 'repetitions_unit_id') + final int repetitionsUnitId; + + @JsonKey(required: true) + final num repetitions; + + @JsonKey(required: true, name: 'weight_unit_id') + final int weightUnitId; + + @JsonKey(required: true) + final num weight; + + @JsonKey(required: true) + final int? iteration; + + @JsonKey(required: true, name: 'one_rep_max_estimate') + final num oneRepMaxEstimate; + + ContextData({ + required this.logId, + required this.date, + required this.sessionId, + required this.exerciseId, + required this.repetitionsUnitId, + required this.repetitions, + required this.weightUnitId, + required this.weight, + this.iteration, + required this.oneRepMaxEstimate, + }); + + // Boilerplate + factory ContextData.fromJson(Map json) => _$ContextDataFromJson(json); + + Map toJson() => _$ContextDataToJson(this); +} diff --git a/lib/models/trophies/user_trophy_context_data.g.dart b/lib/models/trophies/user_trophy_context_data.g.dart new file mode 100644 index 000000000..e1fcc63a4 --- /dev/null +++ b/lib/models/trophies/user_trophy_context_data.g.dart @@ -0,0 +1,50 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'user_trophy_context_data.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +ContextData _$ContextDataFromJson(Map json) { + $checkKeys( + json, + requiredKeys: const [ + 'log_id', + 'date', + 'session_id', + 'exercise_id', + 'repetitions_unit_id', + 'repetitions', + 'weight_unit_id', + 'weight', + 'iteration', + 'one_rep_max_estimate', + ], + ); + return ContextData( + logId: (json['log_id'] as num).toInt(), + date: utcIso8601ToLocalDate(json['date'] as String), + sessionId: (json['session_id'] as num).toInt(), + exerciseId: (json['exercise_id'] as num).toInt(), + repetitionsUnitId: (json['repetitions_unit_id'] as num).toInt(), + repetitions: json['repetitions'] as num, + weightUnitId: (json['weight_unit_id'] as num).toInt(), + weight: json['weight'] as num, + iteration: (json['iteration'] as num?)?.toInt(), + oneRepMaxEstimate: json['one_rep_max_estimate'] as num, + ); +} + +Map _$ContextDataToJson(ContextData instance) => { + 'log_id': instance.logId, + 'date': instance.date.toIso8601String(), + 'session_id': instance.sessionId, + 'exercise_id': instance.exerciseId, + 'repetitions_unit_id': instance.repetitionsUnitId, + 'repetitions': instance.repetitions, + 'weight_unit_id': instance.weightUnitId, + 'weight': instance.weight, + 'iteration': instance.iteration, + 'one_rep_max_estimate': instance.oneRepMaxEstimate, +}; diff --git a/lib/providers/gym_state.dart b/lib/providers/gym_state.dart index 949a753f8..752f785df 100644 --- a/lib/providers/gym_state.dart +++ b/lib/providers/gym_state.dart @@ -481,7 +481,7 @@ class GymStateNotifier extends _$GymStateNotifier { pages.add(PageEntry(type: PageType.workoutSummary, pageIndex: pageIndex + 1)); state = state.copyWith(pages: pages); - print(readPageStructure()); + // _logger.fine(readPageStructure()); _logger.finer('Initialized ${state.pages.length} pages'); } diff --git a/lib/providers/gym_state.g.dart b/lib/providers/gym_state.g.dart index 1899e808d..1ddf6b8b1 100644 --- a/lib/providers/gym_state.g.dart +++ b/lib/providers/gym_state.g.dart @@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider r'4e1ac85de3c9f5c7dad4b0c5e6ad80ad36397610'; +String _$gymStateNotifierHash() => r'8474afce33638bf67570fd64b64e9b5d171804d3'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); diff --git a/lib/providers/trophies.dart b/lib/providers/trophies.dart index 1da6eea39..e172f5ec4 100644 --- a/lib/providers/trophies.dart +++ b/lib/providers/trophies.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/models/trophies/trophy.dart'; @@ -28,6 +29,8 @@ import 'base_provider.dart'; part 'trophies.g.dart'; class TrophyRepository { + final _logger = Logger('TrophyRepository'); + final WgerBaseProvider base; final trophiesPath = 'trophy'; final userTrophiesPath = 'user-trophy'; @@ -36,21 +39,43 @@ class TrophyRepository { TrophyRepository(this.base); Future> fetchTrophies() async { - final url = base.makeUrl(trophiesPath, query: {'limit': API_MAX_PAGE_SIZE}); - final trophyData = await base.fetchPaginated(url); - return trophyData.map((e) => Trophy.fromJson(e)).toList(); + try { + final url = base.makeUrl(trophiesPath, query: {'limit': API_MAX_PAGE_SIZE}); + final trophyData = await base.fetchPaginated(url); + return trophyData.map((e) => Trophy.fromJson(e)).toList(); + } catch (e, stk) { + _logger.warning('Error fetching trophies:', e, stk); + return []; + } } - Future> fetchUserTrophies() async { - final url = base.makeUrl(userTrophiesPath, query: {'limit': API_MAX_PAGE_SIZE}); - final trophyData = await base.fetchPaginated(url); - return trophyData.map((e) => UserTrophy.fromJson(e)).toList(); + Future> fetchUserTrophies({Map? filterQuery}) async { + final query = {'limit': API_MAX_PAGE_SIZE}; + if (filterQuery != null) { + query.addAll(filterQuery); + } + + try { + final url = base.makeUrl(userTrophiesPath, query: query); + final trophyData = await base.fetchPaginated(url); + return trophyData.map((e) => UserTrophy.fromJson(e)).toList(); + } catch (e, stk) { + _logger.warning('Error fetching user trophies:'); + _logger.warning(e); + _logger.warning(stk); + return []; + } } - Future> fetchProgression() async { - final url = base.makeUrl(userTrophyProgressionPath); - final List data = await base.fetch(url); - return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); + Future> fetchProgression({Map? filterQuery}) async { + try { + final url = base.makeUrl(userTrophyProgressionPath, query: filterQuery); + final List data = await base.fetch(url); + return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); + } catch (e, stk) { + _logger.warning('Error fetching user trophy progression:', e, stk); + return []; + } } List filterByType(List list, TrophyType type) => @@ -74,15 +99,27 @@ final class TrophyStateNotifier extends _$TrophyStateNotifier { return repo.fetchTrophies(); } - /// Fetch trophies awarded to the user + /// Fetch trophies awarded to the user. + /// Excludes hidden trophies as well as repeatable (PR) trophies since they are + /// handled separately Future> fetchUserTrophies() async { final repo = ref.read(trophyRepositoryProvider); - return repo.fetchUserTrophies(); + return repo.fetchUserTrophies( + filterQuery: {'trophy__is_hidden': 'false', 'trophy__is_repeatable': 'false'}, + ); + } + + /// Fetch PR trophies awarded to the user + Future> fetchUserPRTrophies() async { + final repo = ref.read(trophyRepositoryProvider); + return repo.fetchUserTrophies(filterQuery: {'trophy__trophy_type': TrophyType.pr.name}); } /// Fetch trophy progression for the user Future> fetchTrophyProgression() async { final repo = ref.read(trophyRepositoryProvider); - return repo.fetchProgression(); + return repo.fetchProgression( + filterQuery: {'trophy__is_hidden': 'false', 'trophy__is_repeatable': 'false'}, + ); } } diff --git a/lib/providers/trophies.g.dart b/lib/providers/trophies.g.dart index 81c827264..4b413f7f6 100644 --- a/lib/providers/trophies.g.dart +++ b/lib/providers/trophies.g.dart @@ -81,7 +81,7 @@ final class TrophyStateNotifierProvider extends $NotifierProvider r'e5c8f2a9477b8f7e5efe4e9ba23765f951627a9f'; +String _$trophyStateNotifierHash() => r'7f50ce352d980168dae169916a17d9b62b388d28'; abstract class _$TrophyStateNotifier extends $Notifier { void build(); diff --git a/lib/widgets/routines/gym_mode/summary.dart b/lib/widgets/routines/gym_mode/summary.dart index 439d7a0d6..850af71ab 100644 --- a/lib/widgets/routines/gym_mode/summary.dart +++ b/lib/widgets/routines/gym_mode/summary.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 2025 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 @@ -24,10 +24,12 @@ import 'package:logging/logging.dart'; import 'package:provider/provider.dart'; import 'package:wger/helpers/date.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/trophies/user_trophy.dart'; import 'package:wger/models/workouts/routine.dart'; import 'package:wger/models/workouts/session_api.dart'; import 'package:wger/providers/gym_state.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/trophies.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; import 'package:wger/widgets/routines/gym_mode/navigation.dart'; @@ -48,6 +50,7 @@ class WorkoutSummary extends ConsumerStatefulWidget { class _WorkoutSummaryState extends ConsumerState { late Future _initData; late Routine _routine; + late List _userPrTrophies; @override void initState() { @@ -62,6 +65,9 @@ class _WorkoutSummaryState extends ConsumerState { _routine = await context.read().fetchAndSetRoutineFull( gymState.routine.id!, ); + + final trophyNotifier = ref.read(trophyStateProvider.notifier); + _userPrTrophies = await trophyNotifier.fetchUserPRTrophies(); } @override @@ -82,10 +88,18 @@ class _WorkoutSummaryState extends ConsumerState { } else if (snapshot.hasError) { return Center(child: Text('Error: ${snapshot.error}: ${snapshot.stackTrace}')); } else if (snapshot.connectionState == ConnectionState.done) { + final apiSession = _routine.sessions.firstWhereOrNull( + (s) => s.session.date.isSameDayAs(clock.now()), + ); + final userTrophies = _userPrTrophies + .where( + (t) => t.contextData!.sessionId == apiSession?.session.id, + ) + .toList(); + return WorkoutSessionStats( - _routine.sessions.firstWhereOrNull( - (s) => s.session.date.isSameDayAs(clock.now()), - ), + apiSession, + userTrophies, ); } @@ -102,12 +116,14 @@ class _WorkoutSummaryState extends ConsumerState { class WorkoutSessionStats extends ConsumerWidget { final _logger = Logger('WorkoutSessionStats'); final WorkoutSessionApi? _sessionApi; + final List _userPrTrophies; - WorkoutSessionStats(this._sessionApi, {super.key}); + WorkoutSessionStats(this._sessionApi, this._userPrTrophies, {super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); if (_sessionApi == null) { return Center( @@ -159,16 +175,19 @@ class WorkoutSessionStats extends ConsumerWidget { ), ], ), - // const SizedBox(height: 16), - // InfoCard( - // title: 'Personal Records', - // value: prCount.toString(), - // color: theme.colorScheme.tertiaryContainer, - // ), + if (_userPrTrophies.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 10), + child: InfoCard( + title: i18n.personalRecords, + value: _userPrTrophies.length.toString(), + color: theme.colorScheme.tertiaryContainer, + ), + ), const SizedBox(height: 10), MuscleGroupsCard(_sessionApi.logs), const SizedBox(height: 10), - ExercisesCard(_sessionApi), + ExercisesCard(_sessionApi, _userPrTrophies), FilledButton( onPressed: () { ref.read(gymStateProvider.notifier).clear(); diff --git a/lib/widgets/routines/logs/exercises_expansion_card.dart b/lib/widgets/routines/logs/exercises_expansion_card.dart index 0286418f2..ea9634e79 100644 --- a/lib/widgets/routines/logs/exercises_expansion_card.dart +++ b/lib/widgets/routines/logs/exercises_expansion_card.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 2025 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 @@ -20,13 +20,15 @@ import 'package:flutter/material.dart'; import 'package:wger/helpers/i18n.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/exercises/exercise.dart'; +import 'package:wger/models/trophies/user_trophy.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/session_api.dart'; class ExercisesCard extends StatelessWidget { final WorkoutSessionApi session; + final List userPrTrophies; - const ExercisesCard(this.session, {super.key}); + const ExercisesCard(this.session, this.userPrTrophies, {super.key}); @override Widget build(BuildContext context) { @@ -44,7 +46,11 @@ class ExercisesCard extends StatelessWidget { const SizedBox(height: 16), ...exercises.map((exercise) { final logs = session.logs.where((log) => log.exerciseId == exercise.id).toList(); - return _ExerciseExpansionTile(exercise: exercise, logs: logs); + return _ExerciseExpansionTile( + exercise: exercise, + logs: logs, + userPrTrophies: userPrTrophies, + ); }), ], ), @@ -57,8 +63,10 @@ class _ExerciseExpansionTile extends StatelessWidget { const _ExerciseExpansionTile({ required this.exercise, required this.logs, + required this.userPrTrophies, }); + final List userPrTrophies; final Exercise exercise; final List logs; @@ -78,20 +86,20 @@ class _ExerciseExpansionTile extends StatelessWidget { // leading: const Icon(Icons.fitness_center), title: Text(exercise.getTranslation(languageCode).name, style: theme.textTheme.titleMedium), subtitle: Text('Top set: $topSetWeight $topSetWeightUnit'), - children: logs.map((log) => _SetDataRow(log: log)).toList(), + children: logs.map((log) => _SetDataRow(log: log, userPrTrophies: userPrTrophies)).toList(), ); } } class _SetDataRow extends StatelessWidget { - const _SetDataRow({required this.log}); + const _SetDataRow({required this.log, required this.userPrTrophies}); final Log log; + final List userPrTrophies; @override Widget build(BuildContext context) { final theme = Theme.of(context); - final i18n = AppLocalizations.of(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), @@ -103,6 +111,8 @@ class _SetDataRow extends StatelessWidget { log.repTextNoNl(context), style: theme.textTheme.bodyMedium, ), + if (userPrTrophies.any((trophy) => trophy.contextData?.logId == log.id)) + Icon(Icons.emoji_events, color: theme.colorScheme.primary, size: 20), // if (log.volume() > 0) // Text( // '${log.volume().toStringAsFixed(0)} ${getServerStringTranslation(log.weightUnitObj!.name, context)}', diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 389f1556e..fb63573cd 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -1107,6 +1107,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get personalRecords => + (super.noSuchMethod( + Invocation.getter(#personalRecords), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#personalRecords), + ), + ) + as String); + @override String get gymMode => (super.noSuchMethod( diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.dart b/test/trophies/widgets/dashboard_trophies_widget_test.dart index 7c6a92b46..9d7ae799d 100644 --- a/test/trophies/widgets/dashboard_trophies_widget_test.dart +++ b/test/trophies/widgets/dashboard_trophies_widget_test.dart @@ -33,7 +33,9 @@ void main() { testWidgets('DashboardTrophiesWidget shows trophies', (WidgetTester tester) async { // Arrange final mockRepository = MockTrophyRepository(); - when(mockRepository.fetchUserTrophies()).thenAnswer((_) async => getUserTrophies()); + when( + mockRepository.fetchUserTrophies(filterQuery: anyNamed('filterQuery')), + ).thenAnswer((_) async => getUserTrophies()); // Act await mockNetworkImagesFor(() async { @@ -52,7 +54,6 @@ void main() { await tester.pumpAndSettle(); // Assert - // expect(find.text('Trophies'), findsOneWidget); expect(find.text('New Year, New Me'), findsOneWidget); }); }); diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart b/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart index 1c8f3bdec..47c030af4 100644 --- a/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart +++ b/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart @@ -94,9 +94,13 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { as _i5.Future>); @override - _i5.Future> fetchUserTrophies() => + _i5.Future> fetchUserTrophies({ + Map? filterQuery, + }) => (super.noSuchMethod( - Invocation.method(#fetchUserTrophies, []), + Invocation.method(#fetchUserTrophies, [], { + #filterQuery: filterQuery, + }), returnValue: _i5.Future>.value( <_i7.UserTrophy>[], ), @@ -104,9 +108,13 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { as _i5.Future>); @override - _i5.Future> fetchProgression() => + _i5.Future> fetchProgression({ + Map? filterQuery, + }) => (super.noSuchMethod( - Invocation.method(#fetchProgression, []), + Invocation.method(#fetchProgression, [], { + #filterQuery: filterQuery, + }), returnValue: _i5.Future>.value( <_i8.UserTrophyProgression>[], ), diff --git a/test/trophies/widgets/trophies_overview_test.dart b/test/trophies/widgets/trophies_overview_test.dart index 7d7d65aa2..7874f991d 100644 --- a/test/trophies/widgets/trophies_overview_test.dart +++ b/test/trophies/widgets/trophies_overview_test.dart @@ -33,7 +33,9 @@ void main() { testWidgets('TrophiesOverview shows trophies', (WidgetTester tester) async { // Arrange final mockRepository = MockTrophyRepository(); - when(mockRepository.fetchProgression()).thenAnswer((_) async => getUserTrophyProgression()); + when( + mockRepository.fetchProgression(filterQuery: anyNamed('filterQuery')), + ).thenAnswer((_) async => getUserTrophyProgression()); // Act await mockNetworkImagesFor(() async { diff --git a/test/trophies/widgets/trophies_overview_test.mocks.dart b/test/trophies/widgets/trophies_overview_test.mocks.dart new file mode 100644 index 000000000..039b622ad --- /dev/null +++ b/test/trophies/widgets/trophies_overview_test.mocks.dart @@ -0,0 +1,131 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/trophies/widgets/trophies_overview_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:mockito/src/dummies.dart' as _i4; +import 'package:wger/models/trophies/trophy.dart' as _i6; +import 'package:wger/models/trophies/user_trophy.dart' as _i7; +import 'package:wger/models/trophies/user_trophy_progression.dart' as _i8; +import 'package:wger/providers/base_provider.dart' as _i2; +import 'package:wger/providers/trophies.dart' as _i3; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +/// A class which mocks [TrophyRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { + MockTrophyRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.WgerBaseProvider get base => + (super.noSuchMethod( + Invocation.getter(#base), + returnValue: _FakeWgerBaseProvider_0( + this, + Invocation.getter(#base), + ), + ) + as _i2.WgerBaseProvider); + + @override + String get trophiesPath => + (super.noSuchMethod( + Invocation.getter(#trophiesPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#trophiesPath), + ), + ) + as String); + + @override + String get userTrophiesPath => + (super.noSuchMethod( + Invocation.getter(#userTrophiesPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#userTrophiesPath), + ), + ) + as String); + + @override + String get userTrophyProgressionPath => + (super.noSuchMethod( + Invocation.getter(#userTrophyProgressionPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#userTrophyProgressionPath), + ), + ) + as String); + + @override + _i5.Future> fetchTrophies() => + (super.noSuchMethod( + Invocation.method(#fetchTrophies, []), + returnValue: _i5.Future>.value(<_i6.Trophy>[]), + ) + as _i5.Future>); + + @override + _i5.Future> fetchUserTrophies({ + Map? filterQuery, + }) => + (super.noSuchMethod( + Invocation.method(#fetchUserTrophies, [], { + #filterQuery: filterQuery, + }), + returnValue: _i5.Future>.value( + <_i7.UserTrophy>[], + ), + ) + as _i5.Future>); + + @override + _i5.Future> fetchProgression({ + Map? filterQuery, + }) => + (super.noSuchMethod( + Invocation.method(#fetchProgression, [], { + #filterQuery: filterQuery, + }), + returnValue: _i5.Future>.value( + <_i8.UserTrophyProgression>[], + ), + ) + as _i5.Future>); + + @override + List<_i6.Trophy> filterByType(List<_i6.Trophy>? list, _i6.TrophyType? type) => + (super.noSuchMethod( + Invocation.method(#filterByType, [list, type]), + returnValue: <_i6.Trophy>[], + ) + as List<_i6.Trophy>); +} From 52892db9b11ff8fad6e4cae8e356cbad7ccd0448 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 22 Dec 2025 13:03:24 +0100 Subject: [PATCH 12/48] Allow passing the language to the fetch request This allows us to use the trophy translations from the server. --- lib/providers/base_provider.dart | 15 ++++---- lib/providers/trophies.dart | 36 ++++++++++++------- lib/providers/trophies.g.dart | 2 +- lib/widgets/dashboard/widgets/trophies.dart | 3 +- lib/widgets/routines/gym_mode/log_page.dart | 3 ++ lib/widgets/routines/gym_mode/summary.dart | 21 ++++++++--- lib/widgets/trophies/trophies_overview.dart | 3 +- test/core/settings_test.mocks.dart | 14 +++++--- .../contribute_exercise_image_test.mocks.dart | 14 +++++--- test/gallery/gallery_form_test.mocks.dart | 14 +++++--- test/gallery/gallery_screen_test.mocks.dart | 14 +++++--- .../measurement_provider_test.mocks.dart | 14 +++++--- .../nutritional_plan_screen_test.mocks.dart | 14 +++++--- .../nutritional_plans_screen_test.mocks.dart | 14 +++++--- .../routine/gym_mode/gym_mode_test.mocks.dart | 14 +++++--- test/routine/routine_screen_test.mocks.dart | 14 +++++--- .../routine/routines_provider_test.mocks.dart | 14 +++++--- test/routine/routines_screen_test.mocks.dart | 14 +++++--- .../trophies_provider_test.mocks.dart | 14 +++++--- .../dashboard_trophies_widget_test.dart | 5 ++- .../dashboard_trophies_widget_test.mocks.dart | 8 +++-- .../widgets/trophies_overview_test.dart | 5 ++- .../widgets/trophies_overview_test.mocks.dart | 8 +++-- test/user/provider_test.mocks.dart | 32 +++++------------ test/weight/weight_provider_test.mocks.dart | 14 +++++--- 25 files changed, 202 insertions(+), 121 deletions(-) diff --git a/lib/providers/base_provider.dart b/lib/providers/base_provider.dart index dee257d75..a1e11f549 100644 --- a/lib/providers/base_provider.dart +++ b/lib/providers/base_provider.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2025 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 @@ -37,7 +37,7 @@ class WgerBaseProvider { this.client = client ?? http.Client(); } - Map getDefaultHeaders({bool includeAuth = false}) { + Map getDefaultHeaders({bool includeAuth = false, String? language}) { final out = { HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: auth.getAppNameHeader(), @@ -47,6 +47,10 @@ class WgerBaseProvider { out[HttpHeaders.authorizationHeader] = 'Token ${auth.token}'; } + if (language != null) { + out[HttpHeaders.acceptLanguageHeader] = language; + } + return out; } @@ -56,8 +60,7 @@ class WgerBaseProvider { } /// Fetch and retrieve the overview list of objects, returns the JSON parsed response - Future fetch(Uri uri) async { - // Future | List> fetch(Uri uri) async { + Future fetch(Uri uri, {String? language}) async { // Send the request final response = await client.get( uri, @@ -74,13 +77,13 @@ class WgerBaseProvider { } /// Fetch and retrieve the overview list of objects, returns the JSON parsed response - Future> fetchPaginated(Uri uri) async { + Future> fetchPaginated(Uri uri, {String? language}) async { final out = []; var url = uri; var allPagesProcessed = false; while (!allPagesProcessed) { - final data = await fetch(url); + final data = await fetch(url, language: language); data['results'].forEach((e) => out.add(e)); diff --git a/lib/providers/trophies.dart b/lib/providers/trophies.dart index e172f5ec4..183a8fdec 100644 --- a/lib/providers/trophies.dart +++ b/lib/providers/trophies.dart @@ -38,10 +38,10 @@ class TrophyRepository { TrophyRepository(this.base); - Future> fetchTrophies() async { + Future> fetchTrophies({String? language}) async { try { final url = base.makeUrl(trophiesPath, query: {'limit': API_MAX_PAGE_SIZE}); - final trophyData = await base.fetchPaginated(url); + final trophyData = await base.fetchPaginated(url, language: language); return trophyData.map((e) => Trophy.fromJson(e)).toList(); } catch (e, stk) { _logger.warning('Error fetching trophies:', e, stk); @@ -49,7 +49,10 @@ class TrophyRepository { } } - Future> fetchUserTrophies({Map? filterQuery}) async { + Future> fetchUserTrophies({ + Map? filterQuery, + String? language, + }) async { final query = {'limit': API_MAX_PAGE_SIZE}; if (filterQuery != null) { query.addAll(filterQuery); @@ -57,7 +60,7 @@ class TrophyRepository { try { final url = base.makeUrl(userTrophiesPath, query: query); - final trophyData = await base.fetchPaginated(url); + final trophyData = await base.fetchPaginated(url, language: language); return trophyData.map((e) => UserTrophy.fromJson(e)).toList(); } catch (e, stk) { _logger.warning('Error fetching user trophies:'); @@ -67,10 +70,13 @@ class TrophyRepository { } } - Future> fetchProgression({Map? filterQuery}) async { + Future> fetchProgression({ + Map? filterQuery, + String? language, + }) async { try { final url = base.makeUrl(userTrophyProgressionPath, query: filterQuery); - final List data = await base.fetch(url); + final List data = await base.fetch(url, language: language); return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); } catch (e, stk) { _logger.warning('Error fetching user trophy progression:', e, stk); @@ -102,24 +108,28 @@ final class TrophyStateNotifier extends _$TrophyStateNotifier { /// Fetch trophies awarded to the user. /// Excludes hidden trophies as well as repeatable (PR) trophies since they are /// handled separately - Future> fetchUserTrophies() async { + Future> fetchUserTrophies({String? language}) async { final repo = ref.read(trophyRepositoryProvider); return repo.fetchUserTrophies( filterQuery: {'trophy__is_hidden': 'false', 'trophy__is_repeatable': 'false'}, + language: language, ); } /// Fetch PR trophies awarded to the user - Future> fetchUserPRTrophies() async { + Future> fetchUserPRTrophies({String? language}) async { final repo = ref.read(trophyRepositoryProvider); - return repo.fetchUserTrophies(filterQuery: {'trophy__trophy_type': TrophyType.pr.name}); + return repo.fetchUserTrophies( + filterQuery: {'trophy__trophy_type': TrophyType.pr.name}, + language: language, + ); } /// Fetch trophy progression for the user - Future> fetchTrophyProgression() async { + Future> fetchTrophyProgression({String? language}) async { final repo = ref.read(trophyRepositoryProvider); - return repo.fetchProgression( - filterQuery: {'trophy__is_hidden': 'false', 'trophy__is_repeatable': 'false'}, - ); + + // Note that repeatable trophies are filtered out in the backend + return repo.fetchProgression(language: language); } } diff --git a/lib/providers/trophies.g.dart b/lib/providers/trophies.g.dart index 4b413f7f6..88f47d587 100644 --- a/lib/providers/trophies.g.dart +++ b/lib/providers/trophies.g.dart @@ -81,7 +81,7 @@ final class TrophyStateNotifierProvider extends $NotifierProvider r'7f50ce352d980168dae169916a17d9b62b388d28'; +String _$trophyStateNotifierHash() => r'47b4babf337bbb8bf60142ebe59dc760fa08dce3'; abstract class _$TrophyStateNotifier extends $Notifier { void build(); diff --git a/lib/widgets/dashboard/widgets/trophies.dart b/lib/widgets/dashboard/widgets/trophies.dart index b0e1bb623..3e39fd451 100644 --- a/lib/widgets/dashboard/widgets/trophies.dart +++ b/lib/widgets/dashboard/widgets/trophies.dart @@ -29,9 +29,10 @@ class DashboardTrophiesWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final provider = ref.watch(trophyStateProvider.notifier); + final languageCode = Localizations.localeOf(context).languageCode; return FutureBuilder( - future: provider.fetchUserTrophies(), + future: provider.fetchUserTrophies(language: languageCode), builder: (context, asyncSnapshot) { if (asyncSnapshot.connectionState != ConnectionState.done) { return const Card(child: BoxedProgressIndicator()); diff --git a/lib/widgets/routines/gym_mode/log_page.dart b/lib/widgets/routines/gym_mode/log_page.dart index 702542667..10cf7e649 100644 --- a/lib/widgets/routines/gym_mode/log_page.dart +++ b/lib/widgets/routines/gym_mode/log_page.dart @@ -549,6 +549,9 @@ class _LogFormWidgetState extends ConsumerState { _weightController = TextEditingController(); WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } _syncControllersWithWidget(); }); } diff --git a/lib/widgets/routines/gym_mode/summary.dart b/lib/widgets/routines/gym_mode/summary.dart index 850af71ab..146b15c57 100644 --- a/lib/widgets/routines/gym_mode/summary.dart +++ b/lib/widgets/routines/gym_mode/summary.dart @@ -38,7 +38,6 @@ import '../logs/muscle_groups.dart'; class WorkoutSummary extends ConsumerStatefulWidget { final _logger = Logger('WorkoutSummary'); - final PageController _controller; WorkoutSummary(this._controller); @@ -51,14 +50,24 @@ class _WorkoutSummaryState extends ConsumerState { late Future _initData; late Routine _routine; late List _userPrTrophies; + bool _didInit = false; @override void initState() { super.initState(); - _initData = _reloadRoutineData(); } - Future _reloadRoutineData() async { + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (!_didInit) { + final languageCode = Localizations.localeOf(context).languageCode; + _initData = _reloadRoutineData(languageCode); + _didInit = true; + } + } + + Future _reloadRoutineData(String languageCode) async { widget._logger.fine('Loading routine data'); final gymState = ref.read(gymStateProvider); @@ -67,7 +76,7 @@ class _WorkoutSummaryState extends ConsumerState { ); final trophyNotifier = ref.read(trophyStateProvider.notifier); - _userPrTrophies = await trophyNotifier.fetchUserPRTrophies(); + _userPrTrophies = await trophyNotifier.fetchUserPRTrophies(language: languageCode); } @override @@ -86,7 +95,9 @@ class _WorkoutSummaryState extends ConsumerState { if (snapshot.connectionState == ConnectionState.waiting) { return const BoxedProgressIndicator(); } else if (snapshot.hasError) { - return Center(child: Text('Error: ${snapshot.error}: ${snapshot.stackTrace}')); + widget._logger.warning(snapshot.error); + widget._logger.warning(snapshot.stackTrace); + return Center(child: Text('Error: ${snapshot.error}')); } else if (snapshot.connectionState == ConnectionState.done) { final apiSession = _routine.sessions.firstWhereOrNull( (s) => s.session.date.isSameDayAs(clock.now()), diff --git a/lib/widgets/trophies/trophies_overview.dart b/lib/widgets/trophies/trophies_overview.dart index 2db561e72..d763e9460 100644 --- a/lib/widgets/trophies/trophies_overview.dart +++ b/lib/widgets/trophies/trophies_overview.dart @@ -29,6 +29,7 @@ class TrophiesOverview extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final notifier = ref.watch(trophyStateProvider.notifier); + final languageCode = Localizations.localeOf(context).languageCode; // Responsive grid: determine columns based on screen width final width = MediaQuery.widthOf(context); @@ -44,7 +45,7 @@ class TrophiesOverview extends ConsumerWidget { } return FutureBuilder>( - future: notifier.fetchTrophyProgression(), + future: notifier.fetchTrophyProgression(language: languageCode), builder: (context, snapshot) { if (snapshot.connectionState != ConnectionState.done) { return const Card(child: BoxedProgressIndicator()); diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index db2394bdf..e883c76de 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -1066,10 +1066,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -1100,17 +1104,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i18.Future fetch(Uri? uri) => + _i18.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i18.Future.value(), ) as _i18.Future); @override - _i18.Future> fetchPaginated(Uri? uri) => + _i18.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i18.Future>.value([]), ) as _i18.Future>); diff --git a/test/exercises/contribute_exercise_image_test.mocks.dart b/test/exercises/contribute_exercise_image_test.mocks.dart index c3685ed3e..c5c3b857c 100644 --- a/test/exercises/contribute_exercise_image_test.mocks.dart +++ b/test/exercises/contribute_exercise_image_test.mocks.dart @@ -368,10 +368,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -402,17 +406,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i14.Future fetch(Uri? uri) => + _i14.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i14.Future.value(), ) as _i14.Future); @override - _i14.Future> fetchPaginated(Uri? uri) => + _i14.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i14.Future>.value([]), ) as _i14.Future>); diff --git a/test/gallery/gallery_form_test.mocks.dart b/test/gallery/gallery_form_test.mocks.dart index e14d78381..a531b6ae9 100644 --- a/test/gallery/gallery_form_test.mocks.dart +++ b/test/gallery/gallery_form_test.mocks.dart @@ -141,10 +141,14 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as _i6.Future); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -175,17 +179,17 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as Uri); @override - _i6.Future fetch(Uri? uri) => + _i6.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i6.Future.value(), ) as _i6.Future); @override - _i6.Future> fetchPaginated(Uri? uri) => + _i6.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i6.Future>.value([]), ) as _i6.Future>); diff --git a/test/gallery/gallery_screen_test.mocks.dart b/test/gallery/gallery_screen_test.mocks.dart index d1ab1318c..330d0c420 100644 --- a/test/gallery/gallery_screen_test.mocks.dart +++ b/test/gallery/gallery_screen_test.mocks.dart @@ -141,10 +141,14 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as _i6.Future); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -175,17 +179,17 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as Uri); @override - _i6.Future fetch(Uri? uri) => + _i6.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i6.Future.value(), ) as _i6.Future); @override - _i6.Future> fetchPaginated(Uri? uri) => + _i6.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i6.Future>.value([]), ) as _i6.Future>); diff --git a/test/measurements/measurement_provider_test.mocks.dart b/test/measurements/measurement_provider_test.mocks.dart index ef362a877..c8c22b455 100644 --- a/test/measurements/measurement_provider_test.mocks.dart +++ b/test/measurements/measurement_provider_test.mocks.dart @@ -78,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -112,17 +116,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/nutrition/nutritional_plan_screen_test.mocks.dart b/test/nutrition/nutritional_plan_screen_test.mocks.dart index 2fe3c4ac5..0ff6d2922 100644 --- a/test/nutrition/nutritional_plan_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plan_screen_test.mocks.dart @@ -88,10 +88,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -122,17 +126,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/nutrition/nutritional_plans_screen_test.mocks.dart b/test/nutrition/nutritional_plans_screen_test.mocks.dart index c702d4015..e42d7a17f 100644 --- a/test/nutrition/nutritional_plans_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plans_screen_test.mocks.dart @@ -323,10 +323,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -357,17 +361,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/routine/gym_mode/gym_mode_test.mocks.dart b/test/routine/gym_mode/gym_mode_test.mocks.dart index 6b3c882cc..8259d2c07 100644 --- a/test/routine/gym_mode/gym_mode_test.mocks.dart +++ b/test/routine/gym_mode/gym_mode_test.mocks.dart @@ -167,10 +167,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -201,17 +205,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i20.Future fetch(Uri? uri) => + _i20.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i20.Future.value(), ) as _i20.Future); @override - _i20.Future> fetchPaginated(Uri? uri) => + _i20.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i20.Future>.value([]), ) as _i20.Future>); diff --git a/test/routine/routine_screen_test.mocks.dart b/test/routine/routine_screen_test.mocks.dart index 99fe1643b..8f05a8179 100644 --- a/test/routine/routine_screen_test.mocks.dart +++ b/test/routine/routine_screen_test.mocks.dart @@ -78,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -112,17 +116,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/routine/routines_provider_test.mocks.dart b/test/routine/routines_provider_test.mocks.dart index 063265063..ae7514683 100644 --- a/test/routine/routines_provider_test.mocks.dart +++ b/test/routine/routines_provider_test.mocks.dart @@ -117,10 +117,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -151,17 +155,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i11.Future fetch(Uri? uri) => + _i11.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i11.Future.value(), ) as _i11.Future); @override - _i11.Future> fetchPaginated(Uri? uri) => + _i11.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i11.Future>.value([]), ) as _i11.Future>); diff --git a/test/routine/routines_screen_test.mocks.dart b/test/routine/routines_screen_test.mocks.dart index 2607f048f..1dafb2ca2 100644 --- a/test/routine/routines_screen_test.mocks.dart +++ b/test/routine/routines_screen_test.mocks.dart @@ -78,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -112,17 +116,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/trophies/provider/trophies_provider_test.mocks.dart b/test/trophies/provider/trophies_provider_test.mocks.dart index 9830acb46..79887735e 100644 --- a/test/trophies/provider/trophies_provider_test.mocks.dart +++ b/test/trophies/provider/trophies_provider_test.mocks.dart @@ -78,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -112,17 +116,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.dart b/test/trophies/widgets/dashboard_trophies_widget_test.dart index 9d7ae799d..bf4209b49 100644 --- a/test/trophies/widgets/dashboard_trophies_widget_test.dart +++ b/test/trophies/widgets/dashboard_trophies_widget_test.dart @@ -34,7 +34,10 @@ void main() { // Arrange final mockRepository = MockTrophyRepository(); when( - mockRepository.fetchUserTrophies(filterQuery: anyNamed('filterQuery')), + mockRepository.fetchUserTrophies( + filterQuery: anyNamed('filterQuery'), + language: anyNamed('language'), + ), ).thenAnswer((_) async => getUserTrophies()); // Act diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart b/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart index 47c030af4..41544f94f 100644 --- a/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart +++ b/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart @@ -86,9 +86,9 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { as String); @override - _i5.Future> fetchTrophies() => + _i5.Future> fetchTrophies({String? language}) => (super.noSuchMethod( - Invocation.method(#fetchTrophies, []), + Invocation.method(#fetchTrophies, [], {#language: language}), returnValue: _i5.Future>.value(<_i6.Trophy>[]), ) as _i5.Future>); @@ -96,10 +96,12 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { @override _i5.Future> fetchUserTrophies({ Map? filterQuery, + String? language, }) => (super.noSuchMethod( Invocation.method(#fetchUserTrophies, [], { #filterQuery: filterQuery, + #language: language, }), returnValue: _i5.Future>.value( <_i7.UserTrophy>[], @@ -110,10 +112,12 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { @override _i5.Future> fetchProgression({ Map? filterQuery, + String? language, }) => (super.noSuchMethod( Invocation.method(#fetchProgression, [], { #filterQuery: filterQuery, + #language: language, }), returnValue: _i5.Future>.value( <_i8.UserTrophyProgression>[], diff --git a/test/trophies/widgets/trophies_overview_test.dart b/test/trophies/widgets/trophies_overview_test.dart index 7874f991d..2c6b71f5a 100644 --- a/test/trophies/widgets/trophies_overview_test.dart +++ b/test/trophies/widgets/trophies_overview_test.dart @@ -34,7 +34,10 @@ void main() { // Arrange final mockRepository = MockTrophyRepository(); when( - mockRepository.fetchProgression(filterQuery: anyNamed('filterQuery')), + mockRepository.fetchProgression( + filterQuery: anyNamed('filterQuery'), + language: anyNamed('language'), + ), ).thenAnswer((_) async => getUserTrophyProgression()); // Act diff --git a/test/trophies/widgets/trophies_overview_test.mocks.dart b/test/trophies/widgets/trophies_overview_test.mocks.dart index 039b622ad..dc837fd8c 100644 --- a/test/trophies/widgets/trophies_overview_test.mocks.dart +++ b/test/trophies/widgets/trophies_overview_test.mocks.dart @@ -86,9 +86,9 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { as String); @override - _i5.Future> fetchTrophies() => + _i5.Future> fetchTrophies({String? language}) => (super.noSuchMethod( - Invocation.method(#fetchTrophies, []), + Invocation.method(#fetchTrophies, [], {#language: language}), returnValue: _i5.Future>.value(<_i6.Trophy>[]), ) as _i5.Future>); @@ -96,10 +96,12 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { @override _i5.Future> fetchUserTrophies({ Map? filterQuery, + String? language, }) => (super.noSuchMethod( Invocation.method(#fetchUserTrophies, [], { #filterQuery: filterQuery, + #language: language, }), returnValue: _i5.Future>.value( <_i7.UserTrophy>[], @@ -110,10 +112,12 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { @override _i5.Future> fetchProgression({ Map? filterQuery, + String? language, }) => (super.noSuchMethod( Invocation.method(#fetchProgression, [], { #filterQuery: filterQuery, + #language: language, }), returnValue: _i5.Future>.value( <_i8.UserTrophyProgression>[], diff --git a/test/user/provider_test.mocks.dart b/test/user/provider_test.mocks.dart index b8fce543f..6ff9bc854 100644 --- a/test/user/provider_test.mocks.dart +++ b/test/user/provider_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/user/provider_test.dart. // Do not manually edit this file. @@ -96,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -130,17 +116,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/weight/weight_provider_test.mocks.dart b/test/weight/weight_provider_test.mocks.dart index 4cd18bb56..bf00ffb14 100644 --- a/test/weight/weight_provider_test.mocks.dart +++ b/test/weight/weight_provider_test.mocks.dart @@ -78,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -112,17 +116,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method(#fetch, [uri], {#language: language}), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); From 0343a0c2a5634a074ffe794ac30e6d115e83dac7 Mon Sep 17 00:00:00 2001 From: Floris C Date: Fri, 19 Dec 2025 12:51:20 +0100 Subject: [PATCH 13/48] Translated using Weblate (Dutch) Currently translated at 100.0% (369 of 369 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/nl/ --- lib/l10n/app_nl.arb | 548 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 547 insertions(+), 1 deletion(-) diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 6da9385a2..449807d2e 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -694,5 +694,551 @@ "toggleDetails": "Schakel details in", "@toggleDetails": { "description": "Switch to toggle detail / overview" - } + }, + "goToDetailPage": "Ga naar detail pagina", + "@goToDetailPage": {}, + "aboutWhySupportTitle": "Open Source & gratis te gebruiken ❤️", + "@aboutWhySupportTitle": {}, + "aboutDescription": "Bedankt voor het gebruiken van wger! wger is een collaboratief open source project, gemaakt door fitness fans van over de hele wereld.", + "@aboutDescription": { + "description": "Text in the about dialog" + }, + "aboutDonateTitle": "Maak een donatie", + "@aboutDonateTitle": {}, + "aboutDonateText": "Hoewel het project gratis is en dat ook altijd zal blijven, zijn de kosten voor het draaien van de server dat niet! De ontwikkeling vergt bovendien veel tijd en inzet van vrijwilligers. Uw bijdrage dekt deze kosten direct en helpt de betrouwbaarheid van de dienst te waarborgen.", + "@aboutDonateText": {}, + "aboutContributeTitle": "Bijdragen", + "@aboutContributeTitle": {}, + "aboutContributeText": "Alle soorten bijdragen zijn welkom. Of je nu ontwikkelaar bent, vertaler of gewoon een fitnessliefhebber, elke vorm van steun wordt gewaardeerd!", + "@aboutContributeText": {}, + "aboutBugsListTitle": "Meld een probleem of stel een functie voor", + "@aboutBugsListTitle": {}, + "aboutTranslationListTitle": "Vertaal de applicatie", + "@aboutTranslationListTitle": {}, + "aboutSourceListTitle": "Bekijk broncode", + "@aboutSourceListTitle": {}, + "aboutJoinCommunityTitle": "Sluit je aan bij de community", + "@aboutJoinCommunityTitle": {}, + "aboutMastodonTitle": "Mastodon", + "@aboutMastodonTitle": {}, + "aboutDiscordTitle": "Discord", + "@aboutDiscordTitle": {}, + "others": "Anderen", + "@others": {}, + "calendar": "Kalender", + "@calendar": {}, + "goToToday": "Ga naar vandaag", + "@goToToday": { + "description": "Label on button to jump back to 'today' in the calendar widget" + }, + "enterValue": "Voer een waarde in", + "@enterValue": { + "description": "Error message when the user hasn't entered a value on a required field" + }, + "selectEntry": "Selecteer een entry", + "@selectEntry": {}, + "selectExercise": "Selecteer een oefening", + "@selectExercise": { + "description": "Error message when the user hasn't selected an exercise in the form" + }, + "enterCharacters": "Voer tussen {min} en {max} tekens in", + "@enterCharacters": { + "description": "Error message when the user hasn't entered the correct number of characters in a form", + "type": "text", + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "formMinMaxValues": "Voer een waarde tussen {min} en {max} in", + "@formMinMaxValues": { + "description": "Error message when the user needs to enter a value between min and max", + "type": "text", + "placeholders": { + "min": { + "type": "int" + }, + "max": { + "type": "int" + } + } + }, + "enterMinCharacters": "Voer minstens {min} tekens in", + "@enterMinCharacters": { + "description": "Error message when the user hasn't entered the minimum amount characters in a form", + "type": "text", + "placeholders": { + "min": { + "type": "String" + } + } + }, + "baseNameEnglish": "Alle oefeningen moeten een basisnaam in het Engels hebben", + "@baseNameEnglish": {}, + "nrOfSets": "Sets per oefening: {nrOfSets}", + "@nrOfSets": { + "description": "Label shown on the slider where the user selects the nr of sets", + "type": "text", + "placeholders": { + "nrOfSets": { + "type": "String" + } + } + }, + "setUnitsAndRir": "Stel eenheden en RiR in", + "@setUnitsAndRir": { + "description": "Label shown on the slider where the user can toggle showing units and RiR", + "type": "text" + }, + "enterValidNumber": "Voer een geldig nummer in", + "@enterValidNumber": { + "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" + }, + "selectIngredient": "Selecteer een ingrediënt", + "@selectIngredient": { + "description": "Error message when the user hasn't selected an ingredient from the autocompleter" + }, + "recentlyUsedIngredients": "Recent toegevoegde ingrediënten", + "@recentlyUsedIngredients": { + "description": "A message when a user adds a new ingredient to a meal." + }, + "selectImage": "Selecteer een afbeelding", + "@selectImage": { + "description": "Label and error message when the user hasn't selected an image to save" + }, + "optionsLabel": "Opties", + "@optionsLabel": { + "description": "Label for the popup with general app options" + }, + "takePicture": "Neem een foto", + "@takePicture": {}, + "chooseFromLibrary": "Kies uit foto galerij", + "@chooseFromLibrary": {}, + "gallery": "Galerij", + "@gallery": {}, + "addImage": "Afbeelding toevoegen", + "@addImage": {}, + "dataCopied": "Gegevens gekopieerd naar een nieuw item", + "@dataCopied": { + "description": "Snackbar message to show on copying data to a new log entry" + }, + "appUpdateTitle": "Update vereist", + "@appUpdateTitle": {}, + "appUpdateContent": "Deze versie van de app is niet compatibel met de server, update uw applicatie.", + "@appUpdateContent": {}, + "productFound": "Product gevonden", + "@productFound": { + "description": "Header label for dialog when product is found with barcode" + }, + "productFoundDescription": "De barcode hoort bij dit product: {productName}. Wilt u doorgaan?", + "@productFoundDescription": { + "description": "Dialog info when product is found with barcode", + "type": "text", + "placeholders": { + "productName": { + "type": "String" + } + } + }, + "productNotFound": "Product niet gevonden", + "@productNotFound": { + "description": "Header label for dialog when product is not found with barcode" + }, + "productNotFoundDescription": "Het product met de gescande barcode {barcode} is niet gevonden in de wger database", + "@productNotFoundDescription": { + "description": "Dialog info when product is not found with barcode", + "type": "text", + "placeholders": { + "barcode": { + "type": "String" + } + } + }, + "scanBarcode": "Scan barcode", + "@scanBarcode": { + "description": "Label for scan barcode button" + }, + "close": "Sluiten", + "@close": { + "description": "Translation for close" + }, + "identicalExercisePleaseDiscard": "Als je een oefening ziet die identiek is aan degene die je toevoegt, gooi dan je concept weg en bewerk die oefening in plaats daarvan.", + "@identicalExercisePleaseDiscard": {}, + "checkInformationBeforeSubmitting": "Controleer of de ingevoerde gegevens correct zijn voordat u de oefening indient", + "@checkInformationBeforeSubmitting": {}, + "add_exercise_image_license": "Afbeeldingen moeten compatibel zijn met de CC BY SA-licentie. Upload bij twijfel alleen foto's die je zelf hebt gemaakt.", + "@add_exercise_image_license": {}, + "imageDetailsTitle": "Afbeeldingsdetails", + "@imageDetailsTitle": { + "description": "Title for image details form" + }, + "imageDetailsLicenseTitle": "Titel", + "@imageDetailsLicenseTitle": { + "description": "Label for image title field" + }, + "imageDetailsLicenseTitleHint": "Voer afbeeldingsnaam in", + "@imageDetailsLicenseTitleHint": { + "description": "Hint text for image title field" + }, + "imageDetailsSourceLink": "Link naar de bronwebsite", + "@imageDetailsSourceLink": { + "description": "Label for source link field" + }, + "author": "Auteur(s)", + "@author": {}, + "authorHint": "Voer auteursnaam in", + "@authorHint": { + "description": "Hint text for author field" + }, + "imageDetailsAuthorLink": "Link naar de website of het profiel van de auteur", + "@imageDetailsAuthorLink": { + "description": "Label for author link field" + }, + "imageDetailsDerivativeSource": "Link naar de originele bron, als dit een afgeleid werk is", + "@imageDetailsDerivativeSource": { + "description": "Label for derivative source field" + }, + "imageDetailsDerivativeHelp": "Hulptekst ter uitleg van afgeleide werken.", + "@imageDetailsDerivativeHelp": { + "description": "Helper text explaining derivative works" + }, + "imageDetailsImageType": "Afbeeldingstype", + "@imageDetailsImageType": { + "description": "Label for image type selector" + }, + "imageDetailsLicenseNotice": "Door deze afbeelding in te dienen, stemt u ermee in deze vrij te geven onder de CC-BY-SA-4-licentie. De afbeelding moet uw eigen werk zijn of de auteur moet deze hebben vrijgegeven onder een licentie die hiermee compatibel is.", + "@imageDetailsLicenseNotice": {}, + "imageDetailsLicenseNoticeLinkToLicense": "Zie licentie tekst.", + "@imageDetailsLicenseNoticeLinkToLicense": {}, + "imageFormatNotSupported": "{imageFormat} wordt niet ondersteund", + "@imageFormatNotSupported": { + "description": "Label shown on the error container when image format is not supported", + "type": "text", + "placeholders": { + "imageFormat": { + "type": "String" + } + } + }, + "imageFormatNotSupportedDetail": "Afbeeldingen met het formaat {imageFormat} worden nog niet ondersteund.", + "@imageFormatNotSupportedDetail": { + "description": "Label shown on the image preview container when image format is not supported", + "type": "text", + "placeholders": { + "imageFormat": { + "type": "String" + } + } + }, + "add": "toevoegen", + "@add": { + "description": "Add button text" + }, + "variations": "Variaties", + "@variations": { + "description": "Variations of one exercise (e.g. benchpress and benchpress narrow)" + }, + "alsoKnownAs": "Ook bekend als: {aliassen}", + "@alsoKnownAs": { + "placeholders": { + "aliases": { + "type": "String" + } + }, + "description": "List of alternative names for an exercise" + }, + "verifiedEmail": "Geverifieerde email", + "@verifiedEmail": {}, + "unVerifiedEmail": "Niet-geverifieerde e-mail", + "@unVerifiedEmail": {}, + "verifiedEmailReason": "Je moet je e-mailadres verifiëren om oefeningen te kunnen doen", + "@verifiedEmailReason": {}, + "verifiedEmailInfo": "Er is een verificatiemail verzonden naar {email}", + "@verifiedEmailInfo": { + "placeholders": { + "email": { + "type": "String" + } + } + }, + "alternativeNames": "Alternatieve namen", + "@alternativeNames": {}, + "oneNamePerLine": "Een naam per lijn", + "@oneNamePerLine": {}, + "whatVariationsExist": "Welke varianten van deze oefening bestaan er, indien van toepassing?", + "@whatVariationsExist": {}, + "previous": "Vorige", + "@previous": {}, + "next": "Volgende", + "@next": {}, + "images": "Afbeeldingen", + "@images": {}, + "language": "Taal", + "@language": {}, + "addExercise": "Voeg oefening toe", + "@addExercise": {}, + "fitInWeek": "In week passen", + "@fitInWeek": {}, + "fitInWeekHelp": "Indien ingeschakeld, zullen de dagen zich herhalen in een wekelijkse cyclus; anders zullen de dagen elkaar opeenvolgend opvolgen, ongeacht het begin van een nieuwe week.", + "@fitInWeekHelp": {}, + "addSuperset": "Superset toevoegen", + "@addSuperset": {}, + "superset": "Superset", + "@superset": {}, + "setHasProgression": "Set heeft progressie", + "@setHasProgression": {}, + "setHasProgressionWarning": "Houd er rekening mee dat het momenteel niet mogelijk is om alle instellingen voor een set te bewerken in de mobiele app of om de automatische voortgang te configureren. Gebruik hiervoor voorlopig de webapp.", + "@setHasProgressionWarning": {}, + "setHasNoExercises": "Deze set heeft nog geen oefeningen!", + "@setHasNoExercises": {}, + "contributeExercise": "Draag een oefening bij", + "@contributeExercise": {}, + "translation": "Vertaling", + "@translation": {}, + "translateExercise": "Vertaal deze oefening", + "@translateExercise": {}, + "baseData": "Basics in Engels", + "@baseData": { + "description": "The base data for an exercise such as category, trained muscles, etc." + }, + "enterTextInLanguage": "Voer de tekst in de juiste taal in!", + "@enterTextInLanguage": {}, + "settingsTitle": "Instellingen", + "@settingsTitle": {}, + "settingsCacheTitle": "Cache", + "@settingsCacheTitle": {}, + "settingsExerciseCacheDescription": "Oefeningscache", + "@settingsExerciseCacheDescription": {}, + "settingsIngredientCacheDescription": "Ingrediënten cache", + "@settingsIngredientCacheDescription": {}, + "settingsCacheDeletedSnackbar": "Cache succesvol geleegd", + "@settingsCacheDeletedSnackbar": {}, + "aboutPageTitle": "Over ons & Support", + "@aboutPageTitle": {}, + "contributeExerciseWarning": "Je kunt alleen oefeningen bijdragen als je account ouder is dan {days} dagen en je e-mailadres is geverifieerd", + "@contributeExerciseWarning": { + "description": "Number of days before which a person can add exercise", + "placeholders": { + "days": { + "type": "String", + "example": "14" + } + } + }, + "simpleMode": "Eenvoudige modus", + "@simpleMode": {}, + "simpleModeHelp": "Verberg enkele van de meer geavanceerde instellingen tijdens het bewerken van oefeningen", + "@simpleModeHelp": {}, + "progressionRules": "Deze oefening heeft voortgangsregels en kan niet worden bewerkt in de mobiele app. Gebruik de webapplicatie om deze oefening te bewerken.", + "@progressionRules": {}, + "cacheWarning": "Vanwege de caching kan het even duren voordat de wijzigingen in de hele applicatie zichtbaar zijn.", + "@cacheWarning": {}, + "textPromptTitle": "Klaar om te starten?", + "@textPromptTitle": {}, + "textPromptSubheading": "Druk op de actieknop om te beginnen", + "@textPromptSubheading": {}, + "abs": "Buikspieren", + "@abs": { + "description": "Generated entry for translation for server strings" + }, + "arms": "Armen", + "@arms": { + "description": "Generated entry for translation for server strings" + }, + "back": "Rug", + "@back": { + "description": "Generated entry for translation for server strings" + }, + "barbell": "Barbell", + "@barbell": { + "description": "Generated entry for translation for server strings" + }, + "bench": "Bench", + "@bench": { + "description": "Generated entry for translation for server strings" + }, + "biceps": "Biceps", + "@biceps": { + "description": "Generated entry for translation for server strings" + }, + "body_weight": "Gewicht", + "@body_weight": { + "description": "Generated entry for translation for server strings" + }, + "calves": "Kuiten", + "@calves": { + "description": "Generated entry for translation for server strings" + }, + "cardio": "Cardio", + "@cardio": { + "description": "Generated entry for translation for server strings" + }, + "chest": "Borst", + "@chest": { + "description": "Generated entry for translation for server strings" + }, + "dumbbell": "Dumbbell", + "@dumbbell": { + "description": "Generated entry for translation for server strings" + }, + "glutes": "Glutes", + "@glutes": { + "description": "Generated entry for translation for server strings" + }, + "gym_mat": "Gym matje", + "@gym_mat": { + "description": "Generated entry for translation for server strings" + }, + "hamstrings": "Hamstrings", + "@hamstrings": { + "description": "Generated entry for translation for server strings" + }, + "incline_bench": "Incline bench", + "@incline_bench": { + "description": "Generated entry for translation for server strings" + }, + "kettlebell": "Kettlebell", + "@kettlebell": { + "description": "Generated entry for translation for server strings" + }, + "kilometers": "Kilometers", + "@kilometers": { + "description": "Generated entry for translation for server strings" + }, + "kilometers_per_hour": "Kilometers Per Uur", + "@kilometers_per_hour": { + "description": "Generated entry for translation for server strings" + }, + "lats": "Lats", + "@lats": { + "description": "Generated entry for translation for server strings" + }, + "legs": "Benen", + "@legs": { + "description": "Generated entry for translation for server strings" + }, + "lower_back": "Onderrug", + "@lower_back": { + "description": "Generated entry for translation for server strings" + }, + "max_reps": "Max Herhalingen", + "@max_reps": { + "description": "Generated entry for translation for server strings" + }, + "miles": "Miles", + "@miles": { + "description": "Generated entry for translation for server strings" + }, + "miles_per_hour": "Miles Per Uur", + "@miles_per_hour": { + "description": "Generated entry for translation for server strings" + }, + "minutes": "Minuten", + "@minutes": { + "description": "Generated entry for translation for server strings" + }, + "plates": "Platen", + "@plates": { + "description": "Generated entry for translation for server strings" + }, + "pull_up_bar": "Pull-up bar", + "@pull_up_bar": { + "description": "Generated entry for translation for server strings" + }, + "quads": "Quads", + "@quads": { + "description": "Generated entry for translation for server strings" + }, + "repetitions": "Herhalingen", + "@repetitions": { + "description": "Generated entry for translation for server strings" + }, + "resistance_band": "Weerstandsband", + "@resistance_band": { + "description": "Generated entry for translation for server strings" + }, + "sz_bar": "SZ-Bar", + "@sz_bar": { + "description": "Generated entry for translation for server strings" + }, + "seconds": "Seconden", + "@seconds": { + "description": "Generated entry for translation for server strings" + }, + "shoulders": "Schouders", + "@shoulders": { + "description": "Generated entry for translation for server strings" + }, + "swiss_ball": "Zwitserse Bal", + "@swiss_ball": { + "description": "Generated entry for translation for server strings" + }, + "triceps": "Triceps", + "@triceps": { + "description": "Generated entry for translation for server strings" + }, + "until_failure": "Tot Falen", + "@until_failure": { + "description": "Generated entry for translation for server strings" + }, + "kg": "kg", + "@kg": { + "description": "Generated entry for translation for server strings" + }, + "lb": "lb", + "@lb": { + "description": "Generated entry for translation for server strings" + }, + "none__bodyweight_exercise_": "geen (lichaamsgewicht)", + "@none__bodyweight_exercise_": { + "description": "Generated entry for translation for server strings" + }, + "log": "Vastleggen", + "@log": { + "description": "Log a specific meal (imperative form)" + }, + "done": "Klaar", + "@done": {}, + "overallChangeWeight": "Algemene verandering", + "@overallChangeWeight": { + "description": "Overall change in weight, added for localization" + }, + "goalTypeMeals": "Van maaltijden", + "@goalTypeMeals": { + "description": "added for localization of Class GoalType's filed meals" + }, + "goalTypeBasic": "Basic", + "@goalTypeBasic": { + "description": "added for localization of Class GoalType's filed basic" + }, + "goalTypeAdvanced": "Geavanceerd", + "@goalTypeAdvanced": { + "description": "added for localization of Class GoalType's filed advanced" + }, + "indicatorRaw": "rauw", + "@indicatorRaw": { + "description": "added for localization of Class Indicator's field text" + }, + "indicatorAvg": "gemiddeld", + "@indicatorAvg": { + "description": "added for localization of Class Indicator's field text" + }, + "endWorkout": "Beëindig workout", + "@endWorkout": { + "description": "Use the imperative, label on button to finish the current workout in gym mode" + }, + "themeMode": "Thema modus", + "@themeMode": {}, + "darkMode": "Altijd donkere modus", + "@darkMode": {}, + "lightMode": "Altijd lichte modus", + "@lightMode": {}, + "systemMode": "Systeem instellingen", + "@systemMode": {}, + "slotEntryTypeMyo": "Myo", + "@slotEntryTypeMyo": {} } From 4bfcde044ff56f2bdb64961298aebcea72600e0d Mon Sep 17 00:00:00 2001 From: Justin Pinheiro Date: Fri, 19 Dec 2025 12:13:08 +0100 Subject: [PATCH 14/48] Translated using Weblate (French) Currently translated at 100.0% (369 of 369 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/fr/ --- lib/l10n/app_fr.arb | 64 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 902d4c582..429c9e541 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -7,7 +7,7 @@ "@weight": { "description": "The weight of a workout log or body weight entry" }, - "confirmDelete": "Êtes-vous sûre de vouloir supprimer « {toDelete} » ?", + "confirmDelete": "Êtes-vous sûr de vouloir supprimer '{toDelete}' ?", "@confirmDelete": { "description": "Confirmation text before the user deletes an object", "type": "text", @@ -364,7 +364,7 @@ } } }, - "imageFormatNotSupportedDetail": "{imageFormat} non pris en charge", + "imageFormatNotSupportedDetail": "{imageFormat} pas encore pris en charge.", "@imageFormatNotSupportedDetail": { "description": "Label shown on the image preview container when image format is not supported", "type": "text", @@ -1126,5 +1126,63 @@ "enterTextInLanguage": "Veuillez saisir le texte dans la bonne langue !", "@enterTextInLanguage": {}, "endWorkout": "Terminer l'entraînement", - "@endWorkout": {} + "@endWorkout": {}, + "impressionGood": "Bonne", + "@impressionGood": {}, + "impressionNeutral": "Neutre", + "@impressionNeutral": {}, + "impressionBad": "Mauvaise", + "@impressionBad": {}, + "gymModeShowExercises": "Afficher les pages d'aperçu des exercices", + "@gymModeShowExercises": {}, + "gymModeShowTimer": "Afficher le chronomètre entre les séries", + "@gymModeShowTimer": {}, + "gymModeTimerType": "Type de chronomètre", + "@gymModeTimerType": {}, + "gymModeTimerTypeHelText": "Si une série a un temps de pause, un compte à rebours est toujours utilisé.", + "@gymModeTimerTypeHelText": {}, + "countdown": "Compte à rebours", + "@countdown": {}, + "stopwatch": "Chronomètre", + "@stopwatch": {}, + "gymModeDefaultCountdownTime": "Temps de compte à rebours par défaut, en secondes", + "@gymModeDefaultCountdownTime": {}, + "gymModeNotifyOnCountdownFinish": "Notifier à la fin du compte à rebours", + "@gymModeNotifyOnCountdownFinish": {}, + "duration": "Durée", + "@duration": {}, + "durationHoursMinutes": "{hours}h {minutes}m", + "@durationHoursMinutes": { + "description": "A duration, in hours and minutes", + "type": "text", + "placeholders": { + "hours": { + "type": "int" + }, + "minutes": { + "type": "int" + } + } + }, + "volume": "Volume", + "@volume": { + "description": "The volume of a workout or set, i.e. weight x reps" + }, + "workoutCompleted": "Entraînement terminé", + "@workoutCompleted": {}, + "formMinMaxValues": "Veuillez entrer une valeur entre {min} et {max}", + "@formMinMaxValues": { + "description": "Error message when the user needs to enter a value between min and max", + "type": "text", + "placeholders": { + "min": { + "type": "int" + }, + "max": { + "type": "int" + } + } + }, + "superset": "Superset", + "@superset": {} } From a06dca5eee9101dccefb98cb5b40740f4e92968e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 23 Dec 2025 15:50:32 +0100 Subject: [PATCH 15/48] Fix variable name --- lib/l10n/app_nl.arb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 449807d2e..031e49e31 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -942,7 +942,7 @@ "@variations": { "description": "Variations of one exercise (e.g. benchpress and benchpress narrow)" }, - "alsoKnownAs": "Ook bekend als: {aliassen}", + "alsoKnownAs": "Ook bekend als: {aliases}", "@alsoKnownAs": { "placeholders": { "aliases": { From 54a2f0c2bc9e7b0f86291b3f030b86ddb56d2d1e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 23 Dec 2025 15:58:18 +0100 Subject: [PATCH 16/48] Bump versions in Gemfile.lock --- Gemfile.lock | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index cf6854755..1d7388fd4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -8,8 +8,8 @@ GEM artifactory (3.0.17) atomos (0.1.3) aws-eventstream (1.4.0) - aws-partitions (1.1194.0) - aws-sdk-core (3.239.2) + aws-partitions (1.1198.0) + aws-sdk-core (3.240.0) aws-eventstream (~> 1, >= 1.3.0) aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) @@ -20,7 +20,7 @@ GEM aws-sdk-kms (1.118.0) aws-sdk-core (~> 3, >= 3.239.1) aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.207.0) + aws-sdk-s3 (1.208.0) aws-sdk-core (~> 3, >= 3.234.0) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) @@ -28,7 +28,7 @@ GEM aws-eventstream (~> 1, >= 1.0.2) babosa (1.0.4) base64 (0.2.0) - bigdecimal (3.3.1) + bigdecimal (4.0.1) claide (1.1.0) colored (1.2) colored2 (3.1.2) @@ -71,7 +71,7 @@ GEM faraday_middleware (1.2.1) faraday (~> 1.0) fastimage (2.4.0) - fastlane (2.229.1) + fastlane (2.230.0) CFPropertyList (>= 2.3, < 4.0.0) abbrev (~> 0.1.2) addressable (>= 2.8, < 3.0.0) @@ -100,6 +100,7 @@ GEM http-cookie (~> 1.0.5) json (< 3.0.0) jwt (>= 2.1.0, < 3) + logger (>= 1.6, < 2.0) mini_magick (>= 4.9.4, < 5.0.0) multipart-post (>= 2.0.0, < 3.0.0) mutex_m (~> 0.3.0) From ed5ab7613be81e02fbaf94139e2d9c5f8c3a3c1a Mon Sep 17 00:00:00 2001 From: Github-Actions Date: Tue, 23 Dec 2025 15:07:35 +0000 Subject: [PATCH 17/48] Bump version to 1.9.4 --- flatpak/de.wger.flutter.metainfo.xml | 6 ++++++ pubspec.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/flatpak/de.wger.flutter.metainfo.xml b/flatpak/de.wger.flutter.metainfo.xml index ab5aadb70..8560be108 100755 --- a/flatpak/de.wger.flutter.metainfo.xml +++ b/flatpak/de.wger.flutter.metainfo.xml @@ -84,6 +84,12 @@ + + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/1.9.4 +

Bug fixes and improvements.

diff --git a/pubspec.yaml b/pubspec.yaml index e70eb6c65..df97a9979 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -21,7 +21,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # - the version number is taken from the git tag vX.Y.Z # - the build number is computed by reading the last one from the play store # and increasing by one -version: 1.9.3+130 +version: 1.9.4+140 environment: sdk: '>=3.8.0 <4.0.0' From 994c962921ff3ec40f208bca1f18dd59d0b759cb Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 28 Dec 2025 14:09:42 +0100 Subject: [PATCH 18/48] Bump flatpak-flutter version --- .github/workflows/build-linux.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index 989036b0d..b24ac7f33 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -62,7 +62,7 @@ jobs: - name: Bump version and update manifest run: | - git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.7.5 ../flatpak-flutter + git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.10.0 ../flatpak-flutter pip install -r ../flatpak-flutter/requirements.txt python bump-wger-version.py ${{ inputs.ref }} ../flatpak-flutter/flatpak-flutter.py --app-module wger flatpak-flutter.json From 16ea5233bc9bd9fed2935ea436317efcb50d829d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 5 Jan 2026 00:03:33 +0000 Subject: [PATCH 19/48] Bump equatable from 2.0.7 to 2.0.8 Bumps [equatable](https://github.com/felangel/equatable) from 2.0.7 to 2.0.8. - [Release notes](https://github.com/felangel/equatable/releases) - [Changelog](https://github.com/felangel/equatable/blob/master/CHANGELOG.md) - [Commits](https://github.com/felangel/equatable/compare/v2.0.7...v2.0.8) --- updated-dependencies: - dependency-name: equatable dependency-version: 2.0.8 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pubspec.lock | 4 ++-- pubspec.yaml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 6b29145d1..9cabd59f6 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -333,10 +333,10 @@ packages: dependency: "direct main" description: name: equatable - sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7" + sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b" url: "https://pub.dev" source: hosted - version: "2.0.7" + version: "2.0.8" fake_async: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index df97a9979..e28e0f82f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -37,7 +37,7 @@ dependencies: collection: ^1.18.0 cupertino_icons: ^1.0.8 drift: ^2.30.0 - equatable: ^2.0.7 + equatable: ^2.0.8 fl_chart: ^1.1.1 flex_color_scheme: ^8.3.1 flutter_html: ^3.0.0 From 696b3333fb5045c76d46f194df839835e3ab0450 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 10 Jan 2026 12:57:52 +0100 Subject: [PATCH 20/48] Only show the progression bar for uncompleted trophies --- lib/widgets/trophies/trophies_overview.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/widgets/trophies/trophies_overview.dart b/lib/widgets/trophies/trophies_overview.dart index d763e9460..2b06f3405 100644 --- a/lib/widgets/trophies/trophies_overview.dart +++ b/lib/widgets/trophies/trophies_overview.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team + * Copyright (c) 2025 - 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 @@ -158,7 +158,7 @@ class _TrophyCardImage extends StatelessWidget { ), const SizedBox(height: 8), - if (userProgression.trophy.isProgressive) + if (userProgression.trophy.isProgressive && !userProgression.isEarned) Tooltip( message: 'Progress: ${userProgression.progressDisplay}', child: SizedBox( From 352a4b1c49b8051a982fb40ebd9bd43c66e8ae33 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 10 Jan 2026 14:02:23 +0100 Subject: [PATCH 21/48] Also show the PR trophies in the regular log page --- lib/providers/trophies.dart | 82 ++++++++--- lib/providers/trophies.g.dart | 27 ++-- lib/screens/home_tabs_screen.dart | 22 +-- lib/screens/routine_logs_screen.dart | 4 +- lib/widgets/dashboard/widgets/trophies.dart | 83 +++++------ lib/widgets/routines/gym_mode/log_page.dart | 2 +- lib/widgets/routines/gym_mode/summary.dart | 13 +- .../routines/logs/day_logs_container.dart | 48 ++++++- .../routines/logs/log_overview_routine.dart | 14 +- lib/widgets/trophies/trophies_overview.dart | 74 ++++------ test/routine/routine_logs_screen_test.dart | 55 ++++--- .../routine_logs_screen_test.mocks.dart | 108 ++++++++++++++ .../dashboard_trophies_widget_test.dart | 22 +-- .../dashboard_trophies_widget_test.mocks.dart | 135 ------------------ .../widgets/trophies_overview_test.dart | 23 ++- .../widgets/trophies_overview_test.mocks.dart | 135 ------------------ .../routines/gym_mode/log_page_test.dart | 16 +-- 17 files changed, 377 insertions(+), 486 deletions(-) delete mode 100644 test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart delete mode 100644 test/trophies/widgets/trophies_overview_test.mocks.dart diff --git a/lib/providers/trophies.dart b/lib/providers/trophies.dart index 183a8fdec..19289af58 100644 --- a/lib/providers/trophies.dart +++ b/lib/providers/trophies.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team + * 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 @@ -28,6 +28,38 @@ import 'base_provider.dart'; part 'trophies.g.dart'; +class TrophyState { + final _logger = Logger('TrophyState'); + + final List trophies; + final List userTrophies; + final List trophyProgression; + + TrophyState({ + this.trophies = const [], + this.userTrophies = const [], + this.trophyProgression = const [], + }); + + TrophyState copyWith({ + List? trophies, + List? userTrophies, + List? trophyProgression, + }) { + return TrophyState( + trophies: trophies ?? this.trophies, + userTrophies: userTrophies ?? this.userTrophies, + trophyProgression: trophyProgression ?? this.trophyProgression, + ); + } + + List get prTrophies => + userTrophies.where((t) => t.trophy.type == TrophyType.pr).toList(); + + List get nonPrTrophies => + userTrophies.where((t) => t.trophy.type != TrophyType.pr).toList(); +} + class TrophyRepository { final _logger = Logger('TrophyRepository'); @@ -96,40 +128,52 @@ TrophyRepository trophyRepository(Ref ref) { @Riverpod(keepAlive: true) final class TrophyStateNotifier extends _$TrophyStateNotifier { + final _logger = Logger('TrophyStateNotifier'); + @override - void build() {} + TrophyState build() { + return TrophyState(); + } + + Future fetchAll({String? language}) async { + await Future.wait([ + fetchTrophies(language: language), + fetchUserTrophies(language: language), + fetchTrophyProgression(language: language), + ]); + } /// Fetch all available trophies - Future> fetchTrophies() async { + Future> fetchTrophies({String? language}) async { + _logger.finer('Fetching trophies'); + final repo = ref.read(trophyRepositoryProvider); - return repo.fetchTrophies(); + final result = await repo.fetchTrophies(language: language); + state = state.copyWith(trophies: result); + return result; } - /// Fetch trophies awarded to the user. - /// Excludes hidden trophies as well as repeatable (PR) trophies since they are - /// handled separately + /// Fetch trophies awarded to the user, excludes hidden trophies Future> fetchUserTrophies({String? language}) async { - final repo = ref.read(trophyRepositoryProvider); - return repo.fetchUserTrophies( - filterQuery: {'trophy__is_hidden': 'false', 'trophy__is_repeatable': 'false'}, - language: language, - ); - } + _logger.finer('Fetching user trophies'); - /// Fetch PR trophies awarded to the user - Future> fetchUserPRTrophies({String? language}) async { final repo = ref.read(trophyRepositoryProvider); - return repo.fetchUserTrophies( - filterQuery: {'trophy__trophy_type': TrophyType.pr.name}, + final result = await repo.fetchUserTrophies( + filterQuery: {'trophy__is_hidden': 'false'}, //'trophy__is_repeatable': 'false' language: language, ); + state = state.copyWith(userTrophies: result); + return result; } /// Fetch trophy progression for the user Future> fetchTrophyProgression({String? language}) async { - final repo = ref.read(trophyRepositoryProvider); + _logger.finer('Fetching user trophy progression'); // Note that repeatable trophies are filtered out in the backend - return repo.fetchProgression(language: language); + final repo = ref.read(trophyRepositoryProvider); + final result = await repo.fetchProgression(language: language); + state = state.copyWith(trophyProgression: result); + return result; } } diff --git a/lib/providers/trophies.g.dart b/lib/providers/trophies.g.dart index 88f47d587..2f2a95e8f 100644 --- a/lib/providers/trophies.g.dart +++ b/lib/providers/trophies.g.dart @@ -53,7 +53,8 @@ String _$trophyRepositoryHash() => r'0699f0c0f7f324f3ba9b21420d9845a3e3096b61'; @ProviderFor(TrophyStateNotifier) const trophyStateProvider = TrophyStateNotifierProvider._(); -final class TrophyStateNotifierProvider extends $NotifierProvider { +final class TrophyStateNotifierProvider + extends $NotifierProvider { const TrophyStateNotifierProvider._() : super( from: null, @@ -73,25 +74,31 @@ final class TrophyStateNotifierProvider extends $NotifierProvider TrophyStateNotifier(); /// {@macro riverpod.override_with_value} - Override overrideWithValue(void value) { + Override overrideWithValue(TrophyState value) { return $ProviderOverride( origin: this, - providerOverride: $SyncValueProvider(value), + providerOverride: $SyncValueProvider(value), ); } } -String _$trophyStateNotifierHash() => r'47b4babf337bbb8bf60142ebe59dc760fa08dce3'; +String _$trophyStateNotifierHash() => r'c80c732272cf843b698f28152f60b9a5f37ee449'; -abstract class _$TrophyStateNotifier extends $Notifier { - void build(); +abstract class _$TrophyStateNotifier extends $Notifier { + TrophyState build(); @$mustCallSuper @override void runBuild() { - build(); - final ref = this.ref as $Ref; + final created = build(); + final ref = this.ref as $Ref; final element = - ref.element as $ClassProviderElement, void, Object?, Object?>; - element.handleValue(ref, null); + ref.element + as $ClassProviderElement< + AnyNotifier, + TrophyState, + Object?, + Object? + >; + element.handleValue(ref, created); } } diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index ebb703985..10de168f7 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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 @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:logging/logging.dart'; import 'package:provider/provider.dart'; @@ -30,6 +31,7 @@ import 'package:wger/providers/gallery.dart'; import 'package:wger/providers/measurement.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/trophies.dart'; import 'package:wger/providers/user.dart'; import 'package:wger/screens/dashboard.dart'; import 'package:wger/screens/gallery_screen.dart'; @@ -37,7 +39,7 @@ import 'package:wger/screens/nutritional_plans_screen.dart'; import 'package:wger/screens/routine_list_screen.dart'; import 'package:wger/screens/weight_screen.dart'; -class HomeTabsScreen extends StatefulWidget { +class HomeTabsScreen extends ConsumerStatefulWidget { final _logger = Logger('HomeTabsScreen'); HomeTabsScreen(); @@ -48,25 +50,20 @@ class HomeTabsScreen extends StatefulWidget { _HomeTabsScreenState createState() => _HomeTabsScreenState(); } -class _HomeTabsScreenState extends State with SingleTickerProviderStateMixin { - late Future _initialData; +class _HomeTabsScreenState extends ConsumerState + with SingleTickerProviderStateMixin { + Future? _initialData; bool _errorHandled = false; int _selectedIndex = 0; bool _isWideScreen = false; - @override - void initState() { - super.initState(); - // Loading data here, since the build method can be called more than once - _initialData = _loadEntries(); - } - @override void didChangeDependencies() { super.didChangeDependencies(); final size = MediaQuery.sizeOf(context); _isWideScreen = size.width > MATERIAL_XS_BREAKPOINT; + _initialData ??= _loadEntries(); } void _onItemTapped(int index) { @@ -85,7 +82,9 @@ class _HomeTabsScreenState extends State with SingleTickerProvid /// Load initial data from the server Future _loadEntries() async { + final languageCode = Localizations.localeOf(context).languageCode; final authProvider = context.read(); + final trophyNotifier = ref.read(trophyStateProvider.notifier); if (!authProvider.dataInit) { final routinesProvider = context.read(); @@ -127,6 +126,7 @@ class _HomeTabsScreenState extends State with SingleTickerProvid // routinesProvider.fetchAndSetAllRoutinesFull(), weightProvider.fetchAndSetEntries(), measurementProvider.fetchAndSetAllCategoriesAndEntries(), + trophyNotifier.fetchAll(language: languageCode), ]); // diff --git a/lib/screens/routine_logs_screen.dart b/lib/screens/routine_logs_screen.dart index 93da5d5c1..c9909b1ff 100644 --- a/lib/screens/routine_logs_screen.dart +++ b/lib/screens/routine_logs_screen.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * Copyright (c) 2020 - 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. diff --git a/lib/widgets/dashboard/widgets/trophies.dart b/lib/widgets/dashboard/widgets/trophies.dart index 3e39fd451..e164e5d5b 100644 --- a/lib/widgets/dashboard/widgets/trophies.dart +++ b/lib/widgets/dashboard/widgets/trophies.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -21,64 +21,45 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/models/trophies/trophy.dart'; import 'package:wger/providers/trophies.dart'; import 'package:wger/screens/trophy_screen.dart'; -import 'package:wger/widgets/core/progress_indicator.dart'; class DashboardTrophiesWidget extends ConsumerWidget { const DashboardTrophiesWidget(); @override Widget build(BuildContext context, WidgetRef ref) { - final provider = ref.watch(trophyStateProvider.notifier); - final languageCode = Localizations.localeOf(context).languageCode; + final trophiesState = ref.read(trophyStateProvider); - return FutureBuilder( - future: provider.fetchUserTrophies(language: languageCode), - builder: (context, asyncSnapshot) { - if (asyncSnapshot.connectionState != ConnectionState.done) { - return const Card(child: BoxedProgressIndicator()); - } + return Card( + color: Colors.transparent, + shadowColor: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (trophiesState.nonPrTrophies.isEmpty) + Padding( + padding: const EdgeInsets.all(16.0), + child: Text('No trophies yet', style: Theme.of(context).textTheme.bodyMedium), + ) + else + SizedBox( + height: 140, + child: ListView.separated( + padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), + scrollDirection: Axis.horizontal, + itemCount: trophiesState.nonPrTrophies.length, + separatorBuilder: (context, index) => const SizedBox(width: 12), + itemBuilder: (context, index) { + final userTrophy = trophiesState.nonPrTrophies[index]; - final userTrophies = asyncSnapshot.data ?? []; - - return Card( - color: Colors.transparent, - shadowColor: Colors.transparent, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // ListTile( - // title: Text( - // 'Trophies', - // style: Theme.of(context).textTheme.headlineSmall, - // ), - // ), - if (userTrophies.isEmpty) - Padding( - padding: const EdgeInsets.all(16.0), - child: Text('No trophies yet', style: Theme.of(context).textTheme.bodyMedium), - ) - else - SizedBox( - height: 140, - child: ListView.separated( - padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), - scrollDirection: Axis.horizontal, - itemCount: userTrophies.length, - separatorBuilder: (context, index) => const SizedBox(width: 12), - itemBuilder: (context, index) { - final userTrophy = userTrophies[index]; - - return SizedBox( - width: 220, - child: TrophyCard(trophy: userTrophy.trophy), - ); - }, - ), - ), - ], - ), - ); - }, + return SizedBox( + width: 220, + child: TrophyCard(trophy: userTrophy.trophy), + ); + }, + ), + ), + ], + ), ); } } diff --git a/lib/widgets/routines/gym_mode/log_page.dart b/lib/widgets/routines/gym_mode/log_page.dart index 10cf7e649..c3c99efbb 100644 --- a/lib/widgets/routines/gym_mode/log_page.dart +++ b/lib/widgets/routines/gym_mode/log_page.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 diff --git a/lib/widgets/routines/gym_mode/summary.dart b/lib/widgets/routines/gym_mode/summary.dart index 146b15c57..e50975008 100644 --- a/lib/widgets/routines/gym_mode/summary.dart +++ b/lib/widgets/routines/gym_mode/summary.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -49,7 +49,6 @@ class WorkoutSummary extends ConsumerStatefulWidget { class _WorkoutSummaryState extends ConsumerState { late Future _initData; late Routine _routine; - late List _userPrTrophies; bool _didInit = false; @override @@ -76,11 +75,13 @@ class _WorkoutSummaryState extends ConsumerState { ); final trophyNotifier = ref.read(trophyStateProvider.notifier); - _userPrTrophies = await trophyNotifier.fetchUserPRTrophies(language: languageCode); + await trophyNotifier.fetchUserTrophies(language: languageCode); } @override Widget build(BuildContext context) { + final trophyState = ref.watch(trophyStateProvider); + return Column( children: [ NavigationHeader( @@ -102,10 +103,8 @@ class _WorkoutSummaryState extends ConsumerState { final apiSession = _routine.sessions.firstWhereOrNull( (s) => s.session.date.isSameDayAs(clock.now()), ); - final userTrophies = _userPrTrophies - .where( - (t) => t.contextData!.sessionId == apiSession?.session.id, - ) + final userTrophies = trophyState.prTrophies + .where((t) => t.contextData?.sessionId == apiSession?.session.id) .toList(); return WorkoutSessionStats( diff --git a/lib/widgets/routines/logs/day_logs_container.dart b/lib/widgets/routines/logs/day_logs_container.dart index 49d829b06..ed3ac3a41 100644 --- a/lib/widgets/routines/logs/day_logs_container.dart +++ b/lib/widgets/routines/logs/day_logs_container.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 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 @@ -17,33 +17,59 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:logging/logging.dart'; import 'package:wger/helpers/date.dart'; import 'package:wger/helpers/errors.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/workouts/routine.dart'; +import 'package:wger/providers/trophies.dart'; +import '../gym_mode/summary.dart'; import 'exercise_log_chart.dart'; import 'muscle_groups.dart'; import 'session_info.dart'; -class DayLogWidget extends StatelessWidget { +class DayLogWidget extends ConsumerWidget { final DateTime _date; final Routine _routine; + final _logger = Logger('DayLogWidget'); - const DayLogWidget(this._date, this._routine); + DayLogWidget(this._date, this._routine); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); + + final trophyState = ref.read(trophyStateProvider); + final sessionApi = _routine.sessions.firstWhere( (sessionApi) => sessionApi.session.date.isSameDayAs(_date), ); final exercises = sessionApi.exercises; + final prTrophies = trophyState.prTrophies + .where((t) => t.contextData?.sessionId == sessionApi.session.id) + .toList(); + + _logger.info(trophyState.prTrophies); + _logger.info(prTrophies); + return Column( spacing: 10, children: [ Card(child: SessionInfo(sessionApi.session)), + if (prTrophies.isNotEmpty) + SizedBox( + width: double.infinity, + child: InfoCard( + title: i18n.personalRecords, + value: prTrophies.length.toString(), + color: theme.colorScheme.tertiaryContainer, + ), + ), MuscleGroupsCard(sessionApi.logs), - Column( spacing: 10, children: [ @@ -66,7 +92,17 @@ class DayLogWidget extends StatelessWidget { (log) => Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text(log.repTextNoNl(context)), + Row( + children: [ + if (prTrophies.any((t) => t.contextData?.logId == log.id)) + Icon( + Icons.emoji_events, + color: theme.colorScheme.primary, + size: 20, + ), + Text(log.repTextNoNl(context)), + ], + ), IconButton( icon: const Icon(Icons.delete), key: ValueKey('delete-log-${log.id}'), diff --git a/lib/widgets/routines/logs/log_overview_routine.dart b/lib/widgets/routines/logs/log_overview_routine.dart index dfcfc1aa4..34f0be5ad 100644 --- a/lib/widgets/routines/logs/log_overview_routine.dart +++ b/lib/widgets/routines/logs/log_overview_routine.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -18,20 +18,26 @@ import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:table_calendar/table_calendar.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/workouts/routine.dart'; +import 'package:wger/providers/trophies.dart'; import 'package:wger/theme/theme.dart'; import 'package:wger/widgets/routines/logs/day_logs_container.dart'; -class WorkoutLogs extends StatelessWidget { +class WorkoutLogs extends ConsumerWidget { final Routine _routine; const WorkoutLogs(this._routine); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + final languageCode = Localizations.localeOf(context).languageCode; + final trophyNotifier = ref.read(trophyStateProvider.notifier); + trophyNotifier.fetchUserTrophies(language: languageCode); + return ListView( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 8), children: [ diff --git a/lib/widgets/trophies/trophies_overview.dart b/lib/widgets/trophies/trophies_overview.dart index 2b06f3405..706040dfa 100644 --- a/lib/widgets/trophies/trophies_overview.dart +++ b/lib/widgets/trophies/trophies_overview.dart @@ -21,15 +21,13 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/helpers/material.dart'; import 'package:wger/models/trophies/user_trophy_progression.dart'; import 'package:wger/providers/trophies.dart'; -import 'package:wger/widgets/core/progress_indicator.dart'; class TrophiesOverview extends ConsumerWidget { const TrophiesOverview({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { - final notifier = ref.watch(trophyStateProvider.notifier); - final languageCode = Localizations.localeOf(context).languageCode; + final trophyState = ref.watch(trophyStateProvider); // Responsive grid: determine columns based on screen width final width = MediaQuery.widthOf(context); @@ -44,52 +42,32 @@ class TrophiesOverview extends ConsumerWidget { crossAxisCount = 5; } - return FutureBuilder>( - future: notifier.fetchTrophyProgression(language: languageCode), - builder: (context, snapshot) { - if (snapshot.connectionState != ConnectionState.done) { - return const Card(child: BoxedProgressIndicator()); - } - - if (snapshot.hasError) { - return Center( - child: Padding( - padding: const EdgeInsets.all(16.0), - child: Text('Error loading trophies', style: Theme.of(context).textTheme.bodyLarge), - ), - ); - } - - final userTrophyProgression = snapshot.data ?? []; - - // If empty, show placeholder - if (userTrophyProgression.isEmpty) { - return Center( - child: Padding( - padding: const EdgeInsets.all(16.0), - child: Text( - 'No trophies yet', - style: Theme.of(context).textTheme.bodyLarge, - textAlign: TextAlign.center, - ), - ), - ); - } - - return RepaintBoundary( - child: GridView.builder( - padding: const EdgeInsets.all(12), - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: crossAxisCount, - ), - key: const ValueKey('trophy-grid'), - itemCount: userTrophyProgression.length, - itemBuilder: (context, index) { - return _TrophyCardImage(userProgression: userTrophyProgression[index]); - }, + // If empty, show placeholder + if (trophyState.trophyProgression.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Text( + 'No trophies yet', + style: Theme.of(context).textTheme.bodyLarge, + textAlign: TextAlign.center, ), - ); - }, + ), + ); + } + + return RepaintBoundary( + child: GridView.builder( + padding: const EdgeInsets.all(12), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: crossAxisCount, + ), + key: const ValueKey('trophy-grid'), + itemCount: trophyState.trophyProgression.length, + itemBuilder: (context, index) { + return _TrophyCardImage(userProgression: trophyState.trophyProgression[index]); + }, + ), ); } } diff --git a/test/routine/routine_logs_screen_test.dart b/test/routine/routine_logs_screen_test.dart index c61bdf3a6..1081171c7 100644 --- a/test/routine/routine_logs_screen_test.dart +++ b/test/routine/routine_logs_screen_test.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -20,6 +20,7 @@ import 'dart:io'; import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -27,14 +28,16 @@ import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/workouts/routine.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/trophies.dart'; import 'package:wger/screens/routine_logs_screen.dart'; import 'package:wger/screens/routine_screen.dart'; import 'package:wger/widgets/routines/logs/log_overview_routine.dart'; import '../../test_data/routines.dart'; +import '../test_data/trophies.dart'; import 'routine_logs_screen_test.mocks.dart'; -@GenerateMocks([RoutinesProvider]) +@GenerateMocks([RoutinesProvider, TrophyRepository]) void main() { late Routine routine; final mockRoutinesProvider = MockRoutinesProvider(); @@ -49,25 +52,39 @@ void main() { Widget renderWidget({locale = 'en'}) { final key = GlobalKey(); - return ChangeNotifierProvider( - create: (context) => mockRoutinesProvider, - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - navigatorKey: key, - home: TextButton( - onPressed: () => key.currentState!.push( - MaterialPageRoute( - settings: RouteSettings(arguments: routine.id), - builder: (_) => const WorkoutLogsScreen(), + // Arrange + final mockRepository = MockTrophyRepository(); + when( + mockRepository.fetchUserTrophies( + filterQuery: anyNamed('filterQuery'), + language: anyNamed('language'), + ), + ).thenAnswer((_) async => getUserTrophies()); + + return ProviderScope( + overrides: [ + trophyRepositoryProvider.overrideWithValue(mockRepository), + ], + child: ChangeNotifierProvider( + create: (context) => mockRoutinesProvider, + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + navigatorKey: key, + home: TextButton( + onPressed: () => key.currentState!.push( + MaterialPageRoute( + settings: RouteSettings(arguments: routine.id), + builder: (_) => const WorkoutLogsScreen(), + ), ), + child: const SizedBox(), ), - child: const SizedBox(), + routes: { + RoutineScreen.routeName: (ctx) => const WorkoutLogsScreen(), + }, ), - routes: { - RoutineScreen.routeName: (ctx) => const WorkoutLogsScreen(), - }, ), ); } diff --git a/test/routine/routine_logs_screen_test.mocks.dart b/test/routine/routine_logs_screen_test.mocks.dart index dca48e937..015095bb0 100644 --- a/test/routine/routine_logs_screen_test.mocks.dart +++ b/test/routine/routine_logs_screen_test.mocks.dart @@ -9,6 +9,9 @@ import 'dart:ui' as _i17; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i16; import 'package:wger/models/exercises/exercise.dart' as _i15; +import 'package:wger/models/trophies/trophy.dart' as _i19; +import 'package:wger/models/trophies/user_trophy.dart' as _i20; +import 'package:wger/models/trophies/user_trophy_progression.dart' as _i21; import 'package:wger/models/workouts/base_config.dart' as _i9; import 'package:wger/models/workouts/day.dart' as _i6; import 'package:wger/models/workouts/day_data.dart' as _i14; @@ -21,6 +24,7 @@ import 'package:wger/models/workouts/slot_entry.dart' as _i8; import 'package:wger/models/workouts/weight_unit.dart' as _i3; import 'package:wger/providers/base_provider.dart' as _i2; import 'package:wger/providers/routines.dart' as _i12; +import 'package:wger/providers/trophies.dart' as _i18; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -592,3 +596,107 @@ class MockRoutinesProvider extends _i1.Mock implements _i12.RoutinesProvider { returnValueForMissingStub: null, ); } + +/// A class which mocks [TrophyRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockTrophyRepository extends _i1.Mock implements _i18.TrophyRepository { + MockTrophyRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.WgerBaseProvider get base => + (super.noSuchMethod( + Invocation.getter(#base), + returnValue: _FakeWgerBaseProvider_0( + this, + Invocation.getter(#base), + ), + ) + as _i2.WgerBaseProvider); + + @override + String get trophiesPath => + (super.noSuchMethod( + Invocation.getter(#trophiesPath), + returnValue: _i16.dummyValue( + this, + Invocation.getter(#trophiesPath), + ), + ) + as String); + + @override + String get userTrophiesPath => + (super.noSuchMethod( + Invocation.getter(#userTrophiesPath), + returnValue: _i16.dummyValue( + this, + Invocation.getter(#userTrophiesPath), + ), + ) + as String); + + @override + String get userTrophyProgressionPath => + (super.noSuchMethod( + Invocation.getter(#userTrophyProgressionPath), + returnValue: _i16.dummyValue( + this, + Invocation.getter(#userTrophyProgressionPath), + ), + ) + as String); + + @override + _i13.Future> fetchTrophies({String? language}) => + (super.noSuchMethod( + Invocation.method(#fetchTrophies, [], {#language: language}), + returnValue: _i13.Future>.value(<_i19.Trophy>[]), + ) + as _i13.Future>); + + @override + _i13.Future> fetchUserTrophies({ + Map? filterQuery, + String? language, + }) => + (super.noSuchMethod( + Invocation.method(#fetchUserTrophies, [], { + #filterQuery: filterQuery, + #language: language, + }), + returnValue: _i13.Future>.value( + <_i20.UserTrophy>[], + ), + ) + as _i13.Future>); + + @override + _i13.Future> fetchProgression({ + Map? filterQuery, + String? language, + }) => + (super.noSuchMethod( + Invocation.method(#fetchProgression, [], { + #filterQuery: filterQuery, + #language: language, + }), + returnValue: _i13.Future>.value( + <_i21.UserTrophyProgression>[], + ), + ) + as _i13.Future>); + + @override + List<_i19.Trophy> filterByType( + List<_i19.Trophy>? list, + _i19.TrophyType? type, + ) => + (super.noSuchMethod( + Invocation.method(#filterByType, [list, type]), + returnValue: <_i19.Trophy>[], + ) + as List<_i19.Trophy>); +} diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.dart b/test/trophies/widgets/dashboard_trophies_widget_test.dart index bf4209b49..687f13a06 100644 --- a/test/trophies/widgets/dashboard_trophies_widget_test.dart +++ b/test/trophies/widgets/dashboard_trophies_widget_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team + * 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 @@ -19,33 +19,25 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; import 'package:network_image_mock/network_image_mock.dart'; import 'package:wger/providers/trophies.dart'; import 'package:wger/widgets/dashboard/widgets/trophies.dart'; import '../../test_data/trophies.dart'; -import 'dashboard_trophies_widget_test.mocks.dart'; -@GenerateMocks([TrophyRepository]) void main() { testWidgets('DashboardTrophiesWidget shows trophies', (WidgetTester tester) async { - // Arrange - final mockRepository = MockTrophyRepository(); - when( - mockRepository.fetchUserTrophies( - filterQuery: anyNamed('filterQuery'), - language: anyNamed('language'), - ), - ).thenAnswer((_) async => getUserTrophies()); - // Act await mockNetworkImagesFor(() async { await tester.pumpWidget( ProviderScope( overrides: [ - trophyRepositoryProvider.overrideWithValue(mockRepository), + trophyStateProvider.overrideWithValue( + TrophyState( + userTrophies: getUserTrophies(), + trophies: getTestTrophies(), + ), + ), ], child: const MaterialApp( home: Scaffold( diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart b/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart deleted file mode 100644 index 41544f94f..000000000 --- a/test/trophies/widgets/dashboard_trophies_widget_test.mocks.dart +++ /dev/null @@ -1,135 +0,0 @@ -// Mocks generated by Mockito 5.4.6 from annotations -// in wger/test/trophies/widgets/dashboard_trophies_widget_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i5; - -import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i4; -import 'package:wger/models/trophies/trophy.dart' as _i6; -import 'package:wger/models/trophies/user_trophy.dart' as _i7; -import 'package:wger/models/trophies/user_trophy_progression.dart' as _i8; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/trophies.dart' as _i3; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: must_be_immutable -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class -// ignore_for_file: invalid_use_of_internal_member - -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -/// A class which mocks [TrophyRepository]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { - MockTrophyRepository() { - _i1.throwOnMissingStub(this); - } - - @override - _i2.WgerBaseProvider get base => - (super.noSuchMethod( - Invocation.getter(#base), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#base), - ), - ) - as _i2.WgerBaseProvider); - - @override - String get trophiesPath => - (super.noSuchMethod( - Invocation.getter(#trophiesPath), - returnValue: _i4.dummyValue( - this, - Invocation.getter(#trophiesPath), - ), - ) - as String); - - @override - String get userTrophiesPath => - (super.noSuchMethod( - Invocation.getter(#userTrophiesPath), - returnValue: _i4.dummyValue( - this, - Invocation.getter(#userTrophiesPath), - ), - ) - as String); - - @override - String get userTrophyProgressionPath => - (super.noSuchMethod( - Invocation.getter(#userTrophyProgressionPath), - returnValue: _i4.dummyValue( - this, - Invocation.getter(#userTrophyProgressionPath), - ), - ) - as String); - - @override - _i5.Future> fetchTrophies({String? language}) => - (super.noSuchMethod( - Invocation.method(#fetchTrophies, [], {#language: language}), - returnValue: _i5.Future>.value(<_i6.Trophy>[]), - ) - as _i5.Future>); - - @override - _i5.Future> fetchUserTrophies({ - Map? filterQuery, - String? language, - }) => - (super.noSuchMethod( - Invocation.method(#fetchUserTrophies, [], { - #filterQuery: filterQuery, - #language: language, - }), - returnValue: _i5.Future>.value( - <_i7.UserTrophy>[], - ), - ) - as _i5.Future>); - - @override - _i5.Future> fetchProgression({ - Map? filterQuery, - String? language, - }) => - (super.noSuchMethod( - Invocation.method(#fetchProgression, [], { - #filterQuery: filterQuery, - #language: language, - }), - returnValue: _i5.Future>.value( - <_i8.UserTrophyProgression>[], - ), - ) - as _i5.Future>); - - @override - List<_i6.Trophy> filterByType(List<_i6.Trophy>? list, _i6.TrophyType? type) => - (super.noSuchMethod( - Invocation.method(#filterByType, [list, type]), - returnValue: <_i6.Trophy>[], - ) - as List<_i6.Trophy>); -} diff --git a/test/trophies/widgets/trophies_overview_test.dart b/test/trophies/widgets/trophies_overview_test.dart index 2c6b71f5a..0bc12cd5e 100644 --- a/test/trophies/widgets/trophies_overview_test.dart +++ b/test/trophies/widgets/trophies_overview_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team + * 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 @@ -19,33 +19,26 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; import 'package:network_image_mock/network_image_mock.dart'; import 'package:wger/providers/trophies.dart'; import 'package:wger/widgets/trophies/trophies_overview.dart'; import '../../test_data/trophies.dart'; -import 'dashboard_trophies_widget_test.mocks.dart'; -@GenerateMocks([TrophyRepository]) void main() { testWidgets('TrophiesOverview shows trophies', (WidgetTester tester) async { - // Arrange - final mockRepository = MockTrophyRepository(); - when( - mockRepository.fetchProgression( - filterQuery: anyNamed('filterQuery'), - language: anyNamed('language'), - ), - ).thenAnswer((_) async => getUserTrophyProgression()); - // Act await mockNetworkImagesFor(() async { await tester.pumpWidget( ProviderScope( overrides: [ - trophyRepositoryProvider.overrideWithValue(mockRepository), + trophyStateProvider.overrideWithValue( + TrophyState( + trophyProgression: getUserTrophyProgression(), + userTrophies: getUserTrophies(), + trophies: getTestTrophies(), + ), + ), ], child: const MaterialApp( home: Scaffold(body: TrophiesOverview()), diff --git a/test/trophies/widgets/trophies_overview_test.mocks.dart b/test/trophies/widgets/trophies_overview_test.mocks.dart deleted file mode 100644 index dc837fd8c..000000000 --- a/test/trophies/widgets/trophies_overview_test.mocks.dart +++ /dev/null @@ -1,135 +0,0 @@ -// Mocks generated by Mockito 5.4.6 from annotations -// in wger/test/trophies/widgets/trophies_overview_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i5; - -import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i4; -import 'package:wger/models/trophies/trophy.dart' as _i6; -import 'package:wger/models/trophies/user_trophy.dart' as _i7; -import 'package:wger/models/trophies/user_trophy_progression.dart' as _i8; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/trophies.dart' as _i3; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: must_be_immutable -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class -// ignore_for_file: invalid_use_of_internal_member - -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -/// A class which mocks [TrophyRepository]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { - MockTrophyRepository() { - _i1.throwOnMissingStub(this); - } - - @override - _i2.WgerBaseProvider get base => - (super.noSuchMethod( - Invocation.getter(#base), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#base), - ), - ) - as _i2.WgerBaseProvider); - - @override - String get trophiesPath => - (super.noSuchMethod( - Invocation.getter(#trophiesPath), - returnValue: _i4.dummyValue( - this, - Invocation.getter(#trophiesPath), - ), - ) - as String); - - @override - String get userTrophiesPath => - (super.noSuchMethod( - Invocation.getter(#userTrophiesPath), - returnValue: _i4.dummyValue( - this, - Invocation.getter(#userTrophiesPath), - ), - ) - as String); - - @override - String get userTrophyProgressionPath => - (super.noSuchMethod( - Invocation.getter(#userTrophyProgressionPath), - returnValue: _i4.dummyValue( - this, - Invocation.getter(#userTrophyProgressionPath), - ), - ) - as String); - - @override - _i5.Future> fetchTrophies({String? language}) => - (super.noSuchMethod( - Invocation.method(#fetchTrophies, [], {#language: language}), - returnValue: _i5.Future>.value(<_i6.Trophy>[]), - ) - as _i5.Future>); - - @override - _i5.Future> fetchUserTrophies({ - Map? filterQuery, - String? language, - }) => - (super.noSuchMethod( - Invocation.method(#fetchUserTrophies, [], { - #filterQuery: filterQuery, - #language: language, - }), - returnValue: _i5.Future>.value( - <_i7.UserTrophy>[], - ), - ) - as _i5.Future>); - - @override - _i5.Future> fetchProgression({ - Map? filterQuery, - String? language, - }) => - (super.noSuchMethod( - Invocation.method(#fetchProgression, [], { - #filterQuery: filterQuery, - #language: language, - }), - returnValue: _i5.Future>.value( - <_i8.UserTrophyProgression>[], - ), - ) - as _i5.Future>); - - @override - List<_i6.Trophy> filterByType(List<_i6.Trophy>? list, _i6.TrophyType? type) => - (super.noSuchMethod( - Invocation.method(#filterByType, [list, type]), - returnValue: <_i6.Trophy>[], - ) - as List<_i6.Trophy>); -} diff --git a/test/widgets/routines/gym_mode/log_page_test.dart b/test/widgets/routines/gym_mode/log_page_test.dart index 45526e7f4..78e80858d 100644 --- a/test/widgets/routines/gym_mode/log_page_test.dart +++ b/test/widgets/routines/gym_mode/log_page_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 - 2025 wger Team + * Copyright (c) 2025 - 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 @@ -189,15 +189,15 @@ void main() { testWidgets('save button calls addLog on RoutinesProvider', (tester) async { // Arrange - final notifier = container.read(gymStateProvider.notifier); + final gymNotifier = container.read(gymStateProvider.notifier); final routine = testdata.getTestRoutine(); - notifier.state = notifier.state.copyWith( + gymNotifier.state = gymNotifier.state.copyWith( dayId: routine.days.first.id, routine: routine, iteration: 1, ); - notifier.calculatePages(); - notifier.state = notifier.state.copyWith(currentPage: 2); + gymNotifier.calculatePages(); + gymNotifier.state = gymNotifier.state.copyWith(currentPage: 2); final mockRoutines = MockRoutinesProvider(); // Act @@ -229,10 +229,10 @@ void main() { expect(capturedLog!.repetitions, equals(7)); expect(capturedLog!.weight, equals(77)); - final currentSlotPage = notifier.state.getSlotEntryPageByIndex()!; + final currentSlotPage = gymNotifier.state.getSlotEntryPageByIndex()!; expect(capturedLog!.slotEntryId, equals(currentSlotPage.setConfigData!.slotEntryId)); - expect(capturedLog!.routineId, equals(notifier.state.routine.id)); - expect(capturedLog!.iteration, equals(notifier.state.iteration)); + expect(capturedLog!.routineId, equals(gymNotifier.state.routine.id)); + expect(capturedLog!.iteration, equals(gymNotifier.state.iteration)); }); }); } From fb6a6735031ea96d74e8810f211b0033c1e65e62 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 12 Jan 2026 21:39:36 +0100 Subject: [PATCH 22/48] Simplify code by adding new log provider This makes the logic for copying or modifying the logs much easier. Also, there were some user reports that the old logic sometimes behaved erratically and old values were sometimes reverted. --- lib/models/workouts/log.dart | 53 ++- lib/models/workouts/session.g.dart | 4 +- lib/models/workouts/slot_data.g.dart | 18 - lib/providers/gym_log_state.dart | 46 ++ lib/providers/gym_log_state.g.dart | 56 +++ lib/providers/gym_state.dart | 23 +- lib/providers/gym_state.g.dart | 18 - lib/widgets/routines/gym_mode/log_page.dart | 444 +++++------------- lib/widgets/routines/gym_mode/navigation.dart | 11 +- test/core/validators_test.mocks.dart | 18 - test/routine/gym_mode/gym_mode_test.dart | 7 +- test/user/provider_test.mocks.dart | 18 - .../routines/gym_mode/log_page_test.dart | 13 +- .../gym_mode/log_page_test.mocks.dart | 18 - 14 files changed, 302 insertions(+), 445 deletions(-) create mode 100644 lib/providers/gym_log_state.dart create mode 100644 lib/providers/gym_log_state.g.dart diff --git a/lib/models/workouts/log.dart b/lib/models/workouts/log.dart index f4473aa13..52b5c9f61 100644 --- a/lib/models/workouts/log.dart +++ b/lib/models/workouts/log.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -101,13 +101,13 @@ class Log { this.repetitions, this.repetitionsTarget, this.repetitionsUnitId = REP_UNIT_REPETITIONS_ID, - required this.rir, + this.rir, this.rirTarget, this.weight, this.weightTarget, this.weightUnitId = WEIGHT_UNIT_KG, - required this.date, - }); + DateTime? date, + }) : date = date ?? DateTime.now(); Log.empty(); @@ -130,6 +130,51 @@ class Log { rirTarget = setConfig.rir; } + Log copyWith({ + int? id, + int? exerciseId, + int? routineId, + int? sessionId, + int? iteration, + int? slotEntryId, + num? rir, + num? rirTarget, + num? repetitions, + num? repetitionsTarget, + int? repetitionsUnitId, + num? weight, + num? weightTarget, + int? weightUnitId, + DateTime? date, + }) { + final out = Log( + id: id ?? this.id, + exerciseId: exerciseId ?? this.exerciseId, + iteration: iteration ?? this.iteration, + slotEntryId: slotEntryId ?? this.slotEntryId, + routineId: routineId ?? this.routineId, + repetitions: repetitions ?? this.repetitions, + repetitionsTarget: repetitionsTarget ?? this.repetitionsTarget, + repetitionsUnitId: repetitionsUnitId ?? this.repetitionsUnitId, + rir: rir ?? this.rir, + rirTarget: rirTarget ?? this.rirTarget, + weight: weight ?? this.weight, + weightTarget: weightTarget ?? this.weightTarget, + weightUnitId: weightUnitId ?? this.weightUnitId, + date: date ?? this.date, + ); + + if (sessionId != null) { + out.sessionId = sessionId; + } + + out.exerciseBase = exercise; + out.repetitionUnit = repetitionsUnitObj; + out.weightUnitObj = weightUnitObj; + + return out; + } + // Boilerplate factory Log.fromJson(Map json) => _$LogFromJson(json); diff --git a/lib/models/workouts/session.g.dart b/lib/models/workouts/session.g.dart index ac78029df..bf061fa15 100644 --- a/lib/models/workouts/session.g.dart +++ b/lib/models/workouts/session.g.dart @@ -23,7 +23,9 @@ WorkoutSession _$WorkoutSessionFromJson(Map json) { id: (json['id'] as num?)?.toInt(), dayId: (json['day'] as num?)?.toInt(), routineId: (json['routine'] as num?)?.toInt(), - impression: json['impression'] == null ? 2 : int.parse(json['impression'] as String), + impression: json['impression'] == null + ? DEFAULT_IMPRESSION + : int.parse(json['impression'] as String), notes: json['notes'] as String? ?? '', timeStart: stringToTimeNull(json['time_start'] as String?), timeEnd: stringToTimeNull(json['time_end'] as String?), diff --git a/lib/models/workouts/slot_data.g.dart b/lib/models/workouts/slot_data.g.dart index 589b2b999..756717e67 100644 --- a/lib/models/workouts/slot_data.g.dart +++ b/lib/models/workouts/slot_data.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'slot_data.dart'; diff --git a/lib/providers/gym_log_state.dart b/lib/providers/gym_log_state.dart new file mode 100644 index 000000000..96604c5b2 --- /dev/null +++ b/lib/providers/gym_log_state.dart @@ -0,0 +1,46 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +import 'package:logging/logging.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/models/workouts/log.dart'; + +part 'gym_log_state.g.dart'; + +@Riverpod(keepAlive: true) +class GymLogNotifier extends _$GymLogNotifier { + final _logger = Logger('GymLogNotifier'); + + @override + Log? build() { + _logger.finer('Initializing GymLogNotifier'); + return null; + } + + void setLog(Log newLog) { + state = newLog; + } + + void setWeight(num weight) { + state = state?.copyWith(weight: weight); + } + + void setRepetitions(num repetitions) { + state = state?.copyWith(repetitions: repetitions); + } +} diff --git a/lib/providers/gym_log_state.g.dart b/lib/providers/gym_log_state.g.dart new file mode 100644 index 000000000..83c92cc12 --- /dev/null +++ b/lib/providers/gym_log_state.g.dart @@ -0,0 +1,56 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'gym_log_state.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(GymLogNotifier) +const gymLogProvider = GymLogNotifierProvider._(); + +final class GymLogNotifierProvider extends $NotifierProvider { + const GymLogNotifierProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'gymLogProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$gymLogNotifierHash(); + + @$internal + @override + GymLogNotifier create() => GymLogNotifier(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(Log? value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$gymLogNotifierHash() => r'f7cdc8f72506e366ca028360b654da0bdd9bcae6'; + +abstract class _$GymLogNotifier extends $Notifier { + Log? build(); + @$mustCallSuper + @override + void runBuild() { + final created = build(); + final ref = this.ref as $Ref; + final element = + ref.element as $ClassProviderElement, Log?, Object?, Object?>; + element.handleValue(ref, created); + } +} diff --git a/lib/providers/gym_state.dart b/lib/providers/gym_state.dart index 949a753f8..882df3664 100644 --- a/lib/providers/gym_state.dart +++ b/lib/providers/gym_state.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team + * 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 @@ -25,8 +25,10 @@ import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/helpers/uuid.dart'; import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/workouts/day_data.dart'; +import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/routine.dart'; import 'package:wger/models/workouts/set_config_data.dart'; +import 'package:wger/providers/gym_log_state.dart'; part 'gym_state.g.dart'; @@ -131,7 +133,11 @@ class SlotPageEntry { this.setConfigData, this.logDone = false, String? uuid, - }) : uuid = uuid ?? uuidV4(); + }) : assert( + type != SlotPageType.log || setConfigData != null, + 'You need to set setConfigData for SlotPageType.log', + ), + uuid = uuid ?? uuidV4(); SlotPageEntry copyWith({ String? uuid, @@ -481,7 +487,7 @@ class GymStateNotifier extends _$GymStateNotifier { pages.add(PageEntry(type: PageType.workoutSummary, pageIndex: pageIndex + 1)); state = state.copyWith(pages: pages); - print(readPageStructure()); + // print(readPageStructure()); _logger.finer('Initialized ${state.pages.length} pages'); } @@ -573,6 +579,17 @@ class GymStateNotifier extends _$GymStateNotifier { void setCurrentPage(int page) { state = state.copyWith(currentPage: page); + + // Ensure that there is a log entry for the current slot entry + final slotEntryPage = state.getSlotEntryPageByIndex(); + if (slotEntryPage == null || slotEntryPage.setConfigData == null) { + return; + } + + final log = Log.fromSetConfigData(slotEntryPage.setConfigData!); + log.routineId = state.routine.id!; + log.iteration = state.iteration; + ref.read(gymLogProvider.notifier).setLog(log); } void setShowExercisePages(bool value) { diff --git a/lib/providers/gym_state.g.dart b/lib/providers/gym_state.g.dart index 7596fa4be..1899e808d 100644 --- a/lib/providers/gym_state.g.dart +++ b/lib/providers/gym_state.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'gym_state.dart'; diff --git a/lib/widgets/routines/gym_mode/log_page.dart b/lib/widgets/routines/gym_mode/log_page.dart index 702542667..088836d65 100644 --- a/lib/widgets/routines/gym_mode/log_page.dart +++ b/lib/widgets/routines/gym_mode/log_page.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -27,6 +27,7 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/set_config_data.dart'; import 'package:wger/models/workouts/slot_entry.dart'; +import 'package:wger/providers/gym_log_state.dart'; import 'package:wger/providers/gym_state.dart'; import 'package:wger/providers/plate_weights.dart'; import 'package:wger/providers/routines.dart'; @@ -39,75 +40,37 @@ import 'package:wger/widgets/routines/forms/weight_unit.dart'; import 'package:wger/widgets/routines/gym_mode/navigation.dart'; import 'package:wger/widgets/routines/plate_calculator.dart'; -class LogPage extends ConsumerStatefulWidget { +class LogPage extends ConsumerWidget { final _logger = Logger('LogPage'); final PageController _controller; - LogPage(this._controller); - - @override - _LogPageState createState() => _LogPageState(); -} - -class _LogPageState extends ConsumerState { final GlobalKey<_LogFormWidgetState> _logFormKey = GlobalKey<_LogFormWidgetState>(); - late FocusNode focusNode; - // Persistent log and current slot-page id to avoid recreating the Log on rebuilds - Log? _currentLog; - String? _currentSlotPageUuid; - @override - void initState() { - super.initState(); - focusNode = FocusNode(); - } - - @override - void dispose() { - focusNode.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); - final state = ref.watch(gymStateProvider); + final gymState = ref.watch(gymStateProvider); final languageCode = Localizations.localeOf(context).languageCode; - final page = state.getPageByIndex(); + final page = gymState.getPageByIndex(); if (page == null) { - widget._logger.info( - 'getPageByIndex for ${state.currentPage} returned null, showing empty container.', + _logger.info( + 'getPageByIndex for ${gymState.currentPage} returned null, showing empty container.', ); return Container(); } - final slotEntryPage = state.getSlotEntryPageByIndex(); + final slotEntryPage = gymState.getSlotEntryPageByIndex(); if (slotEntryPage == null) { - widget._logger.info( - 'getSlotPageByIndex for ${state.currentPage} returned null, showing empty container', + _logger.info( + 'getSlotPageByIndex for ${gymState.currentPage} returned null, showing empty container', ); return Container(); } - final setConfigData = slotEntryPage.setConfigData!; - // Create a Log only when the slot page changed or none exists yet - if (_currentLog == null || _currentSlotPageUuid != slotEntryPage.uuid) { - _currentLog = Log.fromSetConfigData(setConfigData) - ..routineId = state.routine.id! - ..iteration = state.iteration; - _currentSlotPageUuid = slotEntryPage.uuid; - } else { - // Update routine/iteration if needed without creating a new Log - _currentLog! - ..routineId = state.routine.id! - ..iteration = state.iteration; - } - - final log = _currentLog!; + final log = ref.watch(gymLogProvider); // Mark done sets final decorationStyle = slotEntryPage.logDone @@ -117,8 +80,9 @@ class _LogPageState extends ConsumerState { return Column( children: [ NavigationHeader( - log.exercise.getTranslation(languageCode).name, - widget._controller, + log!.exercise.getTranslation(languageCode).name, + _controller, + key: const ValueKey('log-page-navigation-header'), ), Container( @@ -164,16 +128,9 @@ class _LogPageState extends ConsumerState { Text(slotEntryPage.setConfigData!.comment, textAlign: TextAlign.center), const SizedBox(height: 10), Expanded( - child: (state.routine.filterLogsByExercise(log.exercise.id!).isNotEmpty) + child: (gymState.routine.filterLogsByExercise(log.exerciseId).isNotEmpty) ? LogsPastLogsWidget( - log: log, - pastLogs: state.routine.filterLogsByExercise(log.exercise.id!), - onCopy: (pastLog) { - _logFormKey.currentState?.copyFromPastLog(pastLog); - }, - setStateCallback: (fn) { - setState(fn); - }, + pastLogs: gymState.routine.filterLogsByExercise(log.exerciseId), ) : Container(), ), @@ -186,16 +143,15 @@ class _LogPageState extends ConsumerState { child: Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: LogFormWidget( - controller: widget._controller, + controller: _controller, configData: setConfigData, - log: log, - focusNode: focusNode, + // log: log!, key: _logFormKey, ), ), ), ), - NavigationFooter(widget._controller), + NavigationFooter(_controller), ], ); } @@ -255,68 +211,62 @@ class LogsPlatesWidget extends ConsumerWidget { } } -class LogsRepsWidget extends StatelessWidget { - final TextEditingController controller; - final SetConfigData configData; - final FocusNode focusNode; - final Log log; - final void Function(VoidCallback fn) setStateCallback; - +class LogsRepsWidget extends ConsumerWidget { final _logger = Logger('LogsRepsWidget'); + final num valueChange; + LogsRepsWidget({ super.key, - required this.controller, - required this.configData, - required this.focusNode, - required this.log, - required this.setStateCallback, - }); + num? valueChange, + }) : valueChange = valueChange ?? 1; @override - Widget build(BuildContext context) { - final repsValueChange = configData.repetitionsRounding ?? 1; + Widget build(BuildContext context, WidgetRef ref) { final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); - final i18n = AppLocalizations.of(context); + final logNotifier = ref.read(gymLogProvider.notifier); + final log = ref.watch(gymLogProvider); + + final currentReps = log?.repetitions; + final repText = currentReps != null ? numberFormat.format(currentReps) : ''; + return Row( children: [ + // "Quick-remove" button IconButton( icon: const Icon(Icons.remove, color: Colors.black), onPressed: () { - final currentValue = numberFormat.tryParse(controller.text) ?? 0; - final newValue = currentValue - repsValueChange; - if (newValue >= 0) { - setStateCallback(() { - log.repetitions = newValue; - controller.text = numberFormat.format(newValue); - }); + final base = currentReps ?? 0; + final newValue = base - valueChange; + if (newValue >= 0 && log != null) { + logNotifier.setRepetitions(newValue); } }, ), + + // Text field Expanded( child: TextFormField( decoration: InputDecoration(labelText: i18n.repetitions), enabled: true, - controller: controller, + key: ValueKey('reps-field-$repText'), + initialValue: repText, keyboardType: textInputTypeDecimal, - focusNode: focusNode, onChanged: (value) { try { final newValue = numberFormat.parse(value); - setStateCallback(() { - log.repetitions = newValue; - }); + logNotifier.setRepetitions(newValue); } on FormatException catch (error) { - _logger.fine('Error parsing repetitions: $error'); + _logger.finer('Error parsing repetitions: $error'); } }, onSaved: (newValue) { - _logger.info('Saving new reps value: $newValue'); - setStateCallback(() { - log.repetitions = numberFormat.parse(newValue!); - }); + if (newValue == null || log == null) { + return; + } + logNotifier.setRepetitions(numberFormat.parse(newValue)); }, validator: (value) { if (numberFormat.tryParse(value ?? '') == null) { @@ -326,19 +276,15 @@ class LogsRepsWidget extends StatelessWidget { }, ), ), + + // "Quick-add" button IconButton( icon: const Icon(Icons.add, color: Colors.black), onPressed: () { - final value = controller.text.isNotEmpty ? controller.text : '0'; - - try { - final newValue = numberFormat.parse(value) + repsValueChange; - setStateCallback(() { - log.repetitions = newValue; - controller.text = numberFormat.format(newValue); - }); - } on FormatException catch (error) { - _logger.fine('Error parsing reps during quick-add: $error'); + final base = currentReps ?? 0; + final newValue = base + valueChange; + if (newValue >= 0 && log != null) { + logNotifier.setRepetitions(newValue); } }, ), @@ -348,76 +294,62 @@ class LogsRepsWidget extends StatelessWidget { } class LogsWeightWidget extends ConsumerWidget { - final TextEditingController controller; - final SetConfigData configData; - final FocusNode focusNode; - final Log log; - final void Function(VoidCallback fn) setStateCallback; - final _logger = Logger('LogsWeightWidget'); + final num valueChange; + LogsWeightWidget({ super.key, - required this.controller, - required this.configData, - required this.focusNode, - required this.log, - required this.setStateCallback, - }); + num? valueChange, + }) : valueChange = valueChange ?? 1.25; @override Widget build(BuildContext context, WidgetRef ref) { - final weightValueChange = configData.weightRounding ?? 1.25; final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); final i18n = AppLocalizations.of(context); + final plateProvider = ref.read(plateCalculatorProvider.notifier); + final logProvider = ref.read(gymLogProvider.notifier); + final log = ref.watch(gymLogProvider); + + final currentWeight = log?.weight; + final weightText = currentWeight != null ? numberFormat.format(currentWeight) : ''; + return Row( children: [ IconButton( + // "Quick-remove" button icon: const Icon(Icons.remove, color: Colors.black), onPressed: () { - try { - final newValue = numberFormat.parse(controller.text) - weightValueChange; - if (newValue > 0) { - setStateCallback(() { - log.weight = newValue; - controller.text = numberFormat.format(newValue); - ref - .read(plateCalculatorProvider.notifier) - .setWeight( - controller.text == '' ? 0 : newValue, - ); - }); - } - } on FormatException catch (error) { - _logger.fine('Error parsing weight during quick-remove: $error'); + final base = currentWeight ?? 0; + final newValue = base - valueChange; + if (newValue >= 0 && log != null) { + logProvider.setWeight(newValue); } }, ), + + // Text field Expanded( child: TextFormField( + key: ValueKey('weight-field-$weightText'), decoration: InputDecoration(labelText: i18n.weight), - controller: controller, + initialValue: weightText, keyboardType: textInputTypeDecimal, onChanged: (value) { try { final newValue = numberFormat.parse(value); - setStateCallback(() { - log.weight = newValue; - ref - .read(plateCalculatorProvider.notifier) - .setWeight( - controller.text == '' ? 0 : numberFormat.parse(controller.text), - ); - }); + plateProvider.setWeight(newValue); + logProvider.setWeight(newValue); } on FormatException catch (error) { - _logger.fine('Error parsing weight: $error'); + _logger.finer('Error parsing weight: $error'); } }, onSaved: (newValue) { - setStateCallback(() { - log.weight = numberFormat.parse(newValue!); - }); + if (newValue == null || log == null) { + return; + } + logProvider.setWeight(numberFormat.parse(newValue)); }, validator: (value) { if (numberFormat.tryParse(value ?? '') == null) { @@ -427,24 +359,15 @@ class LogsWeightWidget extends ConsumerWidget { }, ), ), + + // "Quick-add" button IconButton( icon: const Icon(Icons.add, color: Colors.black), onPressed: () { - final value = controller.text.isNotEmpty ? controller.text : '0'; - - try { - final newValue = numberFormat.parse(value) + weightValueChange; - setStateCallback(() { - log.weight = newValue; - controller.text = numberFormat.format(newValue); - ref - .read(plateCalculatorProvider.notifier) - .setWeight( - controller.text == '' ? 0 : newValue, - ); - }); - } on FormatException catch (error) { - _logger.fine('Error parsing weight during quick-add: $error'); + final base = currentWeight ?? 0; + final newValue = base + valueChange; + if (log != null) { + logProvider.setWeight(newValue); } }, ), @@ -453,22 +376,19 @@ class LogsWeightWidget extends ConsumerWidget { } } -class LogsPastLogsWidget extends StatelessWidget { - final Log log; +class LogsPastLogsWidget extends ConsumerWidget { final List pastLogs; - final void Function(Log pastLog) onCopy; - final void Function(VoidCallback fn) setStateCallback; const LogsPastLogsWidget({ super.key, - required this.log, required this.pastLogs, - required this.onCopy, - required this.setStateCallback, }); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + final logProvider = ref.read(gymLogProvider.notifier); + final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); + return Container( padding: const EdgeInsets.symmetric(vertical: 8), child: ListView( @@ -482,25 +402,16 @@ class LogsPastLogsWidget extends StatelessWidget { return ListTile( key: ValueKey('past-log-${pastLog.id}'), title: Text(pastLog.repTextNoNl(context)), - subtitle: Text( - DateFormat.yMd(Localizations.localeOf(context).languageCode).format(pastLog.date), - ), + subtitle: Text(dateFormat.format(pastLog.date)), trailing: const Icon(Icons.copy), onTap: () { - setStateCallback(() { - log.rir = pastLog.rir; - log.repetitionUnit = pastLog.repetitionsUnitObj; - log.weightUnit = pastLog.weightUnitObj; - - onCopy(pastLog); - - ScaffoldMessenger.of(context).hideCurrentSnackBar(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(AppLocalizations.of(context).dataCopied), - ), - ); - }); + logProvider.setLog(pastLog); + ScaffoldMessenger.of(context).hideCurrentSnackBar(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(AppLocalizations.of(context).dataCopied), + ), + ); }, contentPadding: const EdgeInsets.symmetric(horizontal: 40), ); @@ -516,15 +427,11 @@ class LogFormWidget extends ConsumerStatefulWidget { final PageController controller; final SetConfigData configData; - final Log log; - final FocusNode focusNode; LogFormWidget({ super.key, required this.controller, required this.configData, - required this.log, - required this.focusNode, }); @override @@ -535,116 +442,11 @@ class _LogFormWidgetState extends ConsumerState { final _form = GlobalKey(); var _detailed = false; bool _isSaving = false; - late Log _log; - - late final TextEditingController _repetitionsController; - late final TextEditingController _weightController; - - @override - void initState() { - super.initState(); - - _log = widget.log; - _repetitionsController = TextEditingController(); - _weightController = TextEditingController(); - - WidgetsBinding.instance.addPostFrameCallback((_) { - _syncControllersWithWidget(); - }); - } - - @override - void didUpdateWidget(covariant LogFormWidget oldWidget) { - super.didUpdateWidget(oldWidget); - - // If the log or config changed, update internal _log and controllers - if (oldWidget.log != widget.log || oldWidget.configData != widget.configData) { - _log = widget.log; - _syncControllersWithWidget(); - } - } - - void _syncControllersWithWidget() { - final locale = Localizations.localeOf(context).toString(); - final numberFormat = NumberFormat.decimalPattern(locale); - - // Priority: current log -> config defaults -> empty - try { - _repetitionsController.text = widget.log.repetitions != null - ? numberFormat.format(widget.log.repetitions) - : (widget.configData.repetitions != null - ? numberFormat.format(widget.configData.repetitions) - : ''); - - _weightController.text = widget.log.weight != null - ? numberFormat.format(widget.log.weight) - : (widget.configData.weight != null ? numberFormat.format(widget.configData.weight) : ''); - } on Exception catch (e) { - // Defensive fallback: set empty strings if formatting fails - widget._logger.warning('Error syncing controllers: $e'); - _repetitionsController.text = ''; - _weightController.text = ''; - } - } - - @override - void dispose() { - _repetitionsController.dispose(); - _weightController.dispose(); - super.dispose(); - } - - void copyFromPastLog(Log pastLog) { - final locale = Localizations.localeOf(context).toString(); - final numberFormat = NumberFormat.decimalPattern(locale); - - setState(() { - _repetitionsController.text = pastLog.repetitions != null - ? numberFormat.format(pastLog.repetitions) - : ''; - widget._logger.finer('Setting log repetitions to ${_repetitionsController.text}'); - - _weightController.text = pastLog.weight != null ? numberFormat.format(pastLog.weight) : ''; - widget._logger.finer('Setting log weight to ${_weightController.text}'); - - _log.repetitions = pastLog.repetitions; - _log.weight = pastLog.weight; - _log.rir = pastLog.rir; - if (pastLog.repetitionsUnitObj != null) { - _log.repetitionUnit = pastLog.repetitionsUnitObj; - } - if (pastLog.weightUnitObj != null) { - _log.weightUnit = pastLog.weightUnitObj; - } - - widget._logger.finer( - 'Copied to _log: repetitions=${_log.repetitions}, weight=${_log.weight}, repetitionsUnitId=${_log.repetitionsUnitId}, weightUnitId=${_log.weightUnitId}, rir=${_log.rir}', - ); - - // Update plate calculator using the value currently visible in the controllers - try { - final weightValue = _weightController.text.isEmpty - ? 0 - : numberFormat.parse(_weightController.text); - ref.read(plateCalculatorProvider.notifier).setWeight(weightValue); - } catch (e) { - widget._logger.fine('Error updating plate calculator: $e'); - } - }); - - // Ensure subsequent syncs (e.g., didUpdateWidget) don't overwrite these values - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) { - return; - } - - _syncControllersWithWidget(); - }); - } @override Widget build(BuildContext context) { final i18n = AppLocalizations.of(context); + final log = ref.watch(gymLogProvider); return Form( key: _form, @@ -662,26 +464,14 @@ class _LogFormWidgetState extends ConsumerState { Flexible( child: LogsRepsWidget( key: const ValueKey('logs-reps-widget'), - controller: _repetitionsController, - configData: widget.configData, - focusNode: widget.focusNode, - log: _log, - setStateCallback: (fn) { - setState(fn); - }, + valueChange: widget.configData.repetitionsRounding, ), ), const SizedBox(width: 8), Flexible( child: LogsWeightWidget( key: const ValueKey('logs-weight-widget'), - controller: _weightController, - configData: widget.configData, - focusNode: widget.focusNode, - log: _log, - setStateCallback: (fn) { - setState(fn); - }, + valueChange: widget.configData.weightRounding, ), ), ], @@ -693,20 +483,14 @@ class _LogFormWidgetState extends ConsumerState { Flexible( child: LogsRepsWidget( key: const ValueKey('logs-reps-widget'), - controller: _repetitionsController, - configData: widget.configData, - focusNode: widget.focusNode, - log: _log, - setStateCallback: (fn) { - setState(fn); - }, + valueChange: widget.configData.repetitionsRounding, ), ), const SizedBox(width: 8), Flexible( child: RepetitionUnitInputWidget( key: const ValueKey('repetition-unit-input-widget'), - _log.repetitionsUnitId, + log!.repetitionsUnitId, onChanged: (v) => {}, ), ), @@ -720,19 +504,13 @@ class _LogFormWidgetState extends ConsumerState { Flexible( child: LogsWeightWidget( key: const ValueKey('logs-weight-widget'), - controller: _weightController, - configData: widget.configData, - focusNode: widget.focusNode, - log: _log, - setStateCallback: (fn) { - setState(fn); - }, + valueChange: widget.configData.weightRounding, ), ), const SizedBox(width: 8), Flexible( child: WeightUnitInputWidget( - _log.weightUnitId, + log!.weightUnitId, onChanged: (v) => {}, key: const ValueKey('weight-unit-input-widget'), ), @@ -743,13 +521,9 @@ class _LogFormWidgetState extends ConsumerState { if (_detailed) RiRInputWidget( key: const ValueKey('rir-input-widget'), - _log.rir, + log!.rir, onChanged: (value) { - if (value == '') { - _log.rir = null; - } else { - _log.rir = num.parse(value); - } + log.rir = value == '' ? null : num.parse(value); }, ), SwitchListTile( @@ -782,7 +556,7 @@ class _LogFormWidgetState extends ConsumerState { await provider.Provider.of( context, listen: false, - ).addLog(_log); + ).addLog(log!); final page = gymState.getSlotEntryPageByIndex()!; gymProvider.markSlotPageAsDone(page.uuid, isDone: true); diff --git a/lib/widgets/routines/gym_mode/navigation.dart b/lib/widgets/routines/gym_mode/navigation.dart index d2572b52f..9639c3d05 100644 --- a/lib/widgets/routines/gym_mode/navigation.dart +++ b/lib/widgets/routines/gym_mode/navigation.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -28,7 +28,12 @@ class NavigationHeader extends StatelessWidget { final String _title; final bool showEndWorkoutButton; - const NavigationHeader(this._title, this._controller, {this.showEndWorkoutButton = true}); + const NavigationHeader( + this._title, + this._controller, { + this.showEndWorkoutButton = true, + super.key, + }); @override Widget build(BuildContext context) { diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 8791d455c..9b069055c 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/core/validators_test.dart. // Do not manually edit this file. diff --git a/test/routine/gym_mode/gym_mode_test.dart b/test/routine/gym_mode/gym_mode_test.dart index 38a3e296c..3f61e88b2 100644 --- a/test/routine/gym_mode/gym_mode_test.dart +++ b/test/routine/gym_mode/gym_mode_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 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 @@ -109,12 +109,10 @@ void main() { await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { await tester.pumpWidget(renderGymMode()); - await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); - await tester.pumpAndSettle(); - //await tester.ensureVisible(find.byKey(Key(key as String))); + // // Start page // @@ -306,6 +304,7 @@ void main() { expect(find.byIcon(Icons.chevron_right), findsNothing); }); }, + tags: ['golden'], semanticsEnabled: false, ); } diff --git a/test/user/provider_test.mocks.dart b/test/user/provider_test.mocks.dart index b8fce543f..08bbf6366 100644 --- a/test/user/provider_test.mocks.dart +++ b/test/user/provider_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/user/provider_test.dart. // Do not manually edit this file. diff --git a/test/widgets/routines/gym_mode/log_page_test.dart b/test/widgets/routines/gym_mode/log_page_test.dart index 45526e7f4..b9ba0f8d4 100644 --- a/test/widgets/routines/gym_mode/log_page_test.dart +++ b/test/widgets/routines/gym_mode/log_page_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 - 2025 wger Team + * Copyright (c) 2025 - 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 @@ -128,6 +128,7 @@ void main() { // Act notifier.calculatePages(); + notifier.setCurrentPage(2); // Assert expect(notifier.state.getSlotEntryPageByIndex()!.type, SlotPageType.log); @@ -159,6 +160,7 @@ void main() { iteration: 1, ); notifier.calculatePages(); + notifier.setCurrentPage(2); // Act // Log page is at index 2 @@ -197,6 +199,7 @@ void main() { iteration: 1, ); notifier.calculatePages(); + notifier.setCurrentPage(2); notifier.state = notifier.state.copyWith(currentPage: 2); final mockRoutines = MockRoutinesProvider(); @@ -206,8 +209,8 @@ void main() { final editableFields = find.byType(EditableText); expect(editableFields, findsWidgets); - await tester.enterText(editableFields.at(0), '7'); - await tester.enterText(editableFields.at(1), '77'); + await tester.enterText(editableFields.at(0), '12'); // Reps + await tester.enterText(editableFields.at(1), '34'); // Weight await tester.pumpAndSettle(); Log? capturedLog; @@ -226,8 +229,8 @@ void main() { // Assert verify(mockRoutines.addLog(any)).called(1); expect(capturedLog, isNotNull); - expect(capturedLog!.repetitions, equals(7)); - expect(capturedLog!.weight, equals(77)); + expect(capturedLog!.repetitions, equals(12)); + expect(capturedLog!.weight, equals(34)); final currentSlotPage = notifier.state.getSlotEntryPageByIndex()!; expect(capturedLog!.slotEntryId, equals(currentSlotPage.setConfigData!.slotEntryId)); diff --git a/test/widgets/routines/gym_mode/log_page_test.mocks.dart b/test/widgets/routines/gym_mode/log_page_test.mocks.dart index 500c61d8d..e9105c48d 100644 --- a/test/widgets/routines/gym_mode/log_page_test.mocks.dart +++ b/test/widgets/routines/gym_mode/log_page_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/widgets/routines/gym_mode/log_page_test.dart. // Do not manually edit this file. From cbdc4a0c561b438f9ef3d1ec43048d1944a69baa Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 12 Jan 2026 21:56:59 +0100 Subject: [PATCH 23/48] Increase page size for languages, no need to use pagination for this Categories and muscles will probably never get so big, but it doesn't do any harm doing it as well. --- lib/providers/exercises.dart | 30 +++++++++++++++---- test/exercises/exercise_provider_db_test.dart | 30 +++++++++++++++++-- test/exercises/exercise_provider_test.dart | 30 +++++++++++++++++-- 3 files changed, 79 insertions(+), 11 deletions(-) diff --git a/lib/providers/exercises.dart b/lib/providers/exercises.dart index 50c8175c9..4e87cf161 100644 --- a/lib/providers/exercises.dart +++ b/lib/providers/exercises.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2020 - 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 @@ -234,7 +234,12 @@ class ExercisesProvider with ChangeNotifier { Future fetchAndSetCategoriesFromApi() async { _logger.info('Loading exercise categories from API'); - final categories = await baseProvider.fetchPaginated(baseProvider.makeUrl(categoriesUrlPath)); + final categories = await baseProvider.fetchPaginated( + baseProvider.makeUrl( + categoriesUrlPath, + query: {'limit': API_MAX_PAGE_SIZE}, + ), + ); for (final category in categories) { _categories.add(ExerciseCategory.fromJson(category)); } @@ -242,7 +247,12 @@ class ExercisesProvider with ChangeNotifier { Future fetchAndSetMusclesFromApi() async { _logger.info('Loading muscles from API'); - final muscles = await baseProvider.fetchPaginated(baseProvider.makeUrl(musclesUrlPath)); + final muscles = await baseProvider.fetchPaginated( + baseProvider.makeUrl( + musclesUrlPath, + query: {'limit': API_MAX_PAGE_SIZE}, + ), + ); for (final muscle in muscles) { _muscles.add(Muscle.fromJson(muscle)); @@ -251,7 +261,12 @@ class ExercisesProvider with ChangeNotifier { Future fetchAndSetEquipmentsFromApi() async { _logger.info('Loading equipment from API'); - final equipments = await baseProvider.fetchPaginated(baseProvider.makeUrl(equipmentUrlPath)); + final equipments = await baseProvider.fetchPaginated( + baseProvider.makeUrl( + equipmentUrlPath, + query: {'limit': API_MAX_PAGE_SIZE}, + ), + ); for (final equipment in equipments) { _equipment.add(Equipment.fromJson(equipment)); @@ -261,7 +276,12 @@ class ExercisesProvider with ChangeNotifier { Future fetchAndSetLanguagesFromApi() async { _logger.info('Loading languages from API'); - final languageData = await baseProvider.fetchPaginated(baseProvider.makeUrl(languageUrlPath)); + final languageData = await baseProvider.fetchPaginated( + baseProvider.makeUrl( + languageUrlPath, + query: {'limit': API_MAX_PAGE_SIZE}, + ), + ); for (final language in languageData) { _languages.add(Language.fromJson(language)); diff --git a/test/exercises/exercise_provider_db_test.dart b/test/exercises/exercise_provider_db_test.dart index 3862baa66..2d0c1f8ba 100644 --- a/test/exercises/exercise_provider_db_test.dart +++ b/test/exercises/exercise_provider_db_test.dart @@ -1,3 +1,21 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + import 'dart:convert'; import 'package:drift/native.dart'; @@ -100,19 +118,25 @@ void main() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); // Mock categories - when(mockBaseProvider.makeUrl(categoryUrl)).thenReturn(tCategoryEntriesUri); + when( + mockBaseProvider.makeUrl(categoryUrl, query: anyNamed('query')), + ).thenReturn(tCategoryEntriesUri); when( mockBaseProvider.fetchPaginated(tCategoryEntriesUri), ).thenAnswer((_) => Future.value(tCategoryMap['results'])); // Mock muscles - when(mockBaseProvider.makeUrl(muscleUrl)).thenReturn(tMuscleEntriesUri); + when( + mockBaseProvider.makeUrl(muscleUrl, query: anyNamed('query')), + ).thenReturn(tMuscleEntriesUri); when( mockBaseProvider.fetchPaginated(tMuscleEntriesUri), ).thenAnswer((_) => Future.value(tMuscleMap['results'])); // Mock equipment - when(mockBaseProvider.makeUrl(equipmentUrl)).thenReturn(tEquipmentEntriesUri); + when( + mockBaseProvider.makeUrl(equipmentUrl, query: anyNamed('query')), + ).thenReturn(tEquipmentEntriesUri); when( mockBaseProvider.fetchPaginated(tEquipmentEntriesUri), ).thenAnswer((_) => Future.value(tEquipmentMap['results'])); diff --git a/test/exercises/exercise_provider_test.dart b/test/exercises/exercise_provider_test.dart index f0920635c..d597759c4 100644 --- a/test/exercises/exercise_provider_test.dart +++ b/test/exercises/exercise_provider_test.dart @@ -1,3 +1,21 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + import 'dart:convert'; import 'package:drift/drift.dart'; @@ -105,19 +123,25 @@ void main() { driftRuntimeOptions.dontWarnAboutMultipleDatabases = true; // Mock categories - when(mockBaseProvider.makeUrl(categoryUrl)).thenReturn(tCategoryEntriesUri); + when( + mockBaseProvider.makeUrl(categoryUrl, query: anyNamed('query')), + ).thenReturn(tCategoryEntriesUri); when( mockBaseProvider.fetchPaginated(tCategoryEntriesUri), ).thenAnswer((_) => Future.value(tCategoryMap['results'])); // Mock muscles - when(mockBaseProvider.makeUrl(muscleUrl)).thenReturn(tMuscleEntriesUri); + when( + mockBaseProvider.makeUrl(muscleUrl, query: anyNamed('query')), + ).thenReturn(tMuscleEntriesUri); when( mockBaseProvider.fetchPaginated(tMuscleEntriesUri), ).thenAnswer((_) => Future.value(tMuscleMap['results'])); // Mock equipment - when(mockBaseProvider.makeUrl(equipmentUrl)).thenReturn(tEquipmentEntriesUri); + when( + mockBaseProvider.makeUrl(equipmentUrl, query: anyNamed('query')), + ).thenReturn(tEquipmentEntriesUri); when( mockBaseProvider.fetchPaginated(tEquipmentEntriesUri), ).thenAnswer((_) => Future.value(tEquipmentMap['results'])); From 814a356e14dadf6d36e5c356ae9a4ca2a4e79889 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Jan 2026 15:15:20 +0000 Subject: [PATCH 24/48] Bump flutter_riverpod, riverpod_generator and riverpod_annotation Bumps [flutter_riverpod](https://github.com/rrousselGit/riverpod), [riverpod_generator](https://github.com/rrousselGit/riverpod) and [riverpod_annotation](https://github.com/rrousselGit/riverpod). These dependencies needed to be updated together. Updates `flutter_riverpod` from 3.0.3 to 3.1.0 - [Commits](https://github.com/rrousselGit/riverpod/compare/flutter_riverpod-v3.0.3...flutter_riverpod-v3.1.0) Updates `riverpod_generator` from 3.0.3 to 4.0.0+1 - [Commits](https://github.com/rrousselGit/riverpod/compare/riverpod_generator-v3.0.3...riverpod_generator-v4.0.0) Updates `riverpod_annotation` from 3.0.3 to 4.0.0 - [Commits](https://github.com/rrousselGit/riverpod/compare/riverpod_annotation-v3.0.3...riverpod_annotation-v4.0.0) --- updated-dependencies: - dependency-name: flutter_riverpod dependency-version: 3.1.0 dependency-type: direct:production update-type: version-update:semver-minor - dependency-name: riverpod_generator dependency-version: 4.0.0+1 dependency-type: direct:production update-type: version-update:semver-major - dependency-name: riverpod_annotation dependency-version: 4.0.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- pubspec.lock | 52 ++++++++++------------------------------------------ pubspec.yaml | 6 +++--- 2 files changed, 13 insertions(+), 45 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 6b29145d1..40fa12167 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -25,14 +25,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.1.11" - analyzer_plugin: - dependency: transitive - description: - name: analyzer_plugin - sha256: "08cfefa90b4f4dd3b447bda831cecf644029f9f8e22820f6ee310213ebe2dd53" - url: "https://pub.dev" - source: hosted - version: "0.13.10" archive: dependency: transitive description: @@ -289,22 +281,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.8" - custom_lint_core: - dependency: transitive - description: - name: custom_lint_core - sha256: "85b339346154d5646952d44d682965dfe9e12cae5febd706f0db3aa5010d6423" - url: "https://pub.dev" - source: hosted - version: "0.8.1" - custom_lint_visitor: - dependency: transitive - description: - name: custom_lint_visitor - sha256: "91f2a81e9f0abb4b9f3bb529f78b6227ce6050300d1ae5b1e2c69c66c7a566d8" - url: "https://pub.dev" - source: hosted - version: "1.0.0+8.4.0" dart_style: dependency: transitive description: @@ -516,10 +492,10 @@ packages: dependency: "direct main" description: name: flutter_riverpod - sha256: "9e2d6907f12cc7d23a846847615941bddee8709bf2bfd274acdf5e80bcf22fde" + sha256: "38ec6c303e2c83ee84512f5fc2a82ae311531021938e63d7137eccc107bf3c02" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "3.1.0" flutter_staggered_grid_view: dependency: "direct main" description: @@ -1144,34 +1120,34 @@ packages: dependency: transitive description: name: riverpod - sha256: c406de02bff19d920b832bddfb8283548bfa05ce41c59afba57ce643e116aa59 + sha256: "16ff608d21e8ea64364f2b7c049c94a02ab81668f78845862b6e88b71dd4935a" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "3.1.0" riverpod_analyzer_utils: dependency: transitive description: name: riverpod_analyzer_utils - sha256: a0f68adb078b790faa3c655110a017f9a7b7b079a57bbd40f540e80dce5fcd29 + sha256: "947b05d04c52a546a2ac6b19ef2a54b08520ff6bdf9f23d67957a4c8df1c3bc0" url: "https://pub.dev" source: hosted - version: "1.0.0-dev.7" + version: "1.0.0-dev.8" riverpod_annotation: dependency: "direct main" description: name: riverpod_annotation - sha256: "7230014155777fc31ba3351bc2cb5a3b5717b11bfafe52b1553cb47d385f8897" + sha256: cc1474bc2df55ec3c1da1989d139dcef22cd5e2bd78da382e867a69a8eca2e46 url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "4.0.0" riverpod_generator: dependency: "direct dev" description: name: riverpod_generator - sha256: "49894543a42cf7a9954fc4e7366b6d3cb2e6ec0fa07775f660afcdd92d097702" + sha256: e43b1537229cc8f487f09b0c20d15dba840acbadcf5fc6dad7ad5e8ab75950dc url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "4.0.0+1" shared_preferences: dependency: "direct main" description: @@ -1497,14 +1473,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.5" - uuid: - dependency: transitive - description: - name: uuid - sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8 - url: "https://pub.dev" - source: hosted - version: "4.5.2" vector_graphics: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index df97a9979..f2d532c4d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -66,8 +66,8 @@ dependencies: version: ^3.0.2 video_player: ^2.10.1 logging: ^1.3.0 - flutter_riverpod: ^3.0.3 - riverpod_annotation: ^3.0.3 + flutter_riverpod: ^3.1.0 + riverpod_annotation: ^4.0.0 dev_dependencies: flutter_test: @@ -83,7 +83,7 @@ dev_dependencies: mockito: ^5.4.4 network_image_mock: ^2.1.1 shared_preferences_platform_interface: ^2.0.0 - riverpod_generator: ^3.0.3 + riverpod_generator: ^4.0.0+1 # Script to read out unused translations #translations_cleaner: ^0.0.5 From 4782c729348175651976ffa2a6dd1536d07a93f9 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 13 Jan 2026 16:26:17 +0100 Subject: [PATCH 25/48] Recreate generated files --- .../ingredients/ingredients_database.g.dart | 18 ------------------ lib/providers/gym_log_state.g.dart | 9 ++++----- lib/providers/gym_state.g.dart | 9 ++++----- .../providers/plate_calculator_test.mocks.dart | 18 ------------------ 4 files changed, 8 insertions(+), 46 deletions(-) diff --git a/lib/database/ingredients/ingredients_database.g.dart b/lib/database/ingredients/ingredients_database.g.dart index 4b73341bb..44ebcde20 100644 --- a/lib/database/ingredients/ingredients_database.g.dart +++ b/lib/database/ingredients/ingredients_database.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'ingredients_database.dart'; diff --git a/lib/providers/gym_log_state.g.dart b/lib/providers/gym_log_state.g.dart index 83c92cc12..b2d45a453 100644 --- a/lib/providers/gym_log_state.g.dart +++ b/lib/providers/gym_log_state.g.dart @@ -10,10 +10,10 @@ part of 'gym_log_state.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(GymLogNotifier) -const gymLogProvider = GymLogNotifierProvider._(); +final gymLogProvider = GymLogNotifierProvider._(); final class GymLogNotifierProvider extends $NotifierProvider { - const GymLogNotifierProvider._() + GymLogNotifierProvider._() : super( from: null, argument: null, @@ -40,17 +40,16 @@ final class GymLogNotifierProvider extends $NotifierProvider r'f7cdc8f72506e366ca028360b654da0bdd9bcae6'; +String _$gymLogNotifierHash() => r'4523975eeeaacceca4e86fb2e4ddd9a42c263d8e'; abstract class _$GymLogNotifier extends $Notifier { Log? build(); @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref; final element = ref.element as $ClassProviderElement, Log?, Object?, Object?>; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/providers/gym_state.g.dart b/lib/providers/gym_state.g.dart index 1899e808d..4239a5496 100644 --- a/lib/providers/gym_state.g.dart +++ b/lib/providers/gym_state.g.dart @@ -10,10 +10,10 @@ part of 'gym_state.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(GymStateNotifier) -const gymStateProvider = GymStateNotifierProvider._(); +final gymStateProvider = GymStateNotifierProvider._(); final class GymStateNotifierProvider extends $NotifierProvider { - const GymStateNotifierProvider._() + GymStateNotifierProvider._() : super( from: null, argument: null, @@ -40,14 +40,13 @@ final class GymStateNotifierProvider extends $NotifierProvider r'4e1ac85de3c9f5c7dad4b0c5e6ad80ad36397610'; +String _$gymStateNotifierHash() => r'3a0bb78e9f7e682ba93a40a73b170126b5eb5ca9'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref; final element = ref.element @@ -57,6 +56,6 @@ abstract class _$GymStateNotifier extends $Notifier { Object?, Object? >; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/test/providers/plate_calculator_test.mocks.dart b/test/providers/plate_calculator_test.mocks.dart index 1036371df..9b3fed8e4 100644 --- a/test/providers/plate_calculator_test.mocks.dart +++ b/test/providers/plate_calculator_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/providers/plate_calculator_test.dart. // Do not manually edit this file. From 43427cbf8affeaea59ddbbe7517ad8a6b637a870 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 13 Jan 2026 16:18:25 +0100 Subject: [PATCH 26/48] Add riverpod linting --- analysis_options.yaml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index b7abc7073..79c8d7cad 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -14,15 +14,16 @@ analyzer: # Allow self-reference to deprecated members (we do this because otherwise we have # to annotate every member in every test, assert, etc, when we deprecate something) deprecated_member_use_from_same_package: ignore - # Ignore analyzer hints for updating pubspecs when using Future or - # Stream and not importing dart:async - # Please see https://github.com/flutter/flutter/pull/24528 for details. - sdk_version_async_exported_from_core: ignore + plugins: + - riverpod_lint formatter: page_width: 100 trailing_commas: preserve +plugins: + riverpod_lint: 3.1.0 + linter: rules: # These rules are documented on and in the same order as From 64b0ce3cc684ea453e83472b6dce749c1fb56671 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 13 Jan 2026 16:31:06 +0100 Subject: [PATCH 27/48] Bump flutter version --- .github/actions/flutter-common/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/flutter-common/action.yml b/.github/actions/flutter-common/action.yml index 5592f5d51..ee3b35f90 100644 --- a/.github/actions/flutter-common/action.yml +++ b/.github/actions/flutter-common/action.yml @@ -9,7 +9,7 @@ runs: uses: subosito/flutter-action@v2 with: channel: stable - flutter-version: 3.38.5 + flutter-version: 3.38.6 cache: true - name: Install Flutter dependencies From 5844a370d3b1055dbc06ac885ca1864d0d62b63f Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 13 Jan 2026 16:32:21 +0100 Subject: [PATCH 28/48] Upgrade transitive packages --- pubspec.lock | 68 ++++++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index cfb098bab..77750a639 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -13,10 +13,10 @@ packages: dependency: transitive description: name: analyzer - sha256: a40a0cee526a7e1f387c6847bd8a5ccbf510a75952ef8a28338e989558072cb0 + sha256: f51c8499b35f9b26820cfe914828a6a98a94efd5cc78b37bb7d03debae3a1d08 url: "https://pub.dev" source: hosted - version: "8.4.0" + version: "8.4.1" analyzer_buffer: dependency: transitive description: @@ -61,10 +61,10 @@ packages: dependency: transitive description: name: build - sha256: c1668065e9ba04752570ad7e038288559d1e2ca5c6d0131c0f5f55e39e777413 + sha256: "275bf6bb2a00a9852c28d4e0b410da1d833a734d57d39d44f94bfc895a484ec3" url: "https://pub.dev" source: hosted - version: "4.0.3" + version: "4.0.4" build_config: dependency: transitive description: @@ -85,10 +85,10 @@ packages: dependency: "direct dev" description: name: build_runner - sha256: "110c56ef29b5eb367b4d17fc79375fa8c18a6cd7acd92c05bb3986c17a079057" + sha256: b4d854962a32fd9f8efc0b76f98214790b833af8b2e9b2df6bfc927c0415a072 url: "https://pub.dev" source: hosted - version: "2.10.4" + version: "2.10.5" built_collection: dependency: transitive description: @@ -101,10 +101,10 @@ packages: dependency: transitive description: name: built_value - sha256: "426cf75afdb23aa74bd4e471704de3f9393f3c7b04c1e2d9c6f1073ae0b8b139" + sha256: "120df83d4a4ce6bed06ad653c0a3e85737e0f66664f31e17a55136ff5a738cde" url: "https://pub.dev" source: hosted - version: "8.12.1" + version: "8.12.2" camera: dependency: transitive description: @@ -117,18 +117,18 @@ packages: dependency: transitive description: name: camera_android_camerax - sha256: "474d8355961658d43f1c976e2fa1ca715505bea1adbd56df34c581aaa70ec41f" + sha256: bc7a96998258adddd0b653dd693b0874537707d58b0489708f2a646e4f124246 url: "https://pub.dev" source: hosted - version: "0.6.26+2" + version: "0.6.27" camera_avfoundation: dependency: transitive description: name: camera_avfoundation - sha256: "0efb057a1fecdbf9b697272fbf79afbd47ac0e7bd69b4d900d3f304b31d93bad" + sha256: "087a9fadef20325cb246b4c13344a3ce8e408acfc3e0c665ebff0ec3144d7163" url: "https://pub.dev" source: hosted - version: "0.9.22+7" + version: "0.9.22+8" camera_platform_interface: dependency: transitive description: @@ -141,10 +141,10 @@ packages: dependency: transitive description: name: camera_web - sha256: "3bc7bb1657a0f29c34116453c5d5e528c23efcf5e75aac0a3387cf108040bf65" + sha256: "57f49a635c8bf249d07fb95eb693d7e4dda6796dedb3777f9127fb54847beba7" url: "https://pub.dev" source: hosted - version: "0.3.5+2" + version: "0.3.5+3" carousel_slider: dependency: "direct main" description: @@ -221,10 +221,10 @@ packages: dependency: transitive description: name: code_builder - sha256: "11654819532ba94c34de52ff5feb52bd81cba1de00ef2ed622fd50295f9d4243" + sha256: "6a6cab2ba4680d6423f34a9b972a4c9a94ebe1b62ecec4e1a1f2cba91fd1319d" url: "https://pub.dev" source: hosted - version: "4.11.0" + version: "4.11.1" collection: dependency: "direct main" description: @@ -293,18 +293,18 @@ packages: dependency: "direct main" description: name: drift - sha256: "3669e1b68d7bffb60192ac6ba9fd2c0306804d7a00e5879f6364c69ecde53a7f" + sha256: "5ea2f718558c0b31d4b8c36a3d8e5b7016f1265f46ceb5a5920e16117f0c0d6a" url: "https://pub.dev" source: hosted - version: "2.30.0" + version: "2.30.1" drift_dev: dependency: "direct dev" description: name: drift_dev - sha256: afe4d1d2cfce6606c86f11a6196e974a2ddbfaa992956ce61e054c9b1899c769 + sha256: "892dfb5d69d9e604bdcd102a9376de8b41768cf7be93fd26b63cfc4d8f91ad5f" url: "https://pub.dev" source: hosted - version: "2.30.0" + version: "2.30.1" equatable: dependency: "direct main" description: @@ -325,10 +325,10 @@ packages: dependency: transitive description: name: ffi - sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + sha256: d07d37192dbf97461359c1518788f203b0c9102cfd2c35a716b823741219542c url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.1.5" file: dependency: transitive description: @@ -643,10 +643,10 @@ packages: dependency: transitive description: name: image - sha256: "51555e36056541237b15b57afc31a0f53d4f9aefd9bd00873a6dc0090e54e332" + sha256: "492bd52f6c4fbb6ee41f781ff27765ce5f627910e1e0cbecfa3d9add5562604c" url: "https://pub.dev" source: hosted - version: "4.6.0" + version: "4.7.2" image_picker: dependency: "direct main" description: @@ -856,10 +856,10 @@ packages: dependency: "direct dev" description: name: mockito - sha256: dac24d461418d363778d53198d9ac0510b9d073869f078450f195766ec48d05e + sha256: a45d1aa065b796922db7b9e7e7e45f921aed17adf3a8318a1f47097e7e695566 url: "https://pub.dev" source: hosted - version: "5.6.1" + version: "5.6.3" multi_select_flutter: dependency: "direct main" description: @@ -1309,10 +1309,10 @@ packages: dependency: transitive description: name: sqlparser - sha256: "162435ede92bcc793ea939fdc0452eef0a73d11f8ed053b58a89792fba749da5" + sha256: f52f5d5649dcc13ed198c4176ddef74bf6851c30f4f31603f1b37788695b93e2 url: "https://pub.dev" source: hosted - version: "0.42.1" + version: "0.43.0" stack_trace: dependency: transitive description: @@ -1533,18 +1533,18 @@ packages: dependency: transitive description: name: video_player_android - sha256: "8587f7b1e1ad7a7b8f7a7e153bd6de8607168f865f0bd983ef1f92efd3f4a02c" + sha256: ee4fd520b0cafa02e4a867a0f882092e727cdaa1a2d24762171e787f8a502b0a url: "https://pub.dev" source: hosted - version: "2.9.0" + version: "2.9.1" video_player_avfoundation: dependency: transitive description: name: video_player_avfoundation - sha256: e4d33b79a064498c6eb3a6a492b6a5012573d4943c28d566caf1a6c0840fe78d + sha256: d1eb970495a76abb35e5fa93ee3c58bd76fb6839e2ddf2fbb636674f2b971dd4 url: "https://pub.dev" source: hosted - version: "2.8.8" + version: "2.8.9" video_player_platform_interface: dependency: transitive description: @@ -1573,10 +1573,10 @@ packages: dependency: transitive description: name: watcher - sha256: f52385d4f73589977c80797e60fe51014f7f2b957b5e9a62c3f6ada439889249 + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.2.1" web: dependency: transitive description: From 574ef3d0b591856be7c03088d3a343257d9fb29e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 14 Jan 2026 13:59:41 +0100 Subject: [PATCH 29/48] Add simple retry logic to the base provider's fetch method This should take care of simple transient errors, or other network hiccups that might happen on the user's device. --- lib/providers/base_provider.dart | 66 ++++-- test/core/settings_test.mocks.dart | 12 +- .../contribute_exercise_image_test.mocks.dart | 12 +- test/gallery/gallery_form_test.mocks.dart | 12 +- test/gallery/gallery_screen_test.mocks.dart | 12 +- .../measurement_provider_test.mocks.dart | 12 +- .../nutritional_plan_screen_test.mocks.dart | 12 +- .../nutritional_plans_screen_test.mocks.dart | 12 +- test/providers/base_provider.dart | 135 +++++++++++ test/providers/base_provider.mocks.dart | 218 ++++++++++++++++++ .../routine/gym_mode/gym_mode_test.mocks.dart | 12 +- test/routine/routine_screen_test.mocks.dart | 12 +- .../routine/routines_provider_test.mocks.dart | 12 +- test/routine/routines_screen_test.mocks.dart | 12 +- test/user/provider_test.mocks.dart | 12 +- test/weight/weight_provider_test.mocks.dart | 12 +- 16 files changed, 536 insertions(+), 39 deletions(-) create mode 100644 test/providers/base_provider.dart create mode 100644 test/providers/base_provider.mocks.dart diff --git a/lib/providers/base_provider.dart b/lib/providers/base_provider.dart index dee257d75..b905e29c5 100644 --- a/lib/providers/base_provider.dart +++ b/lib/providers/base_provider.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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 @@ -16,19 +16,27 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'dart:math' as math; import 'package:http/http.dart' as http; import 'package:http/http.dart'; +import 'package:logging/logging.dart'; import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/providers/auth.dart'; import 'package:wger/providers/helpers.dart'; +/// initial delay for fetch retries, in milliseconds +const FETCH_INITIAL_DELAY = 250; + /// Base provider class. /// /// Provides a couple of comfort functions so we avoid a bit of boilerplate. class WgerBaseProvider { + final _logger = Logger('WgerBaseProvider'); + AuthProvider auth; late http.Client client; @@ -56,21 +64,53 @@ class WgerBaseProvider { } /// Fetch and retrieve the overview list of objects, returns the JSON parsed response - Future fetch(Uri uri) async { - // Future | List> fetch(Uri uri) async { - // Send the request - final response = await client.get( - uri, - headers: getDefaultHeaders(includeAuth: true), - ); + /// with a simple retry mechanism for transient errors. + Future fetch( + Uri uri, { + int maxRetries = 3, + Duration initialDelay = const Duration(milliseconds: 250), + }) async { + int attempt = 0; + final random = math.Random(); - // Something wrong with our request - if (response.statusCode >= 400) { - throw WgerHttpException(response); + Future wait(String reason) async { + final backoff = (initialDelay.inMilliseconds * math.pow(2, attempt - 1)).toInt(); + final jitter = random.nextInt((backoff * 0.25).toInt() + 1); // up to 25% jitter + final delay = backoff + jitter; + _logger.info('Retrying fetch for $uri, attempt $attempt (${delay}ms), reason: $reason'); + + await Future.delayed(Duration(milliseconds: delay)); } - // Process the response - return json.decode(utf8.decode(response.bodyBytes)) as dynamic; + while (true) { + try { + final response = await client + .get(uri, headers: getDefaultHeaders(includeAuth: true)) + .timeout(const Duration(seconds: 5)); + + if (response.statusCode >= 400) { + // Retry on server errors (5xx); e.g. 502 might be transient + if (response.statusCode >= 500 && attempt < maxRetries) { + attempt++; + await wait('status code ${response.statusCode}'); + continue; + } + throw WgerHttpException(response); + } + + return json.decode(utf8.decode(response.bodyBytes)) as dynamic; + } catch (e) { + final isRetryable = + e is SocketException || e is http.ClientException || e is TimeoutException; + if (isRetryable && attempt < maxRetries) { + attempt++; + await wait(e.toString()); + continue; + } + + rethrow; + } + } } /// Fetch and retrieve the overview list of objects, returns the JSON parsed response diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index db2394bdf..699e32d18 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -1100,9 +1100,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i18.Future fetch(Uri? uri) => + _i18.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i18.Future.value(), ) as _i18.Future); diff --git a/test/exercises/contribute_exercise_image_test.mocks.dart b/test/exercises/contribute_exercise_image_test.mocks.dart index c3685ed3e..b477e9d33 100644 --- a/test/exercises/contribute_exercise_image_test.mocks.dart +++ b/test/exercises/contribute_exercise_image_test.mocks.dart @@ -402,9 +402,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i14.Future fetch(Uri? uri) => + _i14.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i14.Future.value(), ) as _i14.Future); diff --git a/test/gallery/gallery_form_test.mocks.dart b/test/gallery/gallery_form_test.mocks.dart index e14d78381..3ec16dfa9 100644 --- a/test/gallery/gallery_form_test.mocks.dart +++ b/test/gallery/gallery_form_test.mocks.dart @@ -175,9 +175,17 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as Uri); @override - _i6.Future fetch(Uri? uri) => + _i6.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i6.Future.value(), ) as _i6.Future); diff --git a/test/gallery/gallery_screen_test.mocks.dart b/test/gallery/gallery_screen_test.mocks.dart index d1ab1318c..c9fe9e746 100644 --- a/test/gallery/gallery_screen_test.mocks.dart +++ b/test/gallery/gallery_screen_test.mocks.dart @@ -175,9 +175,17 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as Uri); @override - _i6.Future fetch(Uri? uri) => + _i6.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i6.Future.value(), ) as _i6.Future); diff --git a/test/measurements/measurement_provider_test.mocks.dart b/test/measurements/measurement_provider_test.mocks.dart index ef362a877..96f42b39a 100644 --- a/test/measurements/measurement_provider_test.mocks.dart +++ b/test/measurements/measurement_provider_test.mocks.dart @@ -112,9 +112,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/nutrition/nutritional_plan_screen_test.mocks.dart b/test/nutrition/nutritional_plan_screen_test.mocks.dart index 2fe3c4ac5..3ee7049aa 100644 --- a/test/nutrition/nutritional_plan_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plan_screen_test.mocks.dart @@ -122,9 +122,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/nutrition/nutritional_plans_screen_test.mocks.dart b/test/nutrition/nutritional_plans_screen_test.mocks.dart index c702d4015..5c9dae552 100644 --- a/test/nutrition/nutritional_plans_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plans_screen_test.mocks.dart @@ -357,9 +357,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/providers/base_provider.dart b/test/providers/base_provider.dart new file mode 100644 index 000000000..203973c3e --- /dev/null +++ b/test/providers/base_provider.dart @@ -0,0 +1,135 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/core/exceptions/http_exception.dart'; +import 'package:wger/providers/base_provider.dart'; + +import '../utils.dart'; +import 'base_provider.mocks.dart'; + +@GenerateMocks([Client]) +void main() { + final Uri testUri = Uri(scheme: 'https', host: 'localhost', path: 'api/v2/test/'); + + test('Retry on SocketException then succeeds', () async { + // Arrange + final mockClient = MockClient(); + var callCount = 0; + when(mockClient.get(testUri, headers: anyNamed('headers'))).thenAnswer((_) { + if (callCount == 0) { + callCount++; + return Future.error(const SocketException('conn fail')); + } + return Future.value(Response('{"ok": true}', 200)); + }); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + final result = await provider.fetch(testUri, initialDelay: const Duration(milliseconds: 1)); + + // Assert + expect(result, isA()); + expect(result['ok'], isTrue); + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(2); + }); + + test('Retry on 5xx then succeeds', () async { + // Arrange + final mockClient = MockClient(); + var callCount = 0; + when(mockClient.get(testUri, headers: anyNamed('headers'))).thenAnswer((_) { + if (callCount == 0) { + callCount++; + return Future.value(Response('{"msg":"error"}', 502)); + } + return Future.value(Response('{"ok": true}', 200)); + }); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + final result = await provider.fetch(testUri, initialDelay: const Duration(milliseconds: 1)); + + // Assert + expect(result, isA()); + expect(result['ok'], isTrue); + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(2); + }); + + test('Do not retry on 4xx client error', () async { + // Arrange + final mockClient = MockClient(); + when( + mockClient.get(testUri, headers: anyNamed('headers')), + ).thenAnswer((_) => Future.value(Response('{"error":"bad"}', 400))); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + + // Assert + await expectLater( + provider.fetch(testUri, initialDelay: const Duration(milliseconds: 1)), + throwsA(isA()), + ); + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(1); + }); + + test('Exceed max retries and rethrow after retries', () async { + // Arrange + final mockClient = MockClient(); + when( + mockClient.get(testUri, headers: anyNamed('headers')), + ).thenAnswer((_) => Future.error(ClientException('conn fail'))); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + dynamic caught; + try { + await provider.fetch(testUri, initialDelay: const Duration(milliseconds: 1)); + } catch (e) { + caught = e; + } + + // Assert + expect(caught, isA()); + // initial try + 3 retries = 4 calls + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(4); + }); + + test('Request succeeds without retries', () async { + // Arrange + final mockClient = MockClient(); + when( + mockClient.get(testUri, headers: anyNamed('headers')), + ).thenAnswer((_) => Future.value(Response('{"ok": true}', 200))); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + final result = await provider.fetch(testUri); + + // Assert + expect(result, isA()); + expect(result['ok'], isTrue); + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(1); + }); +} diff --git a/test/providers/base_provider.mocks.dart b/test/providers/base_provider.mocks.dart new file mode 100644 index 000000000..5111102b5 --- /dev/null +++ b/test/providers/base_provider.mocks.dart @@ -0,0 +1,218 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/providers/base_provider.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; +import 'dart:convert' as _i4; +import 'dart:typed_data' as _i6; + +import 'package:http/http.dart' as _i2; +import 'package:mockito/mockito.dart' as _i1; +import 'package:mockito/src/dummies.dart' as _i5; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { + _FakeStreamedResponse_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +/// A class which mocks [Client]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockClient extends _i1.Mock implements _i2.Client { + MockClient() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Future<_i2.Response> head(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#head, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> get(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#get, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> post( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> put( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> patch( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> delete( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future read(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i3.Future.value( + _i5.dummyValue( + this, + Invocation.method(#read, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future); + + @override + _i3.Future<_i6.Uint8List> readBytes( + Uri? url, { + Map? headers, + }) => + (super.noSuchMethod( + Invocation.method(#readBytes, [url], {#headers: headers}), + returnValue: _i3.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), + ) + as _i3.Future<_i6.Uint8List>); + + @override + _i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => + (super.noSuchMethod( + Invocation.method(#send, [request]), + returnValue: _i3.Future<_i2.StreamedResponse>.value( + _FakeStreamedResponse_1( + this, + Invocation.method(#send, [request]), + ), + ), + ) + as _i3.Future<_i2.StreamedResponse>); + + @override + void close() => super.noSuchMethod( + Invocation.method(#close, []), + returnValueForMissingStub: null, + ); +} diff --git a/test/routine/gym_mode/gym_mode_test.mocks.dart b/test/routine/gym_mode/gym_mode_test.mocks.dart index 6b3c882cc..810029486 100644 --- a/test/routine/gym_mode/gym_mode_test.mocks.dart +++ b/test/routine/gym_mode/gym_mode_test.mocks.dart @@ -201,9 +201,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i20.Future fetch(Uri? uri) => + _i20.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i20.Future.value(), ) as _i20.Future); diff --git a/test/routine/routine_screen_test.mocks.dart b/test/routine/routine_screen_test.mocks.dart index 99fe1643b..41f40bb3e 100644 --- a/test/routine/routine_screen_test.mocks.dart +++ b/test/routine/routine_screen_test.mocks.dart @@ -112,9 +112,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/routine/routines_provider_test.mocks.dart b/test/routine/routines_provider_test.mocks.dart index 063265063..f9125d598 100644 --- a/test/routine/routines_provider_test.mocks.dart +++ b/test/routine/routines_provider_test.mocks.dart @@ -151,9 +151,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i11.Future fetch(Uri? uri) => + _i11.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i11.Future.value(), ) as _i11.Future); diff --git a/test/routine/routines_screen_test.mocks.dart b/test/routine/routines_screen_test.mocks.dart index 2607f048f..ea1014f7b 100644 --- a/test/routine/routines_screen_test.mocks.dart +++ b/test/routine/routines_screen_test.mocks.dart @@ -112,9 +112,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/user/provider_test.mocks.dart b/test/user/provider_test.mocks.dart index 08bbf6366..ecf42fc80 100644 --- a/test/user/provider_test.mocks.dart +++ b/test/user/provider_test.mocks.dart @@ -112,9 +112,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/weight/weight_provider_test.mocks.dart b/test/weight/weight_provider_test.mocks.dart index 4cd18bb56..5fc97437f 100644 --- a/test/weight/weight_provider_test.mocks.dart +++ b/test/weight/weight_provider_test.mocks.dart @@ -112,9 +112,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 500), + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), returnValue: _i5.Future.value(), ) as _i5.Future); From 6620a83baa09e0b3389205e99252f4e80404efb6 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 14 Jan 2026 14:59:07 +0100 Subject: [PATCH 30/48] Improve html error detection In case the header is not correctly set, try to detect html error messages from the content itself --- lib/core/exceptions/http_exception.dart | 5 ++-- lib/helpers/errors.dart | 4 +-- lib/providers/auth.dart | 6 ++--- test/core/http_exception_test.dart | 34 +++++++++++++++++++++++-- 4 files changed, 39 insertions(+), 10 deletions(-) diff --git a/lib/core/exceptions/http_exception.dart b/lib/core/exceptions/http_exception.dart index 948b8975e..73cbc24c0 100644 --- a/lib/core/exceptions/http_exception.dart +++ b/lib/core/exceptions/http_exception.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -43,7 +43,8 @@ class WgerHttpException implements Exception { final dynamic responseBody = response.body; final contentType = response.headers[HttpHeaders.contentTypeHeader]; - if (contentType != null && contentType.contains('text/html')) { + if ((contentType != null && contentType.contains('text/html')) || + responseBody.toString().contains('. - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -51,8 +51,6 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? co return; } - final theme = Theme.of(dialogContext); - showDialog( context: dialogContext, builder: (ctx) => AlertDialog( diff --git a/lib/providers/auth.dart b/lib/providers/auth.dart index edb73a8d0..3f2e26fa8 100644 --- a/lib/providers/auth.dart +++ b/lib/providers/auth.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -58,7 +58,7 @@ class AuthProvider with ChangeNotifier { static const SERVER_VERSION_URL = 'version'; static const REGISTRATION_URL = 'register'; static const LOGIN_URL = 'login'; - static const TEST_URL = 'userprofile'; + static const USERPROFILE_URL = 'userprofile'; late http.Client client; @@ -150,7 +150,7 @@ class AuthProvider with ChangeNotifier { // Login using the API token if (apiToken != null && apiToken.isNotEmpty) { final response = await client.get( - makeUri(serverUrl, TEST_URL), + makeUri(serverUrl, USERPROFILE_URL), headers: { HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: getAppNameHeader(), diff --git a/test/core/http_exception_test.dart b/test/core/http_exception_test.dart index 26b7a7541..30ae455c8 100644 --- a/test/core/http_exception_test.dart +++ b/test/core/http_exception_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -25,20 +25,24 @@ import 'package:wger/core/exceptions/http_exception.dart'; void main() { group('WgerHttpException', () { test('parses valid JSON response', () { + // Arrange final resp = http.Response( '{"foo":"bar"}', 400, headers: {HttpHeaders.contentTypeHeader: 'application/json'}, ); + // Act final ex = WgerHttpException(resp); + // Assert expect(ex.type, ErrorType.json); expect(ex.errors['foo'], 'bar'); expect(ex.toString(), contains('WgerHttpException')); }); test('falls back on malformed JSON', () { + // Arrange const body = '{"foo":'; final resp = http.Response( body, @@ -46,13 +50,16 @@ void main() { headers: {HttpHeaders.contentTypeHeader: 'application/json'}, ); + // Act final ex = WgerHttpException(resp); + // Assert expect(ex.type, ErrorType.json); expect(ex.errors['unknown_error'], body); }); - test('detects HTML response', () { + test('detects HTML response from headers', () { + // Arrange const body = 'Error'; final resp = http.Response( body, @@ -60,16 +67,39 @@ void main() { headers: {HttpHeaders.contentTypeHeader: 'text/html; charset=utf-8'}, ); + // Act final ex = WgerHttpException(resp); + // Assert + expect(ex.type, ErrorType.html); + expect(ex.htmlError, body); + }); + + test('detects HTML response from content', () { + // Arrange + const body = 'Error'; + final resp = http.Response( + body, + 500, + headers: {HttpHeaders.contentTypeHeader: 'text/foo; charset=utf-8'}, + ); + + // Act + final ex = WgerHttpException(resp); + + // Assert expect(ex.type, ErrorType.html); expect(ex.htmlError, body); }); test('fromMap sets errors and type', () { + // Arrange final map = {'field': 'value'}; + + // Act final ex = WgerHttpException.fromMap(map); + // Assert expect(ex.type, ErrorType.json); expect(ex.errors, map); }); From 136607db2534a99013cb5f249c6291cf742649ee Mon Sep 17 00:00:00 2001 From: Benjamin Voisin Date: Mon, 5 Jan 2026 23:03:54 +0100 Subject: [PATCH 31/48] Translated using Weblate (French) Currently translated at 100.0% (369 of 369 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/fr/ --- lib/l10n/app_fr.arb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 429c9e541..8a5cfc2ce 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -199,7 +199,7 @@ "@reset": { "description": "Button text allowing the user to reset the entered values to the default" }, - "useCustomServer": "Utiliser le serveur personnalisé", + "useCustomServer": "Utiliser un serveur personnalisé", "@useCustomServer": { "description": "Toggle button allowing users to switch between the default and a custom wger server" }, From 7c0f47f548ad2ed629bfdc32b047fba623d49a1d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 14 Jan 2026 19:23:46 +0100 Subject: [PATCH 32/48] Bump dependencies in Gemfile.lock --- Gemfile.lock | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index 1d7388fd4..313cae7fe 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -8,8 +8,8 @@ GEM artifactory (3.0.17) atomos (0.1.3) aws-eventstream (1.4.0) - aws-partitions (1.1198.0) - aws-sdk-core (3.240.0) + aws-partitions (1.1203.0) + aws-sdk-core (3.241.3) aws-eventstream (~> 1, >= 1.3.0) aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) @@ -17,11 +17,11 @@ GEM bigdecimal jmespath (~> 1, >= 1.6.1) logger - aws-sdk-kms (1.118.0) - aws-sdk-core (~> 3, >= 3.239.1) + aws-sdk-kms (1.120.0) + aws-sdk-core (~> 3, >= 3.241.3) aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.208.0) - aws-sdk-core (~> 3, >= 3.234.0) + aws-sdk-s3 (1.211.0) + aws-sdk-core (~> 3, >= 3.241.3) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) aws-sigv4 (1.12.1) @@ -61,7 +61,7 @@ GEM faraday-em_synchrony (1.0.1) faraday-excon (1.1.0) faraday-httpclient (1.0.1) - faraday-multipart (1.1.1) + faraday-multipart (1.2.0) multipart-post (~> 2.0) faraday-net_http (1.0.2) faraday-net_http_persistent (1.2.0) @@ -171,7 +171,7 @@ GEM logger (1.7.0) mini_magick (4.13.2) mini_mime (1.1.5) - multi_json (1.18.0) + multi_json (1.19.1) multipart-post (2.4.1) mutex_m (0.3.0) nanaimo (0.4.0) @@ -180,7 +180,7 @@ GEM optparse (0.8.1) os (1.1.4) plist (3.7.2) - public_suffix (7.0.0) + public_suffix (7.0.2) rake (13.3.1) representable (3.2.0) declarative (< 0.1.0) From 5ef7671fabe7bce2969037c719f9a4b37002632d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 14 Jan 2026 21:53:59 +0100 Subject: [PATCH 33/48] Bump version of flatpak-flutter --- .github/workflows/build-linux.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index b24ac7f33..84e01dd5f 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -62,7 +62,7 @@ jobs: - name: Bump version and update manifest run: | - git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.10.0 ../flatpak-flutter + git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.11.0 ../flatpak-flutter pip install -r ../flatpak-flutter/requirements.txt python bump-wger-version.py ${{ inputs.ref }} ../flatpak-flutter/flatpak-flutter.py --app-module wger flatpak-flutter.json From 1146c3902f4223e8f2c295af8a6276a465499716 Mon Sep 17 00:00:00 2001 From: Github-Actions Date: Wed, 14 Jan 2026 20:58:11 +0000 Subject: [PATCH 34/48] Bump version to 1.9.5 --- flatpak/de.wger.flutter.metainfo.xml | 6 ++++++ pubspec.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/flatpak/de.wger.flutter.metainfo.xml b/flatpak/de.wger.flutter.metainfo.xml index 8560be108..9b0daf14f 100755 --- a/flatpak/de.wger.flutter.metainfo.xml +++ b/flatpak/de.wger.flutter.metainfo.xml @@ -84,6 +84,12 @@ + + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/1.9.5 +

Bug fixes and improvements.

diff --git a/pubspec.yaml b/pubspec.yaml index 14a8bd32d..9738a3133 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -21,7 +21,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # - the version number is taken from the git tag vX.Y.Z # - the build number is computed by reading the last one from the play store # and increasing by one -version: 1.9.4+140 +version: 1.9.5+150 environment: sdk: '>=3.8.0 <4.0.0' From 53dcbd8c6c6343e31f7ddf519d50402615cd4d86 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 16 Jan 2026 15:26:38 +0100 Subject: [PATCH 35/48] Don't mark nullable fields as "late" These will be null and we avoid LateInitializationError errors See #1079 --- lib/models/workouts/log.dart | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/models/workouts/log.dart b/lib/models/workouts/log.dart index 52b5c9f61..495ff7d37 100644 --- a/lib/models/workouts/log.dart +++ b/lib/models/workouts/log.dart @@ -51,7 +51,7 @@ class Log { late int routineId; @JsonKey(required: true, name: 'session') - late int? sessionId; + int? sessionId; @JsonKey(required: true) int? iteration; @@ -72,22 +72,22 @@ class Log { num? repetitionsTarget; @JsonKey(required: true, name: 'repetitions_unit') - late int? repetitionsUnitId; + int? repetitionsUnitId; @JsonKey(includeFromJson: false, includeToJson: false) - late RepetitionUnit? repetitionsUnitObj; + RepetitionUnit? repetitionsUnitObj; @JsonKey(required: true, fromJson: stringToNumNull, toJson: numToString) - late num? weight; + num? weight; @JsonKey(required: true, fromJson: stringToNumNull, toJson: numToString, name: 'weight_target') num? weightTarget; @JsonKey(required: true, name: 'weight_unit') - late int? weightUnitId; + int? weightUnitId; @JsonKey(includeFromJson: false, includeToJson: false) - late WeightUnit? weightUnitObj; + WeightUnit? weightUnitObj; @JsonKey(required: true, fromJson: utcIso8601ToLocalDate, toJson: dateToUtcIso8601) late DateTime date; From a249292afc7726b1b17c9e1d91792c5c56622483 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 16 Jan 2026 15:27:04 +0100 Subject: [PATCH 36/48] Don't show the session time if it's not set --- lib/widgets/dashboard/calendar.dart | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index e7175fd15..3fa378ee0 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -141,7 +141,9 @@ class _DashboardCalendarWidgetState extends State _events[date] = []; } var time = ''; - time = '(${timeToString(session.timeStart)} - ${timeToString(session.timeEnd)})'; + if (session.timeStart != null && session.timeEnd != null) { + time = '(${timeToString(session.timeStart)} - ${timeToString(session.timeEnd)})'; + } // Add events to lists _events[date]?.add( From 46fdf1efc7c5a011267fd9c72cb32b14b33a64cb Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 16 Jan 2026 15:28:09 +0100 Subject: [PATCH 37/48] Recreate generated files --- test/core/settings_test.mocks.dart | 2 +- test/exercises/contribute_exercise_image_test.mocks.dart | 2 +- test/gallery/gallery_form_test.mocks.dart | 2 +- test/gallery/gallery_screen_test.mocks.dart | 2 +- test/measurements/measurement_provider_test.mocks.dart | 2 +- test/nutrition/nutritional_plan_screen_test.mocks.dart | 2 +- test/nutrition/nutritional_plans_screen_test.mocks.dart | 2 +- test/routine/gym_mode/gym_mode_test.mocks.dart | 2 +- test/routine/routine_screen_test.mocks.dart | 2 +- test/routine/routines_provider_test.mocks.dart | 2 +- test/routine/routines_screen_test.mocks.dart | 2 +- test/user/provider_test.mocks.dart | 2 +- test/weight/weight_provider_test.mocks.dart | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index 699e32d18..4e060322a 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -1103,7 +1103,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { _i18.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/exercises/contribute_exercise_image_test.mocks.dart b/test/exercises/contribute_exercise_image_test.mocks.dart index b477e9d33..c20d1d75b 100644 --- a/test/exercises/contribute_exercise_image_test.mocks.dart +++ b/test/exercises/contribute_exercise_image_test.mocks.dart @@ -405,7 +405,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { _i14.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/gallery/gallery_form_test.mocks.dart b/test/gallery/gallery_form_test.mocks.dart index 3ec16dfa9..ad71121fa 100644 --- a/test/gallery/gallery_form_test.mocks.dart +++ b/test/gallery/gallery_form_test.mocks.dart @@ -178,7 +178,7 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { _i6.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/gallery/gallery_screen_test.mocks.dart b/test/gallery/gallery_screen_test.mocks.dart index c9fe9e746..7ea2e32fe 100644 --- a/test/gallery/gallery_screen_test.mocks.dart +++ b/test/gallery/gallery_screen_test.mocks.dart @@ -178,7 +178,7 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { _i6.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/measurements/measurement_provider_test.mocks.dart b/test/measurements/measurement_provider_test.mocks.dart index 96f42b39a..7c7667306 100644 --- a/test/measurements/measurement_provider_test.mocks.dart +++ b/test/measurements/measurement_provider_test.mocks.dart @@ -115,7 +115,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { _i5.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/nutrition/nutritional_plan_screen_test.mocks.dart b/test/nutrition/nutritional_plan_screen_test.mocks.dart index 3ee7049aa..9b7d92ee9 100644 --- a/test/nutrition/nutritional_plan_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plan_screen_test.mocks.dart @@ -125,7 +125,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { _i5.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/nutrition/nutritional_plans_screen_test.mocks.dart b/test/nutrition/nutritional_plans_screen_test.mocks.dart index 5c9dae552..1d9f0fb0c 100644 --- a/test/nutrition/nutritional_plans_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plans_screen_test.mocks.dart @@ -360,7 +360,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { _i5.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/routine/gym_mode/gym_mode_test.mocks.dart b/test/routine/gym_mode/gym_mode_test.mocks.dart index 810029486..9541140da 100644 --- a/test/routine/gym_mode/gym_mode_test.mocks.dart +++ b/test/routine/gym_mode/gym_mode_test.mocks.dart @@ -204,7 +204,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { _i20.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/routine/routine_screen_test.mocks.dart b/test/routine/routine_screen_test.mocks.dart index 41f40bb3e..7c623651c 100644 --- a/test/routine/routine_screen_test.mocks.dart +++ b/test/routine/routine_screen_test.mocks.dart @@ -115,7 +115,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { _i5.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/routine/routines_provider_test.mocks.dart b/test/routine/routines_provider_test.mocks.dart index f9125d598..3fc8c4eeb 100644 --- a/test/routine/routines_provider_test.mocks.dart +++ b/test/routine/routines_provider_test.mocks.dart @@ -154,7 +154,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { _i11.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/routine/routines_screen_test.mocks.dart b/test/routine/routines_screen_test.mocks.dart index ea1014f7b..95d3ca97e 100644 --- a/test/routine/routines_screen_test.mocks.dart +++ b/test/routine/routines_screen_test.mocks.dart @@ -115,7 +115,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { _i5.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/user/provider_test.mocks.dart b/test/user/provider_test.mocks.dart index ecf42fc80..4e7436d09 100644 --- a/test/user/provider_test.mocks.dart +++ b/test/user/provider_test.mocks.dart @@ -115,7 +115,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { _i5.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( diff --git a/test/weight/weight_provider_test.mocks.dart b/test/weight/weight_provider_test.mocks.dart index 5fc97437f..be3d38574 100644 --- a/test/weight/weight_provider_test.mocks.dart +++ b/test/weight/weight_provider_test.mocks.dart @@ -115,7 +115,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { _i5.Future fetch( Uri? uri, { int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 500), + Duration? initialDelay = const Duration(milliseconds: 250), }) => (super.noSuchMethod( Invocation.method( From 381d28d0441c29c40f3493d168edb50c655ddbd9 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 16 Jan 2026 15:40:27 +0100 Subject: [PATCH 38/48] Slightly refactor the fetch session data part in the calendar. In general, it doesn't make much sense that the sessions are the only data points that are loaded live every time, all the others are simply read from the respective providers. Hopefully all this can be removed when (if) we move to using a local sqlite db with powersync. --- lib/providers/routines.dart | 2 +- lib/widgets/dashboard/calendar.dart | 42 +++++++++++++---------------- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/lib/providers/routines.dart b/lib/providers/routines.dart index 56d163dc0..67210c406 100644 --- a/lib/providers/routines.dart +++ b/lib/providers/routines.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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 diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index 3fa378ee0..2809734c9 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -134,35 +134,29 @@ class _DashboardCalendarWidgetState extends State // Process workout sessions final routinesProvider = context.read(); - await routinesProvider.fetchSessionData().then((sessions) { - for (final session in sessions) { - final date = DateFormatLists.format(session.date); - if (!_events.containsKey(date)) { - _events[date] = []; - } - var time = ''; - if (session.timeStart != null && session.timeEnd != null) { - time = '(${timeToString(session.timeStart)} - ${timeToString(session.timeEnd)})'; - } - - // Add events to lists - _events[date]?.add( - Event( - EventType.session, - '${i18n.impression}: ${session.impressionAsString(context)} $time', - ), - ); - } - }); + final sessions = await routinesProvider.fetchSessionData(); if (!mounted) { return; } + for (final session in sessions) { + final date = DateFormatLists.format(session.date); + _events.putIfAbsent(date, () => []); + + final time = (session.timeStart != null && session.timeEnd != null) + ? '(${timeToString(session.timeStart)} - ${timeToString(session.timeEnd)})' + : ''; + + _events[date]?.add( + Event( + EventType.session, + '${i18n.impression}: ${session.impressionAsString(context)}${time.isNotEmpty ? ' $time' : ''}', + ), + ); + } + // Process nutritional plans - final NutritionPlansProvider nutritionProvider = Provider.of( - context, - listen: false, - ); + final nutritionProvider = context.read(); for (final plan in nutritionProvider.items) { for (final entry in plan.logEntriesValues.entries) { final date = DateFormatLists.format(entry.key); From ec153c51df7c28df3126b5dcf60223273354e306 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 16 Jan 2026 17:09:05 +0100 Subject: [PATCH 39/48] i18n and other cleanup --- lib/l10n/app_en.arb | 11 ++++ lib/models/trophies/trophy.g.dart | 18 ------- lib/providers/base_provider.dart | 4 +- lib/providers/gym_state.g.dart | 9 ++-- lib/providers/trophies.g.dart | 11 ++-- lib/screens/trophy_screen.dart | 4 +- .../dashboard/widgets/nothing_found.dart | 41 ++++++++------- lib/widgets/dashboard/widgets/routines.dart | 6 +-- lib/widgets/dashboard/widgets/trophies.dart | 24 +++++++-- lib/widgets/dashboard/widgets/weight.dart | 6 +-- .../routines/logs/day_logs_container.dart | 7 +-- .../logs/exercises_expansion_card.dart | 5 +- lib/widgets/trophies/trophies_overview.dart | 4 +- test/core/settings_test.mocks.dart | 17 +++++- .../contribute_exercise_image_test.mocks.dart | 17 +++++- test/gallery/gallery_form_test.mocks.dart | 17 +++++- test/gallery/gallery_screen_test.mocks.dart | 17 +++++- .../measurement_provider_test.mocks.dart | 17 +++++- .../nutritional_plan_screen_test.mocks.dart | 17 +++++- .../nutritional_plans_screen_test.mocks.dart | 17 +++++- .../routine/gym_mode/gym_mode_test.mocks.dart | 17 +++++- test/routine/routine_screen_test.mocks.dart | 17 +++++- .../routine/routines_provider_test.mocks.dart | 17 +++++- test/routine/routines_screen_test.mocks.dart | 17 +++++- .../trophies_provider_test.mocks.dart | 17 +++++- .../dashboard_trophies_widget_test.dart | 52 ++++++++++++++----- .../widgets/trophies_overview_test.dart | 4 ++ test/user/provider_test.mocks.dart | 17 +++++- test/weight/weight_provider_test.mocks.dart | 17 +++++- 29 files changed, 330 insertions(+), 114 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index efce357f9..7c116d7eb 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -233,6 +233,16 @@ "@comment": { "description": "Comment, additional information" }, + "topSet": "Top set: {value}", + "@topSet": { + "description": "Value is a representation of the set, like '10 x 80kg'", + "type": "text", + "placeholders": { + "value": { + "type": "String" + } + } + }, "impressionGood": "Good", "impressionNeutral": "Neutral", "impressionBad": "Bad", @@ -592,6 +602,7 @@ "@newEntry": { "description": "Title when adding a new entry such as a weight or log entry" }, + "noTrophies": "You have no trophies yet", "noWeightEntries": "You have no weight entries", "@noWeightEntries": { "description": "Message shown when the user has no logged weight entries" diff --git a/lib/models/trophies/trophy.g.dart b/lib/models/trophies/trophy.g.dart index aba73ac10..23eb2a47a 100644 --- a/lib/models/trophies/trophy.g.dart +++ b/lib/models/trophies/trophy.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 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 . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'trophy.dart'; diff --git a/lib/providers/base_provider.dart b/lib/providers/base_provider.dart index 1571b12d4..041871aef 100644 --- a/lib/providers/base_provider.dart +++ b/lib/providers/base_provider.dart @@ -73,7 +73,7 @@ class WgerBaseProvider { Uri uri, { int maxRetries = 3, Duration initialDelay = const Duration(milliseconds: 250), - String? language + String? language, }) async { int attempt = 0; final random = math.Random(); @@ -90,7 +90,7 @@ class WgerBaseProvider { while (true) { try { final response = await client - .get(uri, headers: getDefaultHeaders(includeAuth: true)) + .get(uri, headers: getDefaultHeaders(includeAuth: true, language: language)) .timeout(const Duration(seconds: 5)); if (response.statusCode >= 400) { diff --git a/lib/providers/gym_state.g.dart b/lib/providers/gym_state.g.dart index 1ddf6b8b1..4239a5496 100644 --- a/lib/providers/gym_state.g.dart +++ b/lib/providers/gym_state.g.dart @@ -10,10 +10,10 @@ part of 'gym_state.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(GymStateNotifier) -const gymStateProvider = GymStateNotifierProvider._(); +final gymStateProvider = GymStateNotifierProvider._(); final class GymStateNotifierProvider extends $NotifierProvider { - const GymStateNotifierProvider._() + GymStateNotifierProvider._() : super( from: null, argument: null, @@ -40,14 +40,13 @@ final class GymStateNotifierProvider extends $NotifierProvider r'8474afce33638bf67570fd64b64e9b5d171804d3'; +String _$gymStateNotifierHash() => r'3a0bb78e9f7e682ba93a40a73b170126b5eb5ca9'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref; final element = ref.element @@ -57,6 +56,6 @@ abstract class _$GymStateNotifier extends $Notifier { Object?, Object? >; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/providers/trophies.g.dart b/lib/providers/trophies.g.dart index 2f2a95e8f..3f1ffecd2 100644 --- a/lib/providers/trophies.g.dart +++ b/lib/providers/trophies.g.dart @@ -10,12 +10,12 @@ part of 'trophies.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(trophyRepository) -const trophyRepositoryProvider = TrophyRepositoryProvider._(); +final trophyRepositoryProvider = TrophyRepositoryProvider._(); final class TrophyRepositoryProvider extends $FunctionalProvider with $Provider { - const TrophyRepositoryProvider._() + TrophyRepositoryProvider._() : super( from: null, argument: null, @@ -51,11 +51,11 @@ final class TrophyRepositoryProvider String _$trophyRepositoryHash() => r'0699f0c0f7f324f3ba9b21420d9845a3e3096b61'; @ProviderFor(TrophyStateNotifier) -const trophyStateProvider = TrophyStateNotifierProvider._(); +final trophyStateProvider = TrophyStateNotifierProvider._(); final class TrophyStateNotifierProvider extends $NotifierProvider { - const TrophyStateNotifierProvider._() + TrophyStateNotifierProvider._() : super( from: null, argument: null, @@ -89,7 +89,6 @@ abstract class _$TrophyStateNotifier extends $Notifier { @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref; final element = ref.element @@ -99,6 +98,6 @@ abstract class _$TrophyStateNotifier extends $Notifier { Object?, Object? >; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/screens/trophy_screen.dart b/lib/screens/trophy_screen.dart index 0cc3cc023..5df5344be 100644 --- a/lib/screens/trophy_screen.dart +++ b/lib/screens/trophy_screen.dart @@ -31,9 +31,7 @@ class TrophyScreen extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: EmptyAppBar(AppLocalizations.of(context).trophies), - body: WidescreenWrapper( - child: TrophiesOverview(), - ), + body: const WidescreenWrapper(child: TrophiesOverview()), ); } } diff --git a/lib/widgets/dashboard/widgets/nothing_found.dart b/lib/widgets/dashboard/widgets/nothing_found.dart index 326d34175..86afc1405 100644 --- a/lib/widgets/dashboard/widgets/nothing_found.dart +++ b/lib/widgets/dashboard/widgets/nothing_found.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -22,10 +22,10 @@ import 'package:wger/theme/theme.dart'; class NothingFound extends StatelessWidget { final String _title; - final String _titleForm; - final Widget _form; + final String? _titleForm; + final Widget? _form; - const NothingFound(this._title, this._titleForm, this._form); + const NothingFound(this._title, [this._titleForm, this._form]); @override Widget build(BuildContext context) { @@ -35,21 +35,22 @@ class NothingFound extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_title), - IconButton( - iconSize: 30, - icon: const Icon(Icons.add_box, color: wgerPrimaryButtonColor), - onPressed: () { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - _titleForm, - hasListView: true, - _form, - ), - ); - }, - ), + if (_titleForm != null && _form != null) + IconButton( + iconSize: 30, + icon: const Icon(Icons.add_box, color: wgerPrimaryButtonColor), + onPressed: () { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + _titleForm, + hasListView: true, + _form, + ), + ); + }, + ), ], ), ); diff --git a/lib/widgets/dashboard/widgets/routines.dart b/lib/widgets/dashboard/widgets/routines.dart index 5077d9052..dba380452 100644 --- a/lib/widgets/dashboard/widgets/routines.dart +++ b/lib/widgets/dashboard/widgets/routines.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -58,7 +58,7 @@ class _DashboardRoutineWidgetState extends State { ), subtitle: Text( _hasContent - ? '${dateFormat.format(routine!.start)} - ${dateFormat.format(routine!.end)}' + ? '${dateFormat.format(routine!.start)} - ${dateFormat.format(routine.end)}' : '', ), leading: Icon( diff --git a/lib/widgets/dashboard/widgets/trophies.dart b/lib/widgets/dashboard/widgets/trophies.dart index e164e5d5b..42e1cfd4f 100644 --- a/lib/widgets/dashboard/widgets/trophies.dart +++ b/lib/widgets/dashboard/widgets/trophies.dart @@ -18,6 +18,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/trophies/trophy.dart'; import 'package:wger/providers/trophies.dart'; import 'package:wger/screens/trophy_screen.dart'; @@ -28,6 +29,7 @@ class DashboardTrophiesWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final trophiesState = ref.read(trophyStateProvider); + final i18n = AppLocalizations.of(context); return Card( color: Colors.transparent, @@ -36,9 +38,25 @@ class DashboardTrophiesWidget extends ConsumerWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (trophiesState.nonPrTrophies.isEmpty) - Padding( - padding: const EdgeInsets.all(16.0), - child: Text('No trophies yet', style: Theme.of(context).textTheme.bodyMedium), + Card( + child: Column( + children: [ + ListTile( + title: Text( + i18n.trophies, + style: Theme.of(context).textTheme.headlineSmall, + ), + // leading: Icon(Icons.widgets_outlined), + ), + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + i18n.noTrophies, + style: Theme.of(context).textTheme.bodyMedium, + ), + ), + ], + ), ) else SizedBox( diff --git a/lib/widgets/dashboard/widgets/weight.dart b/lib/widgets/dashboard/widgets/weight.dart index 35d407b20..d13e14199 100644 --- a/lib/widgets/dashboard/widgets/weight.dart +++ b/lib/widgets/dashboard/widgets/weight.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -42,7 +42,7 @@ class DashboardWeightWidget extends StatelessWidget { ); return Consumer( - builder: (context, _, __) => Card( + builder: (context, _, _) => Card( child: Column( mainAxisSize: MainAxisSize.min, children: [ diff --git a/lib/widgets/routines/logs/day_logs_container.dart b/lib/widgets/routines/logs/day_logs_container.dart index ed3ac3a41..506723d2e 100644 --- a/lib/widgets/routines/logs/day_logs_container.dart +++ b/lib/widgets/routines/logs/day_logs_container.dart @@ -18,7 +18,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:logging/logging.dart'; import 'package:wger/helpers/date.dart'; import 'package:wger/helpers/errors.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -33,9 +32,8 @@ import 'session_info.dart'; class DayLogWidget extends ConsumerWidget { final DateTime _date; final Routine _routine; - final _logger = Logger('DayLogWidget'); - DayLogWidget(this._date, this._routine); + const DayLogWidget(this._date, this._routine); @override Widget build(BuildContext context, WidgetRef ref) { @@ -53,9 +51,6 @@ class DayLogWidget extends ConsumerWidget { .where((t) => t.contextData?.sessionId == sessionApi.session.id) .toList(); - _logger.info(trophyState.prTrophies); - _logger.info(prTrophies); - return Column( spacing: 10, children: [ diff --git a/lib/widgets/routines/logs/exercises_expansion_card.dart b/lib/widgets/routines/logs/exercises_expansion_card.dart index ea9634e79..0a1a35169 100644 --- a/lib/widgets/routines/logs/exercises_expansion_card.dart +++ b/lib/widgets/routines/logs/exercises_expansion_card.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 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 @@ -74,6 +74,7 @@ class _ExerciseExpansionTile extends StatelessWidget { Widget build(BuildContext context) { final languageCode = Localizations.localeOf(context).languageCode; final theme = Theme.of(context); + final i18n = AppLocalizations.of(context); final topSet = logs.isEmpty ? null @@ -85,7 +86,7 @@ class _ExerciseExpansionTile extends StatelessWidget { return ExpansionTile( // leading: const Icon(Icons.fitness_center), title: Text(exercise.getTranslation(languageCode).name, style: theme.textTheme.titleMedium), - subtitle: Text('Top set: $topSetWeight $topSetWeightUnit'), + subtitle: Text(i18n.topSet('$topSetWeight $topSetWeightUnit')), children: logs.map((log) => _SetDataRow(log: log, userPrTrophies: userPrTrophies)).toList(), ); } diff --git a/lib/widgets/trophies/trophies_overview.dart b/lib/widgets/trophies/trophies_overview.dart index 706040dfa..4f37f087e 100644 --- a/lib/widgets/trophies/trophies_overview.dart +++ b/lib/widgets/trophies/trophies_overview.dart @@ -19,6 +19,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/helpers/material.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/trophies/user_trophy_progression.dart'; import 'package:wger/providers/trophies.dart'; @@ -28,6 +29,7 @@ class TrophiesOverview extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final trophyState = ref.watch(trophyStateProvider); + final i18n = AppLocalizations.of(context); // Responsive grid: determine columns based on screen width final width = MediaQuery.widthOf(context); @@ -48,7 +50,7 @@ class TrophiesOverview extends ConsumerWidget { child: Padding( padding: const EdgeInsets.all(16.0), child: Text( - 'No trophies yet', + i18n.noTrophies, style: Theme.of(context).textTheme.bodyLarge, textAlign: TextAlign.center, ), diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index e883c76de..a6192cd86 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -1104,9 +1104,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i18.Future fetch(Uri? uri, {String? language}) => + _i18.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i18.Future.value(), ) as _i18.Future); diff --git a/test/exercises/contribute_exercise_image_test.mocks.dart b/test/exercises/contribute_exercise_image_test.mocks.dart index c5c3b857c..58b8b260c 100644 --- a/test/exercises/contribute_exercise_image_test.mocks.dart +++ b/test/exercises/contribute_exercise_image_test.mocks.dart @@ -406,9 +406,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i14.Future fetch(Uri? uri, {String? language}) => + _i14.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i14.Future.value(), ) as _i14.Future); diff --git a/test/gallery/gallery_form_test.mocks.dart b/test/gallery/gallery_form_test.mocks.dart index a531b6ae9..5e0488962 100644 --- a/test/gallery/gallery_form_test.mocks.dart +++ b/test/gallery/gallery_form_test.mocks.dart @@ -179,9 +179,22 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as Uri); @override - _i6.Future fetch(Uri? uri, {String? language}) => + _i6.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i6.Future.value(), ) as _i6.Future); diff --git a/test/gallery/gallery_screen_test.mocks.dart b/test/gallery/gallery_screen_test.mocks.dart index 330d0c420..9b6edcbd7 100644 --- a/test/gallery/gallery_screen_test.mocks.dart +++ b/test/gallery/gallery_screen_test.mocks.dart @@ -179,9 +179,22 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as Uri); @override - _i6.Future fetch(Uri? uri, {String? language}) => + _i6.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i6.Future.value(), ) as _i6.Future); diff --git a/test/measurements/measurement_provider_test.mocks.dart b/test/measurements/measurement_provider_test.mocks.dart index c8c22b455..b5127325c 100644 --- a/test/measurements/measurement_provider_test.mocks.dart +++ b/test/measurements/measurement_provider_test.mocks.dart @@ -116,9 +116,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri, {String? language}) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/nutrition/nutritional_plan_screen_test.mocks.dart b/test/nutrition/nutritional_plan_screen_test.mocks.dart index 0ff6d2922..0ed491a6d 100644 --- a/test/nutrition/nutritional_plan_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plan_screen_test.mocks.dart @@ -126,9 +126,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri, {String? language}) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/nutrition/nutritional_plans_screen_test.mocks.dart b/test/nutrition/nutritional_plans_screen_test.mocks.dart index e42d7a17f..7fa3dec26 100644 --- a/test/nutrition/nutritional_plans_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plans_screen_test.mocks.dart @@ -361,9 +361,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri, {String? language}) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/routine/gym_mode/gym_mode_test.mocks.dart b/test/routine/gym_mode/gym_mode_test.mocks.dart index 8259d2c07..8d17cc4f2 100644 --- a/test/routine/gym_mode/gym_mode_test.mocks.dart +++ b/test/routine/gym_mode/gym_mode_test.mocks.dart @@ -205,9 +205,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i20.Future fetch(Uri? uri, {String? language}) => + _i20.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i20.Future.value(), ) as _i20.Future); diff --git a/test/routine/routine_screen_test.mocks.dart b/test/routine/routine_screen_test.mocks.dart index 8f05a8179..8a11f7d11 100644 --- a/test/routine/routine_screen_test.mocks.dart +++ b/test/routine/routine_screen_test.mocks.dart @@ -116,9 +116,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri, {String? language}) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/routine/routines_provider_test.mocks.dart b/test/routine/routines_provider_test.mocks.dart index ae7514683..e70a0c488 100644 --- a/test/routine/routines_provider_test.mocks.dart +++ b/test/routine/routines_provider_test.mocks.dart @@ -155,9 +155,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i11.Future fetch(Uri? uri, {String? language}) => + _i11.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i11.Future.value(), ) as _i11.Future); diff --git a/test/routine/routines_screen_test.mocks.dart b/test/routine/routines_screen_test.mocks.dart index 1dafb2ca2..5502f3a07 100644 --- a/test/routine/routines_screen_test.mocks.dart +++ b/test/routine/routines_screen_test.mocks.dart @@ -116,9 +116,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri, {String? language}) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/trophies/provider/trophies_provider_test.mocks.dart b/test/trophies/provider/trophies_provider_test.mocks.dart index 79887735e..15b59d6e6 100644 --- a/test/trophies/provider/trophies_provider_test.mocks.dart +++ b/test/trophies/provider/trophies_provider_test.mocks.dart @@ -116,9 +116,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri, {String? language}) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.dart b/test/trophies/widgets/dashboard_trophies_widget_test.dart index 687f13a06..d8549d92c 100644 --- a/test/trophies/widgets/dashboard_trophies_widget_test.dart +++ b/test/trophies/widgets/dashboard_trophies_widget_test.dart @@ -18,20 +18,39 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:network_image_mock/network_image_mock.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/trophies.dart'; import 'package:wger/widgets/dashboard/widgets/trophies.dart'; import '../../test_data/trophies.dart'; void main() { - testWidgets('DashboardTrophiesWidget shows trophies', (WidgetTester tester) async { - // Act - await mockNetworkImagesFor(() async { - await tester.pumpWidget( - ProviderScope( - overrides: [ + Future pumpOverview(WidgetTester tester, [List overrides = const []]) async { + await tester.pumpWidget( + ProviderScope( + overrides: overrides, + child: const MaterialApp( + locale: Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: DashboardTrophiesWidget(), + ), + ), + ), + ); + } + + group('DashboardTrophiesWidget tests', () { + testWidgets('shows trophies', (WidgetTester tester) async { + // Act + await mockNetworkImagesFor(() async { + await pumpOverview( + tester, + [ trophyStateProvider.overrideWithValue( TrophyState( userTrophies: getUserTrophies(), @@ -39,17 +58,22 @@ void main() { ), ), ], - child: const MaterialApp( - home: Scaffold( - body: DashboardTrophiesWidget(), - ), - ), - ), - ); + ); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('New Year, New Me'), findsOneWidget); + }); + }); + + testWidgets('handles empty results', (WidgetTester tester) async { + // Act + await pumpOverview(tester); await tester.pumpAndSettle(); // Assert - expect(find.text('New Year, New Me'), findsOneWidget); + expect(find.text('Trophies'), findsOneWidget); + expect(find.text('You have no trophies yet'), findsOneWidget); }); }); } diff --git a/test/trophies/widgets/trophies_overview_test.dart b/test/trophies/widgets/trophies_overview_test.dart index 0bc12cd5e..1a843a213 100644 --- a/test/trophies/widgets/trophies_overview_test.dart +++ b/test/trophies/widgets/trophies_overview_test.dart @@ -20,6 +20,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:network_image_mock/network_image_mock.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/trophies.dart'; import 'package:wger/widgets/trophies/trophies_overview.dart'; @@ -41,6 +42,9 @@ void main() { ), ], child: const MaterialApp( + locale: Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, home: Scaffold(body: TrophiesOverview()), ), ), diff --git a/test/user/provider_test.mocks.dart b/test/user/provider_test.mocks.dart index 6ff9bc854..d16a2200c 100644 --- a/test/user/provider_test.mocks.dart +++ b/test/user/provider_test.mocks.dart @@ -116,9 +116,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri, {String? language}) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); diff --git a/test/weight/weight_provider_test.mocks.dart b/test/weight/weight_provider_test.mocks.dart index bf00ffb14..e1ff97ab5 100644 --- a/test/weight/weight_provider_test.mocks.dart +++ b/test/weight/weight_provider_test.mocks.dart @@ -116,9 +116,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri, {String? language}) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri], {#language: language}), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); From 5574f74a2ffcdb0b238796cf2816b728ea58994c Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 17 Jan 2026 12:50:07 +0100 Subject: [PATCH 40/48] Move dashboard visibility settings to own screen This seems cleaner and can be opened from other places --- lib/l10n/app_en.arb | 1 + lib/main.dart | 9 +- lib/providers/user.dart | 74 +++++++--- lib/screens/dashboard.dart | 14 +- .../settings_dashboard_widgets_screen.dart | 38 +++++ ...creen.dart => settings_plates_screen.dart} | 0 lib/widgets/core/app_bar.dart | 136 ++++++++++-------- lib/widgets/core/settings.dart | 62 ++------ .../core/settings/dashboard_visibility.dart | 65 +++++++++ lib/widgets/routines/gym_mode/log_page.dart | 2 +- test/core/settings_test.dart | 25 ++-- test/core/settings_test.mocks.dart | 34 +++++ .../contribute_exercise_test.mocks.dart | 34 +++++ test/weight/weight_screen_test.mocks.dart | 34 +++++ 14 files changed, 375 insertions(+), 153 deletions(-) create mode 100644 lib/screens/settings_dashboard_widgets_screen.dart rename lib/screens/{configure_plates_screen.dart => settings_plates_screen.dart} (100%) create mode 100644 lib/widgets/core/settings/dashboard_visibility.dart diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 003c43ea6..6d845a4f1 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -100,6 +100,7 @@ "@labelWorkoutPlan": { "description": "Title for screen workout plan" }, + "dashboardWidgets": "Dashboard widgets", "labelDashboard": "Dashboard", "@labelDashboard": { "description": "Title for screen dashboard" diff --git a/lib/main.dart b/lib/main.dart index 477618816..577f346ea 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -37,7 +37,6 @@ import 'package:wger/providers/routines.dart'; import 'package:wger/providers/user.dart'; import 'package:wger/screens/add_exercise_screen.dart'; import 'package:wger/screens/auth_screen.dart'; -import 'package:wger/screens/configure_plates_screen.dart'; import 'package:wger/screens/dashboard.dart'; import 'package:wger/screens/exercise_screen.dart'; import 'package:wger/screens/exercises_screen.dart'; @@ -56,6 +55,8 @@ import 'package:wger/screens/routine_edit_screen.dart'; import 'package:wger/screens/routine_list_screen.dart'; import 'package:wger/screens/routine_logs_screen.dart'; import 'package:wger/screens/routine_screen.dart'; +import 'package:wger/screens/settings_dashboard_widgets_screen.dart'; +import 'package:wger/screens/settings_plates_screen.dart'; import 'package:wger/screens/splash_screen.dart'; import 'package:wger/screens/update_app_screen.dart'; import 'package:wger/screens/weight_screen.dart'; @@ -252,6 +253,8 @@ class MainApp extends StatelessWidget { SettingsPage.routeName: (ctx) => const SettingsPage(), LogOverviewPage.routeName: (ctx) => const LogOverviewPage(), ConfigurePlatesScreen.routeName: (ctx) => const ConfigurePlatesScreen(), + ConfigureDashboardWidgetsScreen.routeName: (ctx) => + const ConfigureDashboardWidgetsScreen(), }, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, diff --git a/lib/providers/user.dart b/lib/providers/user.dart index 27f7516d5..e2dc26645 100644 --- a/lib/providers/user.dart +++ b/lib/providers/user.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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 @@ -26,19 +26,36 @@ import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/models/user/profile.dart'; import 'package:wger/providers/base_provider.dart'; +enum DashboardWidget { + routines('routines'), + weight('weight'), + measurements('measurements'), + calendar('calendar'), + nutrition('nutrition'); + + final String value; + const DashboardWidget(this.value); + + static DashboardWidget? fromString(String s) { + for (final e in DashboardWidget.values) { + if (e.value == s) return e; + } + return null; + } +} + class UserProvider with ChangeNotifier { ThemeMode themeMode = ThemeMode.system; final WgerBaseProvider baseProvider; late SharedPreferencesAsync prefs; - // bool hideNutrition = false; // New: visibility state for dashboard widgets - Map dashboardWidgetVisibility = { - 'routines': true, - 'weight': true, - 'measurements': true, - 'calendar': true, - 'nutrition': true, + Map dashboardWidgetVisibility = { + DashboardWidget.routines: true, + DashboardWidget.weight: true, + DashboardWidget.measurements: true, + DashboardWidget.calendar: true, + DashboardWidget.nutrition: true, }; static const String PREFS_DASHBOARD_VISIBILITY = 'dashboardWidgetVisibility'; @@ -80,31 +97,47 @@ class UserProvider with ChangeNotifier { notifyListeners(); } - Future _loadDashboardVisibility() async { - final jsonString = await prefs.getString(PREFS_DASHBOARD_VISIBILITY); - if (jsonString != null) { - try { - final decoded = jsonDecode(jsonString) as Map; - dashboardWidgetVisibility = - decoded.map((k, v) => MapEntry(k, v as bool)); - } catch (_) { - // If parsing fails, keep defaults + Future _loadDashboardVisibility() async { + final jsonString = await prefs.getString(PREFS_DASHBOARD_VISIBILITY); + if (jsonString == null) { + return; + } + + try { + final decoded = jsonDecode(jsonString) as Map; + final Map loaded = {}; + + for (final entry in decoded.entries) { + final widget = DashboardWidget.fromString(entry.key); + if (widget != null) { + loaded[widget] = entry.value as bool; + } } + + if (loaded.isNotEmpty) { + dashboardWidgetVisibility = loaded; + } + } catch (_) { + // parsing failed -> keep defaults } notifyListeners(); } - bool isDashboardWidgetVisible(String key) { + bool isDashboardWidgetVisible(DashboardWidget key) { return dashboardWidgetVisibility[key] ?? true; } - Future setDashboardWidgetVisible(String key, bool visible) async { + Future setDashboardWidgetVisible(DashboardWidget key, bool visible) async { dashboardWidgetVisibility[key] = visible; + final Map serializable = { + for (final e in dashboardWidgetVisibility.entries) e.key.value: e.value, + }; + await prefs.setString( PREFS_DASHBOARD_VISIBILITY, - jsonEncode(dashboardWidgetVisibility), + jsonEncode(serializable), ); notifyListeners(); } @@ -133,7 +166,6 @@ class UserProvider with ChangeNotifier { } } - /// Save the user's profile to the server Future saveProfile() async { await baseProvider.post( diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index ae41069ef..dae86cb0c 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -19,13 +19,13 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/user.dart'; import 'package:wger/widgets/core/app_bar.dart'; import 'package:wger/widgets/dashboard/calendar.dart'; import 'package:wger/widgets/dashboard/widgets/measurements.dart'; import 'package:wger/widgets/dashboard/widgets/nutrition.dart'; import 'package:wger/widgets/dashboard/widgets/routines.dart'; import 'package:wger/widgets/dashboard/widgets/weight.dart'; -import 'package:wger/providers/user.dart'; class DashboardScreen extends StatelessWidget { const DashboardScreen({super.key}); @@ -42,19 +42,19 @@ class DashboardScreen extends StatelessWidget { padding: const EdgeInsets.all(10), child: Column( children: [ - if (user.isDashboardWidgetVisible('routines')) + if (user.isDashboardWidgetVisible(DashboardWidget.routines)) const DashboardRoutineWidget(), - if (user.isDashboardWidgetVisible('weight')) + if (user.isDashboardWidgetVisible(DashboardWidget.weight)) const DashboardWeightWidget(), - if (user.isDashboardWidgetVisible('measurements')) + if (user.isDashboardWidgetVisible(DashboardWidget.measurements)) const DashboardMeasurementWidget(), - if (user.isDashboardWidgetVisible('calendar')) + if (user.isDashboardWidgetVisible(DashboardWidget.calendar)) const DashboardCalendarWidget(), - if (user.isDashboardWidgetVisible('nutrition')) + if (user.isDashboardWidgetVisible(DashboardWidget.nutrition)) const DashboardNutritionWidget(), ], ), ), ); } -} \ No newline at end of file +} diff --git a/lib/screens/settings_dashboard_widgets_screen.dart b/lib/screens/settings_dashboard_widgets_screen.dart new file mode 100644 index 000000000..d3be77718 --- /dev/null +++ b/lib/screens/settings_dashboard_widgets_screen.dart @@ -0,0 +1,38 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/widgets/core/settings/dashboard_visibility.dart'; + +class ConfigureDashboardWidgetsScreen extends StatelessWidget { + static const routeName = '/ConfigureDashboardWidgetScreen'; + + const ConfigureDashboardWidgetsScreen({super.key}); + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + + return Scaffold( + appBar: AppBar(title: Text(i18n.dashboardWidgets)), + body: const WidescreenWrapper(child: SettingsDashboardVisibility()), + ); + } +} diff --git a/lib/screens/configure_plates_screen.dart b/lib/screens/settings_plates_screen.dart similarity index 100% rename from lib/screens/configure_plates_screen.dart rename to lib/screens/settings_plates_screen.dart diff --git a/lib/widgets/core/app_bar.dart b/lib/widgets/core/app_bar.dart index cf0948d53..be52f0638 100644 --- a/lib/widgets/core/app_bar.dart +++ b/lib/widgets/core/app_bar.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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 @@ -26,6 +26,7 @@ import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/routines.dart'; import 'package:wger/providers/user.dart'; import 'package:wger/screens/form_screen.dart'; +import 'package:wger/screens/settings_dashboard_widgets_screen.dart'; import 'package:wger/widgets/core/about.dart'; import 'package:wger/widgets/core/settings.dart'; import 'package:wger/widgets/user/forms.dart'; @@ -40,71 +41,19 @@ class MainAppBar extends StatelessWidget implements PreferredSizeWidget { return AppBar( title: Text(_title), actions: [ + IconButton( + icon: const Icon(Icons.widgets_outlined), + onPressed: () { + Navigator.of(context).pushNamed(ConfigureDashboardWidgetsScreen.routeName); + }, + ), IconButton( icon: const Icon(Icons.settings), onPressed: () async { return showDialog( context: context, builder: (BuildContext context) { - return AlertDialog( - title: Text(AppLocalizations.of(context).optionsLabel), - actions: [ - TextButton( - child: Text( - MaterialLocalizations.of(context).closeButtonLabel, - ), - onPressed: () => Navigator.of(context).pop(), - ), - ], - contentPadding: EdgeInsets.zero, - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - //dense: true, - leading: const Icon(Icons.person), - title: Text(AppLocalizations.of(context).userProfile), - onTap: () => Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).userProfile, - UserProfileForm( - context.read().profile!, - ), - ), - ), - ), - ListTile( - leading: const Icon(Icons.settings), - onTap: () => Navigator.of(context).pushNamed(SettingsPage.routeName), - title: Text(AppLocalizations.of(context).settingsTitle), - ), - ListTile( - leading: const Icon(Icons.info), - onTap: () => Navigator.of(context).pushNamed(AboutPage.routeName), - title: Text(AppLocalizations.of(context).aboutPageTitle), - ), - const Divider(), - ListTile( - //dense: true, - leading: const Icon(Icons.exit_to_app), - title: Text(AppLocalizations.of(context).logout), - onTap: () { - context.read().logout(); - context.read().clear(); - context.read().clear(); - context.read().clear(); - context.read().clear(); - context.read().clear(); - - Navigator.of(context).pop(); - Navigator.of(context).pushReplacementNamed('/'); - }, - ), - ], - ), - ); + return const MainSettingsDialog(); }, ); }, @@ -117,6 +66,73 @@ class MainAppBar extends StatelessWidget implements PreferredSizeWidget { Size get preferredSize => const Size.fromHeight(kToolbarHeight); } +class MainSettingsDialog extends StatelessWidget { + const MainSettingsDialog({super.key}); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(AppLocalizations.of(context).optionsLabel), + actions: [ + TextButton( + child: Text( + MaterialLocalizations.of(context).closeButtonLabel, + ), + onPressed: () => Navigator.of(context).pop(), + ), + ], + contentPadding: EdgeInsets.zero, + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + //dense: true, + leading: const Icon(Icons.person), + title: Text(AppLocalizations.of(context).userProfile), + onTap: () => Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).userProfile, + UserProfileForm( + context.read().profile!, + ), + ), + ), + ), + ListTile( + leading: const Icon(Icons.settings), + onTap: () => Navigator.of(context).pushNamed(SettingsPage.routeName), + title: Text(AppLocalizations.of(context).settingsTitle), + ), + ListTile( + leading: const Icon(Icons.info), + onTap: () => Navigator.of(context).pushNamed(AboutPage.routeName), + title: Text(AppLocalizations.of(context).aboutPageTitle), + ), + const Divider(), + ListTile( + //dense: true, + leading: const Icon(Icons.exit_to_app), + title: Text(AppLocalizations.of(context).logout), + onTap: () { + context.read().logout(); + context.read().clear(); + context.read().clear(); + context.read().clear(); + context.read().clear(); + context.read().clear(); + + Navigator.of(context).pop(); + Navigator.of(context).pushReplacementNamed('/'); + }, + ), + ], + ), + ); + } +} + /// App bar that only displays a title class EmptyAppBar extends StatelessWidget implements PreferredSizeWidget { final String _title; diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index 336e13b81..8ddcf0eed 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -16,17 +16,14 @@ * along with this program. If not, see . */ -//import 'package:drift/drift.dart'; import 'package:flutter/material.dart'; -import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/screens/configure_plates_screen.dart'; -import 'package:wger/widgets/core/settings/exercise_cache.dart'; -import 'package:wger/widgets/core/settings/ingredient_cache.dart'; -import 'package:wger/widgets/core/settings/theme.dart'; -import 'package:provider/provider.dart'; -import 'package:wger/providers/user.dart'; +import 'package:wger/screens/settings_dashboard_widgets_screen.dart'; +import 'package:wger/screens/settings_plates_screen.dart'; +import './settings/exercise_cache.dart'; +import './settings/ingredient_cache.dart'; +import './settings/theme.dart'; class SettingsPage extends StatelessWidget { static String routeName = '/SettingsPage'; @@ -48,44 +45,6 @@ class SettingsPage extends StatelessWidget { const SettingsIngredientCache(), ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)), const SettingsTheme(), - Consumer( - builder: (context, user, _) { - return Column( - children: [ - SwitchListTile( - title: const Text('Show routines on dashboard'), - value: user.isDashboardWidgetVisible('routines'), - onChanged: (v) => - user.setDashboardWidgetVisible('routines', v), - ), - SwitchListTile( - title: const Text('Show weight on dashboard'), - value: user.isDashboardWidgetVisible('weight'), - onChanged: (v) => - user.setDashboardWidgetVisible('weight', v), - ), - SwitchListTile( - title: const Text('Show measurements on dashboard'), - value: user.isDashboardWidgetVisible('measurements'), - onChanged: (v) => - user.setDashboardWidgetVisible('measurements', v), - ), - SwitchListTile( - title: const Text('Show calendar on dashboard'), - value: user.isDashboardWidgetVisible('calendar'), - onChanged: (v) => - user.setDashboardWidgetVisible('calendar', v), - ), - SwitchListTile( - title: const Text('Show nutrition on dashboard'), - value: user.isDashboardWidgetVisible('nutrition'), - onChanged: (v) => - user.setDashboardWidgetVisible('nutrition', v), - ), - ], - ); - }, - ), ListTile( title: Text(i18n.selectAvailablePlates), onTap: () { @@ -93,6 +52,13 @@ class SettingsPage extends StatelessWidget { }, trailing: const Icon(Icons.chevron_right), ), + ListTile( + title: Text(i18n.dashboardWidgets), + onTap: () { + Navigator.of(context).pushNamed(ConfigureDashboardWidgetsScreen.routeName); + }, + trailing: const Icon(Icons.chevron_right), + ), ], ), ); diff --git a/lib/widgets/core/settings/dashboard_visibility.dart b/lib/widgets/core/settings/dashboard_visibility.dart new file mode 100644 index 000000000..d00ead0b5 --- /dev/null +++ b/lib/widgets/core/settings/dashboard_visibility.dart @@ -0,0 +1,65 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/user.dart'; + +class SettingsDashboardVisibility extends StatelessWidget { + const SettingsDashboardVisibility({super.key}); + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + + return Consumer( + builder: (context, user, _) { + return Column( + children: [ + SwitchListTile( + title: Text(i18n.routines), + value: user.isDashboardWidgetVisible(DashboardWidget.routines), + onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.routines, v), + ), + SwitchListTile( + title: Text(i18n.weight), + value: user.isDashboardWidgetVisible(DashboardWidget.weight), + onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.weight, v), + ), + SwitchListTile( + title: Text(i18n.measurements), + value: user.isDashboardWidgetVisible(DashboardWidget.measurements), + onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.measurements, v), + ), + SwitchListTile( + title: Text(i18n.calendar), + value: user.isDashboardWidgetVisible(DashboardWidget.calendar), + onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.calendar, v), + ), + SwitchListTile( + title: Text(i18n.nutritionalPlans), + value: user.isDashboardWidgetVisible(DashboardWidget.nutrition), + onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.nutrition, v), + ), + ], + ); + }, + ); + } +} diff --git a/lib/widgets/routines/gym_mode/log_page.dart b/lib/widgets/routines/gym_mode/log_page.dart index 088836d65..49865e7ea 100644 --- a/lib/widgets/routines/gym_mode/log_page.dart +++ b/lib/widgets/routines/gym_mode/log_page.dart @@ -31,7 +31,7 @@ import 'package:wger/providers/gym_log_state.dart'; import 'package:wger/providers/gym_state.dart'; import 'package:wger/providers/plate_weights.dart'; import 'package:wger/providers/routines.dart'; -import 'package:wger/screens/configure_plates_screen.dart'; +import 'package:wger/screens/settings_plates_screen.dart'; import 'package:wger/widgets/core/core.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; import 'package:wger/widgets/routines/forms/reps_unit.dart'; diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index b29346827..bb27464b1 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -49,13 +49,9 @@ void main() { setUp(() { when(mockUserProvider.themeMode).thenReturn(ThemeMode.system); + when(mockUserProvider.isDashboardWidgetVisible(any)).thenReturn(true); when(mockExerciseProvider.exercises).thenReturn(getTestExercises()); when(mockNutritionProvider.ingredients).thenReturn([ingredient1, ingredient2]); - when(mockUserProvider.isDashboardWidgetVisible('routines')).thenReturn(true); - when(mockUserProvider.isDashboardWidgetVisible('weight')).thenReturn(true); - when(mockUserProvider.isDashboardWidgetVisible('measurements')).thenReturn(true); - when(mockUserProvider.isDashboardWidgetVisible('calendar')).thenReturn(true); - when(mockUserProvider.isDashboardWidgetVisible('nutrition')).thenReturn(true); }); Widget createSettingsScreen({locale = 'en'}) { @@ -105,24 +101,27 @@ void main() { group('Theme settings', () { test('Default theme is system', () async { when(mockSharedPreferences.getBool(PREFS_USER_DARK_THEME)).thenAnswer((_) async => null); - when(mockSharedPreferences.getString('dashboardWidgetVisibility')) - .thenAnswer((_) async => null); + when( + mockSharedPreferences.getString('dashboardWidgetVisibility'), + ).thenAnswer((_) async => null); final userProvider = await UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); expect(userProvider.themeMode, ThemeMode.system); }); test('Loads light theme', () async { when(mockSharedPreferences.getBool(PREFS_USER_DARK_THEME)).thenAnswer((_) async => false); - when(mockSharedPreferences.getString('dashboardWidgetVisibility')) - .thenAnswer((_) async => null); + when( + mockSharedPreferences.getString('dashboardWidgetVisibility'), + ).thenAnswer((_) async => null); final userProvider = await UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); expect(userProvider.themeMode, ThemeMode.light); }); test('Saves theme to prefs', () { when(mockSharedPreferences.getBool(any)).thenAnswer((_) async => null); - when(mockSharedPreferences.getString('dashboardWidgetVisibility')) - .thenAnswer((_) async => null); + when( + mockSharedPreferences.getString('dashboardWidgetVisibility'), + ).thenAnswer((_) async => null); final userProvider = UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); userProvider.setThemeMode(ThemeMode.dark); verify(mockSharedPreferences.setBool(PREFS_USER_DARK_THEME, true)).called(1); diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index 4e060322a..b7dc303fe 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -943,6 +943,14 @@ class MockUserProvider extends _i1.Mock implements _i21.UserProvider { ) as _i14.SharedPreferencesAsync); + @override + Map<_i21.DashboardWidget, bool> get dashboardWidgetVisibility => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgetVisibility), + returnValue: <_i21.DashboardWidget, bool>{}, + ) + as Map<_i21.DashboardWidget, bool>); + @override set themeMode(_i22.ThemeMode? value) => super.noSuchMethod( Invocation.setter(#themeMode, value), @@ -955,6 +963,12 @@ class MockUserProvider extends _i1.Mock implements _i21.UserProvider { returnValueForMissingStub: null, ); + @override + set dashboardWidgetVisibility(Map<_i21.DashboardWidget, bool>? value) => super.noSuchMethod( + Invocation.setter(#dashboardWidgetVisibility, value), + returnValueForMissingStub: null, + ); + @override set profile(_i23.Profile? value) => super.noSuchMethod( Invocation.setter(#profile, value), @@ -971,6 +985,26 @@ class MockUserProvider extends _i1.Mock implements _i21.UserProvider { returnValueForMissingStub: null, ); + @override + bool isDashboardWidgetVisible(_i21.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i18.Future setDashboardWidgetVisible( + _i21.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i18.Future.value(), + returnValueForMissingStub: _i18.Future.value(), + ) + as _i18.Future); + @override void setThemeMode(_i22.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), diff --git a/test/exercises/contribute_exercise_test.mocks.dart b/test/exercises/contribute_exercise_test.mocks.dart index 726b8a14f..c3defcf4f 100644 --- a/test/exercises/contribute_exercise_test.mocks.dart +++ b/test/exercises/contribute_exercise_test.mocks.dart @@ -389,6 +389,14 @@ class MockUserProvider extends _i1.Mock implements _i17.UserProvider { ) as _i4.SharedPreferencesAsync); + @override + Map<_i17.DashboardWidget, bool> get dashboardWidgetVisibility => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgetVisibility), + returnValue: <_i17.DashboardWidget, bool>{}, + ) + as Map<_i17.DashboardWidget, bool>); + @override set themeMode(_i18.ThemeMode? value) => super.noSuchMethod( Invocation.setter(#themeMode, value), @@ -401,6 +409,12 @@ class MockUserProvider extends _i1.Mock implements _i17.UserProvider { returnValueForMissingStub: null, ); + @override + set dashboardWidgetVisibility(Map<_i17.DashboardWidget, bool>? value) => super.noSuchMethod( + Invocation.setter(#dashboardWidgetVisibility, value), + returnValueForMissingStub: null, + ); + @override set profile(_i19.Profile? value) => super.noSuchMethod( Invocation.setter(#profile, value), @@ -417,6 +431,26 @@ class MockUserProvider extends _i1.Mock implements _i17.UserProvider { returnValueForMissingStub: null, ); + @override + bool isDashboardWidgetVisible(_i17.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i15.Future setDashboardWidgetVisible( + _i17.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i15.Future.value(), + returnValueForMissingStub: _i15.Future.value(), + ) + as _i15.Future); + @override void setThemeMode(_i18.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), diff --git a/test/weight/weight_screen_test.mocks.dart b/test/weight/weight_screen_test.mocks.dart index 8f508d55c..eac9ecd40 100644 --- a/test/weight/weight_screen_test.mocks.dart +++ b/test/weight/weight_screen_test.mocks.dart @@ -231,6 +231,14 @@ class MockUserProvider extends _i1.Mock implements _i13.UserProvider { ) as _i4.SharedPreferencesAsync); + @override + Map<_i13.DashboardWidget, bool> get dashboardWidgetVisibility => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgetVisibility), + returnValue: <_i13.DashboardWidget, bool>{}, + ) + as Map<_i13.DashboardWidget, bool>); + @override set themeMode(_i14.ThemeMode? value) => super.noSuchMethod( Invocation.setter(#themeMode, value), @@ -243,6 +251,12 @@ class MockUserProvider extends _i1.Mock implements _i13.UserProvider { returnValueForMissingStub: null, ); + @override + set dashboardWidgetVisibility(Map<_i13.DashboardWidget, bool>? value) => super.noSuchMethod( + Invocation.setter(#dashboardWidgetVisibility, value), + returnValueForMissingStub: null, + ); + @override set profile(_i15.Profile? value) => super.noSuchMethod( Invocation.setter(#profile, value), @@ -259,6 +273,26 @@ class MockUserProvider extends _i1.Mock implements _i13.UserProvider { returnValueForMissingStub: null, ); + @override + bool isDashboardWidgetVisible(_i13.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i11.Future setDashboardWidgetVisible( + _i13.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i11.Future.value(), + returnValueForMissingStub: _i11.Future.value(), + ) + as _i11.Future); + @override void setThemeMode(_i14.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), From b81331609af2a325546b4a36da49cd1ec9ea09da Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 17 Jan 2026 13:23:55 +0100 Subject: [PATCH 41/48] Also allow changing the order of the dashboard widgets This makes the behaviour more consistent and allows users to remove widgets they won't be using, like the trophies --- lib/providers/user.dart | 111 +++--- lib/screens/dashboard.dart | 33 +- lib/widgets/core/settings.dart | 8 - .../core/settings/dashboard_visibility.dart | 69 ++-- .../settings_dashboard_visibility_test.dart | 121 ++++++ ...tings_dashboard_visibility_test.mocks.dart | 349 ++++++++++++++++++ test/core/settings_test.dart | 16 +- test/core/settings_test.mocks.dart | 23 +- test/core/validators_test.mocks.dart | 11 + .../contribute_exercise_test.mocks.dart | 23 +- test/user/provider_test.dart | 82 +++- test/weight/weight_screen_test.mocks.dart | 23 +- 12 files changed, 735 insertions(+), 134 deletions(-) create mode 100644 test/core/settings_dashboard_visibility_test.dart create mode 100644 test/core/settings_dashboard_visibility_test.mocks.dart diff --git a/lib/providers/user.dart b/lib/providers/user.dart index e2dc26645..e2c4c0a86 100644 --- a/lib/providers/user.dart +++ b/lib/providers/user.dart @@ -19,6 +19,7 @@ import 'dart:async'; import 'dart:convert'; +import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/helpers/consts.dart'; @@ -28,44 +29,48 @@ import 'package:wger/providers/base_provider.dart'; enum DashboardWidget { routines('routines'), + nutrition('nutrition'), weight('weight'), measurements('measurements'), - calendar('calendar'), - nutrition('nutrition'); + calendar('calendar'); final String value; const DashboardWidget(this.value); static DashboardWidget? fromString(String s) { for (final e in DashboardWidget.values) { - if (e.value == s) return e; + if (e.value == s) { + return e; + } } return null; } } +class DashboardItem { + final DashboardWidget widget; + bool isVisible; + + DashboardItem(this.widget, {this.isVisible = true}); + + Map toJson() => { + 'widget': widget.value, + 'visible': isVisible, + }; +} + class UserProvider with ChangeNotifier { ThemeMode themeMode = ThemeMode.system; final WgerBaseProvider baseProvider; late SharedPreferencesAsync prefs; - // New: visibility state for dashboard widgets - Map dashboardWidgetVisibility = { - DashboardWidget.routines: true, - DashboardWidget.weight: true, - DashboardWidget.measurements: true, - DashboardWidget.calendar: true, - DashboardWidget.nutrition: true, - }; - - static const String PREFS_DASHBOARD_VISIBILITY = 'dashboardWidgetVisibility'; - UserProvider(this.baseProvider, {SharedPreferencesAsync? prefs}) { this.prefs = prefs ?? PreferenceHelper.asyncPref; _loadThemeMode(); - _loadDashboardVisibility(); + _loadDashboardConfig(); } + static const String PREFS_DASHBOARD_CONFIG = 'dashboardConfig'; static const PROFILE_URL = 'userprofile'; static const VERIFY_EMAIL = 'verify-email'; @@ -76,15 +81,6 @@ class UserProvider with ChangeNotifier { profile = null; } - // // change the unit of plates - // void changeUnit({changeTo = 'kg'}) { - // if (changeTo == 'kg') { - // profile?.weightUnitStr = 'lb'; - // } else { - // profile?.weightUnitStr = 'kg'; - // } - // } - // Load theme mode from SharedPreferences Future _loadThemeMode() async { final prefsDarkMode = await prefs.getBool(PREFS_USER_DARK_THEME); @@ -98,47 +94,76 @@ class UserProvider with ChangeNotifier { notifyListeners(); } - Future _loadDashboardVisibility() async { - final jsonString = await prefs.getString(PREFS_DASHBOARD_VISIBILITY); + // Dashboard configuration + List _dashboardItems = DashboardWidget.values + .map((w) => DashboardItem(w)) + .toList(); + + List get dashboardOrder => _dashboardItems.map((e) => e.widget).toList(); + + Future _loadDashboardConfig() async { + final jsonString = await prefs.getString(PREFS_DASHBOARD_CONFIG); if (jsonString == null) { + notifyListeners(); return; } try { - final decoded = jsonDecode(jsonString) as Map; - final Map loaded = {}; + final List decoded = jsonDecode(jsonString); + final List loaded = []; - for (final entry in decoded.entries) { - final widget = DashboardWidget.fromString(entry.key); + for (final item in decoded) { + final widget = DashboardWidget.fromString(item['widget']); if (widget != null) { - loaded[widget] = entry.value as bool; + loaded.add( + DashboardItem(widget, isVisible: item['visible'] as bool), + ); } } - if (loaded.isNotEmpty) { - dashboardWidgetVisibility = loaded; + // Add any missing widgets (e.g. newly added features) + for (final widget in DashboardWidget.values) { + if (!loaded.any((item) => item.widget == widget)) { + loaded.add(DashboardItem(widget)); + } } + + _dashboardItems = loaded; } catch (_) { // parsing failed -> keep defaults } - notifyListeners(); } + Future _saveDashboardConfig() async { + final serializable = _dashboardItems.map((e) => e.toJson()).toList(); + await prefs.setString(PREFS_DASHBOARD_CONFIG, jsonEncode(serializable)); + } + bool isDashboardWidgetVisible(DashboardWidget key) { - return dashboardWidgetVisibility[key] ?? true; + final widget = _dashboardItems.firstWhereOrNull((e) => e.widget == key); + return widget == null || widget.isVisible; } Future setDashboardWidgetVisible(DashboardWidget key, bool visible) async { - dashboardWidgetVisibility[key] = visible; - final Map serializable = { - for (final e in dashboardWidgetVisibility.entries) e.key.value: e.value, - }; + final item = _dashboardItems.firstWhereOrNull((e) => e.widget == key); + if (item == null) { + return; + } - await prefs.setString( - PREFS_DASHBOARD_VISIBILITY, - jsonEncode(serializable), - ); + item.isVisible = visible; + await _saveDashboardConfig(); + notifyListeners(); + } + + Future setDashboardOrder(int oldIndex, int newIndex) async { + if (oldIndex < newIndex) { + newIndex -= 1; + } + final item = _dashboardItems.removeAt(oldIndex); + _dashboardItems.insert(newIndex, item); + + await _saveDashboardConfig(); notifyListeners(); } diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index dae86cb0c..b7162bd77 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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 @@ -32,6 +32,21 @@ class DashboardScreen extends StatelessWidget { static const routeName = '/dashboard'; + Widget _getDashboardWidget(DashboardWidget widget) { + switch (widget) { + case DashboardWidget.routines: + return const DashboardRoutineWidget(); + case DashboardWidget.weight: + return const DashboardWeightWidget(); + case DashboardWidget.measurements: + return const DashboardMeasurementWidget(); + case DashboardWidget.calendar: + return const DashboardCalendarWidget(); + case DashboardWidget.nutrition: + return const DashboardNutritionWidget(); + } + } + @override Widget build(BuildContext context) { final user = Provider.of(context); @@ -41,18 +56,10 @@ class DashboardScreen extends StatelessWidget { body: SingleChildScrollView( padding: const EdgeInsets.all(10), child: Column( - children: [ - if (user.isDashboardWidgetVisible(DashboardWidget.routines)) - const DashboardRoutineWidget(), - if (user.isDashboardWidgetVisible(DashboardWidget.weight)) - const DashboardWeightWidget(), - if (user.isDashboardWidgetVisible(DashboardWidget.measurements)) - const DashboardMeasurementWidget(), - if (user.isDashboardWidgetVisible(DashboardWidget.calendar)) - const DashboardCalendarWidget(), - if (user.isDashboardWidgetVisible(DashboardWidget.nutrition)) - const DashboardNutritionWidget(), - ], + children: user.dashboardOrder + .where((w) => user.isDashboardWidgetVisible(w)) + .map(_getDashboardWidget) + .toList(), ), ), ); diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index 8ddcf0eed..014b281d9 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -18,7 +18,6 @@ import 'package:flutter/material.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/screens/settings_dashboard_widgets_screen.dart'; import 'package:wger/screens/settings_plates_screen.dart'; import './settings/exercise_cache.dart'; @@ -52,13 +51,6 @@ class SettingsPage extends StatelessWidget { }, trailing: const Icon(Icons.chevron_right), ), - ListTile( - title: Text(i18n.dashboardWidgets), - onTap: () { - Navigator.of(context).pushNamed(ConfigureDashboardWidgetsScreen.routeName); - }, - trailing: const Icon(Icons.chevron_right), - ), ], ), ); diff --git a/lib/widgets/core/settings/dashboard_visibility.dart b/lib/widgets/core/settings/dashboard_visibility.dart index d00ead0b5..b7d110b89 100644 --- a/lib/widgets/core/settings/dashboard_visibility.dart +++ b/lib/widgets/core/settings/dashboard_visibility.dart @@ -28,36 +28,49 @@ class SettingsDashboardVisibility extends StatelessWidget { Widget build(BuildContext context) { final i18n = AppLocalizations.of(context); + String getTitle(DashboardWidget w) { + switch (w) { + case DashboardWidget.routines: + return i18n.routines; + case DashboardWidget.weight: + return i18n.weight; + case DashboardWidget.measurements: + return i18n.measurements; + case DashboardWidget.calendar: + return i18n.calendar; + case DashboardWidget.nutrition: + return i18n.nutritionalPlans; + } + } + return Consumer( builder: (context, user, _) { - return Column( - children: [ - SwitchListTile( - title: Text(i18n.routines), - value: user.isDashboardWidgetVisible(DashboardWidget.routines), - onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.routines, v), - ), - SwitchListTile( - title: Text(i18n.weight), - value: user.isDashboardWidgetVisible(DashboardWidget.weight), - onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.weight, v), - ), - SwitchListTile( - title: Text(i18n.measurements), - value: user.isDashboardWidgetVisible(DashboardWidget.measurements), - onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.measurements, v), - ), - SwitchListTile( - title: Text(i18n.calendar), - value: user.isDashboardWidgetVisible(DashboardWidget.calendar), - onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.calendar, v), - ), - SwitchListTile( - title: Text(i18n.nutritionalPlans), - value: user.isDashboardWidgetVisible(DashboardWidget.nutrition), - onChanged: (v) => user.setDashboardWidgetVisible(DashboardWidget.nutrition, v), - ), - ], + return ReorderableListView( + physics: const NeverScrollableScrollPhysics(), + buildDefaultDragHandles: false, + onReorder: user.setDashboardOrder, + children: user.dashboardOrder.asMap().entries.map((entry) { + final index = entry.key; + final w = entry.value; + + return ListTile( + key: ValueKey(w), + title: Text(getTitle(w)), + leading: IconButton( + icon: user.isDashboardWidgetVisible(w) + ? const Icon(Icons.visibility) + : const Icon(Icons.visibility_off, color: Colors.grey), + onPressed: () => user.setDashboardWidgetVisible( + w, + !user.isDashboardWidgetVisible(w), + ), + ), + trailing: ReorderableDragStartListener( + index: index, + child: const Icon(Icons.drag_handle), + ), + ); + }).toList(), ); }, ); diff --git a/test/core/settings_dashboard_visibility_test.dart b/test/core/settings_dashboard_visibility_test.dart new file mode 100644 index 000000000..a171bbd42 --- /dev/null +++ b/test/core/settings_dashboard_visibility_test.dart @@ -0,0 +1,121 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:provider/provider.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/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/user.dart'; +import 'package:wger/widgets/core/settings/dashboard_visibility.dart'; + +import 'settings_dashboard_visibility_test.mocks.dart'; + +@GenerateMocks([ + UserProvider, + WgerBaseProvider, +]) +void main() { + late UserProvider userProvider; + late MockWgerBaseProvider mockBaseProvider; + + setUp(() { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + mockBaseProvider = MockWgerBaseProvider(); + userProvider = UserProvider(mockBaseProvider); + }); + + Widget createWidget() { + return ChangeNotifierProvider.value( + value: userProvider, + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SettingsDashboardVisibility(), + ), + ), + ); + } + + testWidgets('renders list of dashboard widgets', (tester) async { + await tester.pumpWidget(createWidget()); + await tester.pumpAndSettle(); + + // Verify all items are present + expect(find.byType(ListTile), findsNWidgets(DashboardWidget.values.length)); + expect(find.text('Routines'), findsOneWidget); + }); + + testWidgets('toggle visibility updates provider', (tester) async { + await tester.pumpWidget(createWidget()); + await tester.pumpAndSettle(); + + // Routines should be visible initally (default is true) + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), true); + + // Find the visibility icon for Routines + final routineTile = find.byKey(const ValueKey(DashboardWidget.routines)); + final iconBtn = find.descendant(of: routineTile, matching: find.byType(IconButton)); + + // Check icon is 'visibility' + expect(find.descendant(of: iconBtn, matching: find.byIcon(Icons.visibility)), findsOneWidget); + + // Tap to toggle + await tester.tap(iconBtn); + await tester.pump(); // re-render + + // Check provider state + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), false); + + // Check icon is 'visibility_off' + expect( + find.descendant(of: iconBtn, matching: find.byIcon(Icons.visibility_off)), + findsOneWidget, + ); + }); + + // Reordering test is a bit flaky without full drag setup, but we can try + testWidgets('dragging reorders items', (tester) async { + await tester.pumpWidget(createWidget()); + await tester.pumpAndSettle(); + + // Initial order: routines, nutrition, weight... + expect(userProvider.dashboardOrder[0], DashboardWidget.routines); + expect(userProvider.dashboardOrder[1], DashboardWidget.nutrition); + + // Find drag handle for Routines (index 0) + final handleFinder = find.byIcon(Icons.drag_handle); + final firstHandle = handleFinder.at(0); + // final secondHandle = handleFinder.at(1); + + // Drag first item down + await tester.drag(firstHandle, const Offset(0, 100)); // Drag down enough to swap + await tester.pumpAndSettle(); + + // Verify order changed + // If swapped with second item (nutrition) and maybe third (weight) depending on height + // Based on running test: index 0 is nutrition, index 1 is weight. + expect(userProvider.dashboardOrder[0], DashboardWidget.nutrition); + expect(userProvider.dashboardOrder[1], DashboardWidget.weight); + expect(userProvider.dashboardOrder[2], DashboardWidget.routines); + }); +} diff --git a/test/core/settings_dashboard_visibility_test.mocks.dart b/test/core/settings_dashboard_visibility_test.mocks.dart new file mode 100644 index 000000000..01803e1b2 --- /dev/null +++ b/test/core/settings_dashboard_visibility_test.mocks.dart @@ -0,0 +1,349 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/core/settings_dashboard_visibility_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i9; +import 'dart:ui' as _i10; + +import 'package:flutter/material.dart' as _i7; +import 'package:http/http.dart' as _i5; +import 'package:mockito/mockito.dart' as _i1; +import 'package:shared_preferences/shared_preferences.dart' as _i3; +import 'package:wger/models/user/profile.dart' as _i8; +import 'package:wger/providers/auth.dart' as _i4; +import 'package:wger/providers/base_provider.dart' as _i2; +import 'package:wger/providers/user.dart' as _i6; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeSharedPreferencesAsync_1 extends _i1.SmartFake implements _i3.SharedPreferencesAsync { + _FakeSharedPreferencesAsync_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeAuthProvider_2 extends _i1.SmartFake implements _i4.AuthProvider { + _FakeAuthProvider_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeClient_3 extends _i1.SmartFake implements _i5.Client { + _FakeClient_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeUri_4 extends _i1.SmartFake implements Uri { + _FakeUri_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeResponse_5 extends _i1.SmartFake implements _i5.Response { + _FakeResponse_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +/// A class which mocks [UserProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockUserProvider extends _i1.Mock implements _i6.UserProvider { + MockUserProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i7.ThemeMode get themeMode => + (super.noSuchMethod( + Invocation.getter(#themeMode), + returnValue: _i7.ThemeMode.system, + ) + as _i7.ThemeMode); + + @override + _i2.WgerBaseProvider get baseProvider => + (super.noSuchMethod( + Invocation.getter(#baseProvider), + returnValue: _FakeWgerBaseProvider_0( + this, + Invocation.getter(#baseProvider), + ), + ) + as _i2.WgerBaseProvider); + + @override + _i3.SharedPreferencesAsync get prefs => + (super.noSuchMethod( + Invocation.getter(#prefs), + returnValue: _FakeSharedPreferencesAsync_1( + this, + Invocation.getter(#prefs), + ), + ) + as _i3.SharedPreferencesAsync); + + @override + List<_i6.DashboardWidget> get dashboardOrder => + (super.noSuchMethod( + Invocation.getter(#dashboardOrder), + returnValue: <_i6.DashboardWidget>[], + ) + as List<_i6.DashboardWidget>); + + @override + set themeMode(_i7.ThemeMode? value) => super.noSuchMethod( + Invocation.setter(#themeMode, value), + returnValueForMissingStub: null, + ); + + @override + set prefs(_i3.SharedPreferencesAsync? value) => super.noSuchMethod( + Invocation.setter(#prefs, value), + returnValueForMissingStub: null, + ); + + @override + set profile(_i8.Profile? value) => super.noSuchMethod( + Invocation.setter(#profile, value), + returnValueForMissingStub: null, + ); + + @override + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); + + @override + void clear() => super.noSuchMethod( + Invocation.method(#clear, []), + returnValueForMissingStub: null, + ); + + @override + bool isDashboardWidgetVisible(_i6.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i9.Future setDashboardWidgetVisible( + _i6.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i9.Future.value(), + returnValueForMissingStub: _i9.Future.value(), + ) + as _i9.Future); + + @override + _i9.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i9.Future.value(), + returnValueForMissingStub: _i9.Future.value(), + ) + as _i9.Future); + + @override + void setThemeMode(_i7.ThemeMode? mode) => super.noSuchMethod( + Invocation.method(#setThemeMode, [mode]), + returnValueForMissingStub: null, + ); + + @override + _i9.Future fetchAndSetProfile() => + (super.noSuchMethod( + Invocation.method(#fetchAndSetProfile, []), + returnValue: _i9.Future.value(), + returnValueForMissingStub: _i9.Future.value(), + ) + as _i9.Future); + + @override + _i9.Future saveProfile() => + (super.noSuchMethod( + Invocation.method(#saveProfile, []), + returnValue: _i9.Future.value(), + returnValueForMissingStub: _i9.Future.value(), + ) + as _i9.Future); + + @override + _i9.Future verifyEmail() => + (super.noSuchMethod( + Invocation.method(#verifyEmail, []), + returnValue: _i9.Future.value(), + returnValueForMissingStub: _i9.Future.value(), + ) + as _i9.Future); + + @override + void addListener(_i10.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#addListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void removeListener(_i10.VoidCallback? listener) => super.noSuchMethod( + Invocation.method(#removeListener, [listener]), + returnValueForMissingStub: null, + ); + + @override + void dispose() => super.noSuchMethod( + Invocation.method(#dispose, []), + returnValueForMissingStub: null, + ); + + @override + void notifyListeners() => super.noSuchMethod( + Invocation.method(#notifyListeners, []), + returnValueForMissingStub: null, + ); +} + +/// A class which mocks [WgerBaseProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { + MockWgerBaseProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i4.AuthProvider get auth => + (super.noSuchMethod( + Invocation.getter(#auth), + returnValue: _FakeAuthProvider_2(this, Invocation.getter(#auth)), + ) + as _i4.AuthProvider); + + @override + _i5.Client get client => + (super.noSuchMethod( + Invocation.getter(#client), + returnValue: _FakeClient_3(this, Invocation.getter(#client)), + ) + as _i5.Client); + + @override + set auth(_i4.AuthProvider? value) => super.noSuchMethod( + Invocation.setter(#auth, value), + returnValueForMissingStub: null, + ); + + @override + set client(_i5.Client? value) => super.noSuchMethod( + Invocation.setter(#client, value), + returnValueForMissingStub: null, + ); + + @override + Map getDefaultHeaders({bool? includeAuth = false}) => + (super.noSuchMethod( + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), + returnValue: {}, + ) + as Map); + + @override + Uri makeUrl( + String? path, { + int? id, + String? objectMethod, + Map? query, + }) => + (super.noSuchMethod( + Invocation.method( + #makeUrl, + [path], + {#id: id, #objectMethod: objectMethod, #query: query}, + ), + returnValue: _FakeUri_4( + this, + Invocation.method( + #makeUrl, + [path], + {#id: id, #objectMethod: objectMethod, #query: query}, + ), + ), + ) + as Uri); + + @override + _i9.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + }) => + (super.noSuchMethod( + Invocation.method( + #fetch, + [uri], + {#maxRetries: maxRetries, #initialDelay: initialDelay}, + ), + returnValue: _i9.Future.value(), + ) + as _i9.Future); + + @override + _i9.Future> fetchPaginated(Uri? uri) => + (super.noSuchMethod( + Invocation.method(#fetchPaginated, [uri]), + returnValue: _i9.Future>.value([]), + ) + as _i9.Future>); + + @override + _i9.Future> post(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#post, [data, uri]), + returnValue: _i9.Future>.value( + {}, + ), + ) + as _i9.Future>); + + @override + _i9.Future> patch( + Map? data, + Uri? uri, + ) => + (super.noSuchMethod( + Invocation.method(#patch, [data, uri]), + returnValue: _i9.Future>.value( + {}, + ), + ) + as _i9.Future>); + + @override + _i9.Future<_i5.Response> deleteRequest(String? url, int? id) => + (super.noSuchMethod( + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i9.Future<_i5.Response>.value( + _FakeResponse_5( + this, + Invocation.method(#deleteRequest, [url, id]), + ), + ), + ) + as _i9.Future<_i5.Response>); +} diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index bb27464b1..f4869b4e6 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -49,7 +49,9 @@ void main() { setUp(() { when(mockUserProvider.themeMode).thenReturn(ThemeMode.system); - when(mockUserProvider.isDashboardWidgetVisible(any)).thenReturn(true); + when( + mockSharedPreferences.getString(UserProvider.PREFS_DASHBOARD_CONFIG), + ).thenAnswer((_) async => null); when(mockExerciseProvider.exercises).thenReturn(getTestExercises()); when(mockNutritionProvider.ingredients).thenReturn([ingredient1, ingredient2]); }); @@ -101,19 +103,15 @@ void main() { group('Theme settings', () { test('Default theme is system', () async { when(mockSharedPreferences.getBool(PREFS_USER_DARK_THEME)).thenAnswer((_) async => null); - when( - mockSharedPreferences.getString('dashboardWidgetVisibility'), - ).thenAnswer((_) async => null); - final userProvider = await UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); + final userProvider = UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); + await Future.delayed(const Duration(milliseconds: 50)); // wait for async prefs load expect(userProvider.themeMode, ThemeMode.system); }); test('Loads light theme', () async { when(mockSharedPreferences.getBool(PREFS_USER_DARK_THEME)).thenAnswer((_) async => false); - when( - mockSharedPreferences.getString('dashboardWidgetVisibility'), - ).thenAnswer((_) async => null); - final userProvider = await UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); + final userProvider = UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); + await Future.delayed(const Duration(milliseconds: 50)); // wait for async prefs load expect(userProvider.themeMode, ThemeMode.light); }); diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index b7dc303fe..6df8a7d9b 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -944,12 +944,12 @@ class MockUserProvider extends _i1.Mock implements _i21.UserProvider { as _i14.SharedPreferencesAsync); @override - Map<_i21.DashboardWidget, bool> get dashboardWidgetVisibility => + List<_i21.DashboardWidget> get dashboardOrder => (super.noSuchMethod( - Invocation.getter(#dashboardWidgetVisibility), - returnValue: <_i21.DashboardWidget, bool>{}, + Invocation.getter(#dashboardOrder), + returnValue: <_i21.DashboardWidget>[], ) - as Map<_i21.DashboardWidget, bool>); + as List<_i21.DashboardWidget>); @override set themeMode(_i22.ThemeMode? value) => super.noSuchMethod( @@ -963,12 +963,6 @@ class MockUserProvider extends _i1.Mock implements _i21.UserProvider { returnValueForMissingStub: null, ); - @override - set dashboardWidgetVisibility(Map<_i21.DashboardWidget, bool>? value) => super.noSuchMethod( - Invocation.setter(#dashboardWidgetVisibility, value), - returnValueForMissingStub: null, - ); - @override set profile(_i23.Profile? value) => super.noSuchMethod( Invocation.setter(#profile, value), @@ -1005,6 +999,15 @@ class MockUserProvider extends _i1.Mock implements _i21.UserProvider { ) as _i18.Future); + @override + _i18.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i18.Future.value(), + returnValueForMissingStub: _i18.Future.value(), + ) + as _i18.Future); + @override void setThemeMode(_i22.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 9b069055c..dad59660a 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -404,6 +404,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get dashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgets), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#dashboardWidgets), + ), + ) + as String); + @override String get labelDashboard => (super.noSuchMethod( diff --git a/test/exercises/contribute_exercise_test.mocks.dart b/test/exercises/contribute_exercise_test.mocks.dart index c3defcf4f..dd9f98e8b 100644 --- a/test/exercises/contribute_exercise_test.mocks.dart +++ b/test/exercises/contribute_exercise_test.mocks.dart @@ -390,12 +390,12 @@ class MockUserProvider extends _i1.Mock implements _i17.UserProvider { as _i4.SharedPreferencesAsync); @override - Map<_i17.DashboardWidget, bool> get dashboardWidgetVisibility => + List<_i17.DashboardWidget> get dashboardOrder => (super.noSuchMethod( - Invocation.getter(#dashboardWidgetVisibility), - returnValue: <_i17.DashboardWidget, bool>{}, + Invocation.getter(#dashboardOrder), + returnValue: <_i17.DashboardWidget>[], ) - as Map<_i17.DashboardWidget, bool>); + as List<_i17.DashboardWidget>); @override set themeMode(_i18.ThemeMode? value) => super.noSuchMethod( @@ -409,12 +409,6 @@ class MockUserProvider extends _i1.Mock implements _i17.UserProvider { returnValueForMissingStub: null, ); - @override - set dashboardWidgetVisibility(Map<_i17.DashboardWidget, bool>? value) => super.noSuchMethod( - Invocation.setter(#dashboardWidgetVisibility, value), - returnValueForMissingStub: null, - ); - @override set profile(_i19.Profile? value) => super.noSuchMethod( Invocation.setter(#profile, value), @@ -451,6 +445,15 @@ class MockUserProvider extends _i1.Mock implements _i17.UserProvider { ) as _i15.Future); + @override + _i15.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i15.Future.value(), + returnValueForMissingStub: _i15.Future.value(), + ) + as _i15.Future); + @override void setThemeMode(_i18.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), diff --git a/test/user/provider_test.dart b/test/user/provider_test.dart index 8297b3308..e12951f87 100644 --- a/test/user/provider_test.dart +++ b/test/user/provider_test.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * 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. * - * wger Workout Manager is distributed in the hope that it will be useful, + * 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. @@ -21,6 +21,7 @@ import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import 'package:shared_preferences/shared_preferences.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/providers/base_provider.dart'; @@ -51,7 +52,6 @@ void main() { ); setUp(() { - /// Replacement for SharedPreferences.setMockInitialValues() SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); mockWgerBaseProvider = MockWgerBaseProvider(); userProvider = UserProvider(mockWgerBaseProvider); @@ -103,4 +103,80 @@ void main() { verify(userProvider.baseProvider.fetch(tEmailVerifyUri)); }); }); + + group('dashboard config', () { + test('initial config should be default (all visible, default order)', () { + expect(userProvider.dashboardOrder.length, 5); + + expect( + userProvider.dashboardOrder, + orderedEquals([ + DashboardWidget.routines, + DashboardWidget.nutrition, + DashboardWidget.weight, + DashboardWidget.measurements, + DashboardWidget.calendar, + ]), + ); + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), true); + }); + + test('toggling visibility should update state', () async { + // act + await userProvider.setDashboardWidgetVisible(DashboardWidget.routines, false); + + // assert + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), false); + + // re-enable + await userProvider.setDashboardWidgetVisible(DashboardWidget.routines, true); + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), true); + }); + + test('reordering should update order', () async { + // arrange + final initialFirst = userProvider.dashboardOrder[0]; + final initialSecond = userProvider.dashboardOrder[1]; + + // act: move first to second position + // oldIndex: 0, newIndex: 2 (because insert is before index) + await userProvider.setDashboardOrder(0, 2); + + // assert + expect(userProvider.dashboardOrder[0], initialSecond); + expect(userProvider.dashboardOrder[1], initialFirst); + }); + + test('should load config from prefs', () async { + // arrange + final prefs = SharedPreferencesAsync(); + final customConfig = [ + {'widget': 'nutrition', 'visible': true}, + {'widget': 'routines', 'visible': false}, + ]; + await prefs.setString( + UserProvider.PREFS_DASHBOARD_CONFIG, + jsonEncode(customConfig), + ); + + // act + final newProvider = UserProvider(mockWgerBaseProvider, prefs: prefs); + await Future.delayed(const Duration(milliseconds: 50)); // wait for async prefs load + + // assert + // The loaded ones come first + expect(newProvider.dashboardOrder[0], DashboardWidget.nutrition); + expect(newProvider.dashboardOrder[1], DashboardWidget.routines); + + // Check visibility + expect(newProvider.isDashboardWidgetVisible(DashboardWidget.nutrition), true); + expect(newProvider.isDashboardWidgetVisible(DashboardWidget.routines), false); + + // Remaining items are added after + expect(newProvider.dashboardOrder.length, 5); + + // Items not in the prefs are visible by default + expect(newProvider.isDashboardWidgetVisible(DashboardWidget.weight), true); + }); + }); } diff --git a/test/weight/weight_screen_test.mocks.dart b/test/weight/weight_screen_test.mocks.dart index eac9ecd40..ae2d83ee3 100644 --- a/test/weight/weight_screen_test.mocks.dart +++ b/test/weight/weight_screen_test.mocks.dart @@ -232,12 +232,12 @@ class MockUserProvider extends _i1.Mock implements _i13.UserProvider { as _i4.SharedPreferencesAsync); @override - Map<_i13.DashboardWidget, bool> get dashboardWidgetVisibility => + List<_i13.DashboardWidget> get dashboardOrder => (super.noSuchMethod( - Invocation.getter(#dashboardWidgetVisibility), - returnValue: <_i13.DashboardWidget, bool>{}, + Invocation.getter(#dashboardOrder), + returnValue: <_i13.DashboardWidget>[], ) - as Map<_i13.DashboardWidget, bool>); + as List<_i13.DashboardWidget>); @override set themeMode(_i14.ThemeMode? value) => super.noSuchMethod( @@ -251,12 +251,6 @@ class MockUserProvider extends _i1.Mock implements _i13.UserProvider { returnValueForMissingStub: null, ); - @override - set dashboardWidgetVisibility(Map<_i13.DashboardWidget, bool>? value) => super.noSuchMethod( - Invocation.setter(#dashboardWidgetVisibility, value), - returnValueForMissingStub: null, - ); - @override set profile(_i15.Profile? value) => super.noSuchMethod( Invocation.setter(#profile, value), @@ -293,6 +287,15 @@ class MockUserProvider extends _i1.Mock implements _i13.UserProvider { ) as _i11.Future); + @override + _i11.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i11.Future.value(), + returnValueForMissingStub: _i11.Future.value(), + ) + as _i11.Future); + @override void setThemeMode(_i14.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), From f5a591a3b7e8f98c66a9a20e2245957bf11610fa Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 17 Jan 2026 14:01:17 +0100 Subject: [PATCH 42/48] Add trophies to configurable dashboard lists --- lib/main.dart | 2 +- lib/providers/user.dart | 9 +- lib/screens/dashboard.dart | 17 +- .../core/settings/dashboard_visibility.dart | 2 + .../settings_dashboard_visibility_test.dart | 24 +- ...tings_dashboard_visibility_test.mocks.dart | 267 ++++-------------- test/core/validators_test.mocks.dart | 22 ++ test/user/provider_test.dart | 27 +- 8 files changed, 119 insertions(+), 251 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 4f2f13947..956c4874b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -266,7 +266,7 @@ class MainApp extends StatelessWidget { LogOverviewPage.routeName: (ctx) => const LogOverviewPage(), ConfigurePlatesScreen.routeName: (ctx) => const ConfigurePlatesScreen(), ConfigureDashboardWidgetsScreen.routeName: (ctx) => - const ConfigureDashboardWidgetsScreen(), + const ConfigureDashboardWidgetsScreen(), TrophyScreen.routeName: (ctx) => const TrophyScreen(), }, localizationsDelegates: AppLocalizations.localizationsDelegates, diff --git a/lib/providers/user.dart b/lib/providers/user.dart index e2c4c0a86..5e4004e7e 100644 --- a/lib/providers/user.dart +++ b/lib/providers/user.dart @@ -28,6 +28,7 @@ import 'package:wger/models/user/profile.dart'; import 'package:wger/providers/base_provider.dart'; enum DashboardWidget { + trophies('trophies'), routines('routines'), nutrition('nutrition'), weight('weight'), @@ -124,7 +125,13 @@ class UserProvider with ChangeNotifier { // Add any missing widgets (e.g. newly added features) for (final widget in DashboardWidget.values) { if (!loaded.any((item) => item.widget == widget)) { - loaded.add(DashboardItem(widget)); + // Try to insert at the original position defined in the enum + // taking into account the current size of the list + var index = DashboardWidget.values.indexOf(widget); + if (index > loaded.length) { + index = loaded.length; + } + loaded.insert(index, DashboardItem(widget)); } } diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index 26a9aec26..513197227 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -18,6 +18,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import 'package:wger/helpers/material.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/user.dart'; import 'package:wger/widgets/core/app_bar.dart'; @@ -25,10 +26,9 @@ import 'package:wger/widgets/dashboard/calendar.dart'; import 'package:wger/widgets/dashboard/widgets/measurements.dart'; import 'package:wger/widgets/dashboard/widgets/nutrition.dart'; import 'package:wger/widgets/dashboard/widgets/routines.dart'; +import 'package:wger/widgets/dashboard/widgets/trophies.dart'; import 'package:wger/widgets/dashboard/widgets/weight.dart'; -import '../widgets/dashboard/widgets/trophies.dart'; - class DashboardScreen extends StatelessWidget { const DashboardScreen({super.key}); @@ -46,6 +46,8 @@ class DashboardScreen extends StatelessWidget { return const DashboardCalendarWidget(); case DashboardWidget.nutrition: return const DashboardNutritionWidget(); + case DashboardWidget.trophies: + return const DashboardTrophiesWidget(); } /* child: Column( @@ -60,7 +62,7 @@ class DashboardScreen extends StatelessWidget { Widget build(BuildContext context) { final width = MediaQuery.sizeOf(context).width; final isMobile = width < MATERIAL_XS_BREAKPOINT; - inal user = Provider.of(context); + final user = Provider.of(context); late final int crossAxisCount; if (width < MATERIAL_XS_BREAKPOINT) { @@ -73,22 +75,21 @@ class DashboardScreen extends StatelessWidget { crossAxisCount = 4; } - - return Scaffold( appBar: MainAppBar(AppLocalizations.of(context).labelDashboard), body: Center( child: ConstrainedBox( - constraints: BoxConstraints(maxWidth: MATERIAL_LG_BREAKPOINT.toDouble()), + constraints: const BoxConstraints(maxWidth: MATERIAL_LG_BREAKPOINT), child: isMobile ? ListView.builder( padding: const EdgeInsets.all(10), - itemBuilder: (context, index) => _getDashboardWidget(index), + itemBuilder: (context, index) => _getDashboardWidget(user.dashboardOrder[index]), itemCount: user.dashboardOrder.length, ) : GridView.builder( padding: const EdgeInsets.all(10), - itemBuilder: (context, index) => SingleChildScrollView(child: _getDashboardWidget(index)), + itemBuilder: (context, index) => + SingleChildScrollView(child: _getDashboardWidget(user.dashboardOrder[index])), itemCount: user.dashboardOrder.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: crossAxisCount, diff --git a/lib/widgets/core/settings/dashboard_visibility.dart b/lib/widgets/core/settings/dashboard_visibility.dart index b7d110b89..a86b8d5f2 100644 --- a/lib/widgets/core/settings/dashboard_visibility.dart +++ b/lib/widgets/core/settings/dashboard_visibility.dart @@ -40,6 +40,8 @@ class SettingsDashboardVisibility extends StatelessWidget { return i18n.calendar; case DashboardWidget.nutrition: return i18n.nutritionalPlans; + case DashboardWidget.trophies: + return i18n.trophies; } } diff --git a/test/core/settings_dashboard_visibility_test.dart b/test/core/settings_dashboard_visibility_test.dart index a171bbd42..1aedab97e 100644 --- a/test/core/settings_dashboard_visibility_test.dart +++ b/test/core/settings_dashboard_visibility_test.dart @@ -29,10 +29,7 @@ import 'package:wger/widgets/core/settings/dashboard_visibility.dart'; import 'settings_dashboard_visibility_test.mocks.dart'; -@GenerateMocks([ - UserProvider, - WgerBaseProvider, -]) +@GenerateMocks([WgerBaseProvider]) void main() { late UserProvider userProvider; late MockWgerBaseProvider mockBaseProvider; @@ -98,24 +95,23 @@ void main() { await tester.pumpWidget(createWidget()); await tester.pumpAndSettle(); - // Initial order: routines, nutrition, weight... - expect(userProvider.dashboardOrder[0], DashboardWidget.routines); - expect(userProvider.dashboardOrder[1], DashboardWidget.nutrition); + // Initial order: trophies, routines, nutrition, weight... + expect(userProvider.dashboardOrder[0], DashboardWidget.trophies); + expect(userProvider.dashboardOrder[1], DashboardWidget.routines); - // Find drag handle for Routines (index 0) + // Find drag handle for Trophies (index 0) final handleFinder = find.byIcon(Icons.drag_handle); final firstHandle = handleFinder.at(0); - // final secondHandle = handleFinder.at(1); // Drag first item down await tester.drag(firstHandle, const Offset(0, 100)); // Drag down enough to swap await tester.pumpAndSettle(); // Verify order changed - // If swapped with second item (nutrition) and maybe third (weight) depending on height - // Based on running test: index 0 is nutrition, index 1 is weight. - expect(userProvider.dashboardOrder[0], DashboardWidget.nutrition); - expect(userProvider.dashboardOrder[1], DashboardWidget.weight); - expect(userProvider.dashboardOrder[2], DashboardWidget.routines); + // 100px drag seems to skip 2 items (trophies moves to index 2) + // [routines, nutrition, trophies, ...] + expect(userProvider.dashboardOrder[0], DashboardWidget.routines); + expect(userProvider.dashboardOrder[1], DashboardWidget.nutrition); + expect(userProvider.dashboardOrder[2], DashboardWidget.trophies); }); } diff --git a/test/core/settings_dashboard_visibility_test.mocks.dart b/test/core/settings_dashboard_visibility_test.mocks.dart index 01803e1b2..bc9ac783c 100644 --- a/test/core/settings_dashboard_visibility_test.mocks.dart +++ b/test/core/settings_dashboard_visibility_test.mocks.dart @@ -3,17 +3,12 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i9; -import 'dart:ui' as _i10; +import 'dart:async' as _i5; -import 'package:flutter/material.dart' as _i7; -import 'package:http/http.dart' as _i5; +import 'package:http/http.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; -import 'package:shared_preferences/shared_preferences.dart' as _i3; -import 'package:wger/models/user/profile.dart' as _i8; -import 'package:wger/providers/auth.dart' as _i4; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/user.dart' as _i6; +import 'package:wger/providers/auth.dart' as _i2; +import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -30,234 +25,67 @@ import 'package:wger/providers/user.dart' as _i6; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); +class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeSharedPreferencesAsync_1 extends _i1.SmartFake implements _i3.SharedPreferencesAsync { - _FakeSharedPreferencesAsync_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); +class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { + _FakeClient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAuthProvider_2 extends _i1.SmartFake implements _i4.AuthProvider { - _FakeAuthProvider_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeUri_2 extends _i1.SmartFake implements Uri { + _FakeUri_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeClient_3 extends _i1.SmartFake implements _i5.Client { - _FakeClient_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeUri_4 extends _i1.SmartFake implements Uri { - _FakeUri_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeResponse_5 extends _i1.SmartFake implements _i5.Response { - _FakeResponse_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -/// A class which mocks [UserProvider]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockUserProvider extends _i1.Mock implements _i6.UserProvider { - MockUserProvider() { - _i1.throwOnMissingStub(this); - } - - @override - _i7.ThemeMode get themeMode => - (super.noSuchMethod( - Invocation.getter(#themeMode), - returnValue: _i7.ThemeMode.system, - ) - as _i7.ThemeMode); - - @override - _i2.WgerBaseProvider get baseProvider => - (super.noSuchMethod( - Invocation.getter(#baseProvider), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#baseProvider), - ), - ) - as _i2.WgerBaseProvider); - - @override - _i3.SharedPreferencesAsync get prefs => - (super.noSuchMethod( - Invocation.getter(#prefs), - returnValue: _FakeSharedPreferencesAsync_1( - this, - Invocation.getter(#prefs), - ), - ) - as _i3.SharedPreferencesAsync); - - @override - List<_i6.DashboardWidget> get dashboardOrder => - (super.noSuchMethod( - Invocation.getter(#dashboardOrder), - returnValue: <_i6.DashboardWidget>[], - ) - as List<_i6.DashboardWidget>); - - @override - set themeMode(_i7.ThemeMode? value) => super.noSuchMethod( - Invocation.setter(#themeMode, value), - returnValueForMissingStub: null, - ); - - @override - set prefs(_i3.SharedPreferencesAsync? value) => super.noSuchMethod( - Invocation.setter(#prefs, value), - returnValueForMissingStub: null, - ); - - @override - set profile(_i8.Profile? value) => super.noSuchMethod( - Invocation.setter(#profile, value), - returnValueForMissingStub: null, - ); - - @override - bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); - - @override - void clear() => super.noSuchMethod( - Invocation.method(#clear, []), - returnValueForMissingStub: null, - ); - - @override - bool isDashboardWidgetVisible(_i6.DashboardWidget? key) => - (super.noSuchMethod( - Invocation.method(#isDashboardWidgetVisible, [key]), - returnValue: false, - ) - as bool); - - @override - _i9.Future setDashboardWidgetVisible( - _i6.DashboardWidget? key, - bool? visible, - ) => - (super.noSuchMethod( - Invocation.method(#setDashboardWidgetVisible, [key, visible]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future setDashboardOrder(int? oldIndex, int? newIndex) => - (super.noSuchMethod( - Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - void setThemeMode(_i7.ThemeMode? mode) => super.noSuchMethod( - Invocation.method(#setThemeMode, [mode]), - returnValueForMissingStub: null, - ); - - @override - _i9.Future fetchAndSetProfile() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetProfile, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future saveProfile() => - (super.noSuchMethod( - Invocation.method(#saveProfile, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future verifyEmail() => - (super.noSuchMethod( - Invocation.method(#verifyEmail, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - void addListener(_i10.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#addListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void removeListener(_i10.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#removeListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); - - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); +class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { + _FakeResponse_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. /// /// See the documentation for Mockito's code generation for more information. -class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { +class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { MockWgerBaseProvider() { _i1.throwOnMissingStub(this); } @override - _i4.AuthProvider get auth => + _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_2(this, Invocation.getter(#auth)), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) - as _i4.AuthProvider); + as _i2.AuthProvider); @override - _i5.Client get client => + _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_3(this, Invocation.getter(#client)), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) - as _i5.Client); + as _i3.Client); @override - set auth(_i4.AuthProvider? value) => super.noSuchMethod( + set auth(_i2.AuthProvider? value) => super.noSuchMethod( Invocation.setter(#auth, value), returnValueForMissingStub: null, ); @override - set client(_i5.Client? value) => super.noSuchMethod( + set client(_i3.Client? value) => super.noSuchMethod( Invocation.setter(#client, value), returnValueForMissingStub: null, ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -276,7 +104,7 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { [path], {#id: id, #objectMethod: objectMethod, #query: query}, ), - returnValue: _FakeUri_4( + returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, @@ -288,62 +116,67 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i9.Future fetch( + _i5.Future fetch( Uri? uri, { int? maxRetries = 3, Duration? initialDelay = const Duration(milliseconds: 250), + String? language, }) => (super.noSuchMethod( Invocation.method( #fetch, [uri], - {#maxRetries: maxRetries, #initialDelay: initialDelay}, + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, ), - returnValue: _i9.Future.value(), + returnValue: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); @override - _i9.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), - returnValue: _i9.Future>.value([]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), + returnValue: _i5.Future>.value([]), ) - as _i9.Future>); + as _i5.Future>); @override - _i9.Future> post(Map? data, Uri? uri) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( Invocation.method(#post, [data, uri]), - returnValue: _i9.Future>.value( + returnValue: _i5.Future>.value( {}, ), ) - as _i9.Future>); + as _i5.Future>); @override - _i9.Future> patch( + _i5.Future> patch( Map? data, Uri? uri, ) => (super.noSuchMethod( Invocation.method(#patch, [data, uri]), - returnValue: _i9.Future>.value( + returnValue: _i5.Future>.value( {}, ), ) - as _i9.Future>); + as _i5.Future>); @override - _i9.Future<_i5.Response> deleteRequest(String? url, int? id) => + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( Invocation.method(#deleteRequest, [url, id]), - returnValue: _i9.Future<_i5.Response>.value( - _FakeResponse_5( + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( this, Invocation.method(#deleteRequest, [url, id]), ), ), ) - as _i9.Future<_i5.Response>); + as _i5.Future<_i3.Response>); } diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index f79e03545..b89be4522 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -2207,6 +2207,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get noTrophies => + (super.noSuchMethod( + Invocation.getter(#noTrophies), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#noTrophies), + ), + ) + as String); + @override String get noWeightEntries => (super.noSuchMethod( @@ -3843,6 +3854,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String topSet(String? value) => + (super.noSuchMethod( + Invocation.method(#topSet, [value]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#topSet, [value]), + ), + ) + as String); + @override String durationHoursMinutes(int? hours, int? minutes) => (super.noSuchMethod( diff --git a/test/user/provider_test.dart b/test/user/provider_test.dart index e12951f87..c5a9206e3 100644 --- a/test/user/provider_test.dart +++ b/test/user/provider_test.dart @@ -106,11 +106,12 @@ void main() { group('dashboard config', () { test('initial config should be default (all visible, default order)', () { - expect(userProvider.dashboardOrder.length, 5); + expect(userProvider.dashboardOrder.length, 6); expect( userProvider.dashboardOrder, orderedEquals([ + DashboardWidget.trophies, DashboardWidget.routines, DashboardWidget.nutrition, DashboardWidget.weight, @@ -161,22 +162,28 @@ void main() { // act final newProvider = UserProvider(mockWgerBaseProvider, prefs: prefs); - await Future.delayed(const Duration(milliseconds: 50)); // wait for async prefs load + await Future.delayed(const Duration(milliseconds: 100)); // wait for async prefs load // assert - // The loaded ones come first - expect(newProvider.dashboardOrder[0], DashboardWidget.nutrition); - expect(newProvider.dashboardOrder[1], DashboardWidget.routines); + // Loaded: [nutrition, routines] + // Missing: trophies (0), weight (3), measurements (4), calendar (5) + // 1. trophies (index 0) inserted at 0 -> [trophies, nutrition, routines] + // 2. weight (index 3) inserted at 3 -> [trophies, nutrition, routines, weight] + + expect(newProvider.dashboardOrder[0], DashboardWidget.trophies); + expect(newProvider.dashboardOrder[1], DashboardWidget.nutrition); + expect(newProvider.dashboardOrder[2], DashboardWidget.routines); + expect(newProvider.dashboardOrder[3], DashboardWidget.weight); // Check visibility expect(newProvider.isDashboardWidgetVisible(DashboardWidget.nutrition), true); expect(newProvider.isDashboardWidgetVisible(DashboardWidget.routines), false); - // Remaining items are added after - expect(newProvider.dashboardOrder.length, 5); - - // Items not in the prefs are visible by default - expect(newProvider.isDashboardWidgetVisible(DashboardWidget.weight), true); + // Missing items should be visible by default + expect( + newProvider.isDashboardWidgetVisible(DashboardWidget.weight), + true, + ); }); }); } From 8ae6512456fa6b79b29aaab08837c85c5381719b Mon Sep 17 00:00:00 2001 From: Github-Actions Date: Sat, 17 Jan 2026 15:30:06 +0000 Subject: [PATCH 43/48] Bump version to 1.9.6 --- flatpak/de.wger.flutter.metainfo.xml | 6 ++++++ pubspec.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/flatpak/de.wger.flutter.metainfo.xml b/flatpak/de.wger.flutter.metainfo.xml index 9b0daf14f..badbff45d 100755 --- a/flatpak/de.wger.flutter.metainfo.xml +++ b/flatpak/de.wger.flutter.metainfo.xml @@ -84,6 +84,12 @@ + + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/1.9.6 +

Bug fixes and improvements.

diff --git a/pubspec.yaml b/pubspec.yaml index 9738a3133..613da16ca 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -21,7 +21,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # - the version number is taken from the git tag vX.Y.Z # - the build number is computed by reading the last one from the play store # and increasing by one -version: 1.9.5+150 +version: 1.9.6+160 environment: sdk: '>=3.8.0 <4.0.0' From 1e2d7c9ac2dbdbbe81dc8485276274f0f41b969c Mon Sep 17 00:00:00 2001 From: MarcMeRu11 Date: Wed, 14 Jan 2026 20:25:43 +0100 Subject: [PATCH 44/48] Translated using Weblate (Spanish) Currently translated at 100.0% (369 of 369 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/es/ --- lib/l10n/app_es.arb | 100 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 97 insertions(+), 3 deletions(-) diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 395cd1e2f..ed5075576 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -462,7 +462,7 @@ }, "logIngredient": "Registrar en el diario nutricional", "@logIngredient": {}, - "plateCalculatorNotDivisible": "No se puede obtener el peso con las placas disponbles", + "plateCalculatorNotDivisible": "No se puede obtener el peso con las placas disponibles", "@plateCalculatorNotDivisible": { "description": "Error message when the current weight is not reachable with plates (e.g. 33.1 kg)" }, @@ -1005,7 +1005,7 @@ "@goalTypeAdvanced": { "description": "added for localization of Class GoalType's filed advanced" }, - "indicatorRaw": "raw", + "indicatorRaw": "Bruto", "@indicatorRaw": { "description": "added for localization of Class Indicator's field text" }, @@ -1114,5 +1114,99 @@ "type": "String" } } - } + }, + "dayTypeCustom": "Personalizado", + "@dayTypeCustom": {}, + "dayTypeAmrap": "Tantas rondas como sea posible", + "@dayTypeAmrap": {}, + "dayTypeHiit": "Entrenamiento en intervalos de alta intensidad", + "@dayTypeHiit": {}, + "dayTypeEdt": "Entrenamiento de intensidad creciente", + "@dayTypeEdt": {}, + "dayTypeRft": "Rondas por tiempo", + "@dayTypeRft": {}, + "dayTypeAfap": "Tan rápido como sea posible", + "@dayTypeAfap": {}, + "slotEntryTypeNormal": "Normal", + "@slotEntryTypeNormal": {}, + "slotEntryTypeDropset": "Serie descendiente", + "@slotEntryTypeDropset": {}, + "slotEntryTypePartial": "Parcial", + "@slotEntryTypePartial": {}, + "slotEntryTypeForced": "Forzadas", + "@slotEntryTypeForced": {}, + "slotEntryTypeTut": "Tiempo bajo tensión", + "@slotEntryTypeTut": {}, + "slotEntryTypeIso": "Aguante isométrico", + "@slotEntryTypeIso": {}, + "slotEntryTypeJump": "Salto", + "@slotEntryTypeJump": {}, + "impressionGood": "Bien", + "@impressionGood": {}, + "impressionNeutral": "Neutral", + "@impressionNeutral": {}, + "impressionBad": "Mal", + "@impressionBad": {}, + "gymModeShowExercises": "Ver páginas de resumen de ejercicios", + "@gymModeShowExercises": {}, + "gymModeShowTimer": "Mostrar temporizador entre series", + "@gymModeShowTimer": {}, + "gymModeTimerType": "Tipo de temporizador", + "@gymModeTimerType": {}, + "gymModeTimerTypeHelText": "Si una serie tiene tiempo de pausa, siempre se usa una cuenta regresiva.", + "@gymModeTimerTypeHelText": {}, + "countdown": "Cuenta regresiva", + "@countdown": {}, + "stopwatch": "Cronómetro", + "@stopwatch": {}, + "gymModeDefaultCountdownTime": "Tiempo predeterminado de cuenta regresiva, en segundos", + "@gymModeDefaultCountdownTime": {}, + "gymModeNotifyOnCountdownFinish": "Notificar al terminar cuenta regresiva", + "@gymModeNotifyOnCountdownFinish": {}, + "duration": "Duración", + "@duration": {}, + "volume": "Volumen", + "@volume": { + "description": "The volume of a workout or set, i.e. weight x reps" + }, + "workoutCompleted": "Entrenamiento completado", + "@workoutCompleted": {}, + "formMinMaxValues": "Por favor introduce un número entre {min} y {max}", + "@formMinMaxValues": { + "description": "Error message when the user needs to enter a value between min and max", + "type": "text", + "placeholders": { + "min": { + "type": "int" + }, + "max": { + "type": "int" + } + } + }, + "superset": "Superserie", + "@superset": {}, + "endWorkout": "Finalizar entrenamiento", + "@endWorkout": { + "description": "Use the imperative, label on button to finish the current workout in gym mode" + }, + "durationHoursMinutes": "{hours}h {minutes}m", + "@durationHoursMinutes": { + "description": "A duration, in hours and minutes", + "type": "text", + "placeholders": { + "hours": { + "type": "int" + }, + "minutes": { + "type": "int" + } + } + }, + "dayTypeEnom": "Cada minuto, en el minuto", + "@dayTypeEnom": {}, + "dayTypeTabata": "Entrenamiento Tabata", + "@dayTypeTabata": {}, + "slotEntryTypeMyo": "Entrenamiento Myo", + "@slotEntryTypeMyo": {} } From 69d90196bdaba7f18a9744916f9e2716c60c3f12 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 18 Jan 2026 12:34:32 +0100 Subject: [PATCH 45/48] Bump flutter version --- .github/actions/flutter-common/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/flutter-common/action.yml b/.github/actions/flutter-common/action.yml index ee3b35f90..20c5dc849 100644 --- a/.github/actions/flutter-common/action.yml +++ b/.github/actions/flutter-common/action.yml @@ -9,7 +9,7 @@ runs: uses: subosito/flutter-action@v2 with: channel: stable - flutter-version: 3.38.6 + flutter-version: 3.38.7 cache: true - name: Install Flutter dependencies From 7c09745bd4ca85cd84127188a026bce503c6b65b Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 18 Jan 2026 13:03:09 +0100 Subject: [PATCH 46/48] Update authors list --- AUTHORS.md | 169 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 148 insertions(+), 21 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index e478e970a..12f2f5229 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -2,26 +2,58 @@ Thank you all for contributing to the project, you are true heroes! 🫶 -*Generated on 2025-11-10* +*Generated on 2026-01-18* --- ## Contributors -- thisisyoussef - [https://github.com/thisisyoussef](https://github.com/thisisyoussef) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) -- Yashas H Majmudar - [https://github.com/yashas-hm](https://github.com/yashas-hm) - Github-actions - [https://github.com/invalid-email-address](https://github.com/invalid-email-address) +- unknown - [https://github.com/elias170105](https://github.com/elias170105) +- Diya Hituvalli - [https://github.com/dhituval](https://github.com/dhituval) +- dhituval - [https://github.com/dhituval](https://github.com/dhituval) +- john +- ImgBotApp - [https://github.com/ImgBotApp](https://github.com/ImgBotApp) +- DhruvSingh19 - [https://github.com/DhruvSingh19](https://github.com/DhruvSingh19) +- Anupthor007 - [https://github.com/Anupthor007](https://github.com/Anupthor007) +- lenka369 +- lenka369 - [https://github.com/lenka369](https://github.com/lenka369) +- Branislav Nohaj +- Branislav Nohaj - [https://github.com/Oknarb258](https://github.com/Oknarb258) +- Kyle Hekkers - [https://github.com/List0734](https://github.com/List0734) +- GhostInTheNN - [https://github.com/GhostInTheNN](https://github.com/GhostInTheNN) +- Arthur De Neyer - [https://github.com/GaecKo](https://github.com/GaecKo) +- Arthur De Neyer +- Max Pylypenko - [https://github.com/3mpee3mpee](https://github.com/3mpee3mpee) +- rishad.n - [https://github.com/rishadn-gif](https://github.com/rishadn-gif) +- Nelumbo Nucifera - [https://github.com/nelumboy](https://github.com/nelumboy) +- Patrik - [https://github.com/P4TR1K1305](https://github.com/P4TR1K1305) +- Iman Karimian - [https://github.com/IK7D3](https://github.com/IK7D3) +- Afzal Momin - [https://github.com/afzal09](https://github.com/afzal09) +- Ninguém Mesmo +- Dieter Plaetinck - [https://github.com/Dieterbe](https://github.com/Dieterbe) +- RahulShaw321 +- shravya - [https://github.com/shraavv](https://github.com/shraavv) +- kobo +- burny0202 - [https://github.com/Shininess8816](https://github.com/Shininess8816) +- Rohitdhall987 - [https://github.com/Rohitdhall987](https://github.com/Rohitdhall987) +- Yashas H Majmudar - [https://github.com/yashas-hm](https://github.com/yashas-hm) +- Yashas H Majmudar - [https://github.com/yashas-hm](https://github.com/yashas-hm) +- thisisyoussef - [https://github.com/thisisyoussef](https://github.com/thisisyoussef) +- Peter Thaler - Christijan - [https://github.com/ChrispyM](https://github.com/ChrispyM) - Jackpkn - [https://github.com/Jackpkn](https://github.com/Jackpkn) - sangharshdeveloper - [https://github.com/Sangharshdeveloper](https://github.com/Sangharshdeveloper) -- ImgBotApp - [https://github.com/ImgBotApp](https://github.com/ImgBotApp) -- தமிழ்நேரம் - [https://github.com/TamilNeram](https://github.com/TamilNeram) +- Ayush Sourav Jagaty - [https://github.com/AyushJagaty](https://github.com/AyushJagaty) +- eyjhb - [https://github.com/eyJhb](https://github.com/eyJhb) +- AyushJagaty - [https://github.com/AyushJagaty](https://github.com/AyushJagaty) +- Ayush Sourav Jagaty +- தமிழ்நேரம் - Xianglin Zeng - [https://github.com/FutureYL3](https://github.com/FutureYL3) - Arya Pratap Singh - [https://github.com/ARYPROGRAMMER](https://github.com/ARYPROGRAMMER) - ARYPROGRAMMER - [https://github.com/ARYPROGRAMMER](https://github.com/ARYPROGRAMMER) -- Dieter Plaetinck - [https://github.com/Dieterbe](https://github.com/Dieterbe) -- szalas - [https://github.com/szalas](https://github.com/szalas) +- szalas - dan - [https://github.com/sizzlesloth](https://github.com/sizzlesloth) - DVPeer - [https://github.com/Denpeer](https://github.com/Denpeer) - Marco Rimoldi - [https://github.com/marcor](https://github.com/marcor) @@ -33,7 +65,7 @@ Thank you all for contributing to the project, you are true heroes! 🫶 - Milksheyke - [https://github.com/sheyaln](https://github.com/sheyaln) - Abhishek Saini - [https://github.com/Abhisheksainii](https://github.com/Abhisheksainii) - dimii27 - [https://github.com/dimii27](https://github.com/dimii27) -- Antonis-geo - [https://github.com/Antonis-geo](https://github.com/Antonis-geo) +- Antonis-geo - artchiee - [https://github.com/artchiee](https://github.com/artchiee) - artchiee - [https://github.com/artchiee](https://github.com/artchiee) - Jigar Prajapati - [https://github.com/Jiggy9](https://github.com/Jiggy9) @@ -104,6 +136,7 @@ Thank you all for contributing to the project, you are true heroes! 🫶 - Jannik Norden - Allan Nordhøy - [https://github.com/comradekingu](https://github.com/comradekingu) - Stefano Rossi - [https://github.com/stefanorossiti](https://github.com/stefanorossiti) +- Dylan Aird - [https://github.com/Dolaned](https://github.com/Dolaned) ## Translators @@ -113,23 +146,28 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Arabic +- Jaafer Mahfoud - [https://github.com/mysterI0s](https://github.com/mysterI0s) +- Yrooma - [https://github.com/Yrooma](https://github.com/Yrooma) - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Hanaa - [https://github.com/hn-n](https://github.com/hn-n) - Ahmed zein - [https://github.com/Ahmed-Zein](https://github.com/Ahmed-Zein) ### Catalan -- Zixu Sun - [https://github.com/ziixu](https://github.com/ziixu) - Anonymous - [https://github.com/weblate](https://github.com/weblate) +- Zixu Sun - [https://github.com/ziixu](https://github.com/ziixu) - guillem - [https://github.com/gbuendia](https://github.com/gbuendia) ### Chinese (Simplified Han script) +- KW Lam - [https://github.com/loksonlkw](https://github.com/loksonlkw) +- Wen QI - [https://github.com/kevinwenyu](https://github.com/kevinwenyu) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Herb Huang ### Chinese (Simplified) -- 纪颖志 - [https://github.com/jiyingzhi](https://github.com/jiyingzhi) +- 纪颖志 - [https://github.com/yingzhi0808](https://github.com/yingzhi0808) - Yi-Han Hsiung - [https://github.com/AaronHsiung](https://github.com/AaronHsiung) - Tsz Hong CHAN - [https://github.com/tomyan112](https://github.com/tomyan112) - Eddie Tang - [https://github.com/EDED2314](https://github.com/EDED2314) @@ -140,6 +178,9 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Chinese (Traditional Han script) +- Chia Wen Tsai - [https://github.com/cjwind](https://github.com/cjwind) +- Paulkit - [https://github.com/Paulkit](https://github.com/Paulkit) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Peter Dave Hello - [https://github.com/PeterDaveHello](https://github.com/PeterDaveHello) ### Chinese (Traditional) @@ -152,11 +193,14 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Croatian - Milo Ivir - [https://github.com/milotype](https://github.com/milotype) +- Neno Horvat - [https://github.com/ness993](https://github.com/ness993) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) - SMilohanic - [https://github.com/sandimilohanic](https://github.com/sandimilohanic) ### Czech +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Fjuro - [https://github.com/Fjuro](https://github.com/Fjuro) - Fjuro - CaptainDolphy - [https://github.com/CaptainDolphy](https://github.com/CaptainDolphy) @@ -164,6 +208,7 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Dutch +- Floris C - Joey Haalboom - [https://github.com/JoeyHaalboom](https://github.com/JoeyHaalboom) ### English @@ -172,11 +217,22 @@ Thank you all for contributing to the project, you are true heroes! 🫶 - Allan Nordhøy - [https://github.com/comradekingu](https://github.com/comradekingu) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) +### Filipino + +- john + ### French +- Benjamin Voisin - [https://github.com/benjamin-voisin](https://github.com/benjamin-voisin) +- Justin Pinheiro - [https://github.com/justin-pinheiro](https://github.com/justin-pinheiro) +- Paul Bonneau - [https://github.com/paulbonneau](https://github.com/paulbonneau) +- Martin Derleth +- Vocatis - [https://github.com/Vocatis](https://github.com/Vocatis) +- Kilian +- Enzo Besnainou +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - William - [https://github.com/WilliamR312](https://github.com/WilliamR312) - florent4014 - [https://github.com/florent4014](https://github.com/florent4014) -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Xav Basco - David Olewski - [https://github.com/Arigowin](https://github.com/Arigowin) - yoyomax80400 - [https://github.com/yoyomax80400](https://github.com/yoyomax80400) @@ -190,9 +246,15 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### German -- kvnrmnn - [https://github.com/rmnn92](https://github.com/rmnn92) -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) +- Elias Lang - [https://github.com/elias170105](https://github.com/elias170105) +- Panoloo - [https://github.com/Panoloo](https://github.com/Panoloo) +- johannes heintz - [https://github.com/Randalix](https://github.com/Randalix) +- Tobias Maschek - [https://github.com/jemx](https://github.com/jemx) +- Richard Mrosk - [https://github.com/EtheriousNight](https://github.com/EtheriousNight) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) +- BlinderUhu - [https://github.com/BlinderUhu](https://github.com/BlinderUhu) +- kvnrmnn - [https://github.com/rmnn92](https://github.com/rmnn92) - Victor Jouhoff - [https://github.com/jouhoffv](https://github.com/jouhoffv) - m4skedbyte - Axel Steinbrecher @@ -207,12 +269,13 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Greek - Dimitrys Meliates -- Antonis-geo - [https://github.com/Antonis-geo](https://github.com/Antonis-geo) +- Antonis-geo ### Hebrew -- Anonymous - [https://github.com/weblate](https://github.com/weblate) +- Omer I.S - [https://github.com/omeritzics](https://github.com/omeritzics) - n,rdo +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Tomer Ben Rachel - [https://github.com/TomerPacific](https://github.com/TomerPacific) ### Hindi @@ -221,8 +284,14 @@ Thank you all for contributing to the project, you are true heroes! 🫶 - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Debayan Sutradhar - [https://github.com/rnayabed](https://github.com/rnayabed) +### Hungarian + +- Greg + ### Indonesian +- Nurfitra Pujo Santiko - [https://github.com/NurfitraPujo](https://github.com/NurfitraPujo) +- Arga Pandika - [https://github.com/argakast](https://github.com/argakast) - aryakdaniswara - [https://github.com/aryakdaniswara](https://github.com/aryakdaniswara) - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Debi Maulana Ahsan Halla @@ -230,9 +299,15 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Italian +- Alessio - [https://github.com/menitz](https://github.com/menitz) +- Federico - [https://github.com/FedericoVaga](https://github.com/FedericoVaga) +- Luca Galli - [https://github.com/Lvcaa](https://github.com/Lvcaa) +- clafalco - [https://github.com/clafalco](https://github.com/clafalco) +- adriano onorati - [https://github.com/banphi](https://github.com/banphi) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) +- Matteo Morari - [https://github.com/matteomorari](https://github.com/matteomorari) - Antenore Gatta - [https://github.com/antenore](https://github.com/antenore) - Gab Gat -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Federico Pierantoni - [https://github.com/F3FFO](https://github.com/F3FFO) - oarion - [https://github.com/oarion](https://github.com/oarion) - Alessandro Faucci - [https://github.com/Dhy19971](https://github.com/Dhy19971) @@ -247,22 +322,36 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Japanese +- Ryohei Morimoto - [https://github.com/Ryohei-Caulked](https://github.com/Ryohei-Caulked) - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Tsz Hong CHAN - [https://github.com/tomyan112](https://github.com/tomyan112) - sasukeiscool - [https://github.com/sasukeiscool](https://github.com/sasukeiscool) - yiter +### Korean + +- jyk0619 - [https://github.com/jyk0619](https://github.com/jyk0619) +- kobo + ### Norwegian Bokmål +- Morten R. Bjørklund - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) - Allan Nordhøy - [https://github.com/comradekingu](https://github.com/comradekingu) +### Persian + +- Mahmuoud Salehi + ### Polish +- saalaataa - [https://github.com/saalaataa](https://github.com/saalaataa) +- Kamil Maciąg +- Y - [https://github.com/dioxyg](https://github.com/dioxyg) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Karol Solecki - [https://github.com/karolsol](https://github.com/karolsol) - Piotr Strebski - [https://github.com/strebski](https://github.com/strebski) - Dawid Panyło -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Marcin Schoenknecht - Patryk - [https://github.com/byakurau](https://github.com/byakurau) - Michał Homza - [https://github.com/HagiaHaya](https://github.com/HagiaHaya) @@ -270,8 +359,11 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Portuguese -- Edson Wolf - [https://github.com/edsonblwolf](https://github.com/edsonblwolf) +- Ninguém Mesmo +- caue Antunes Siqueira - [https://github.com/caue-siqueira](https://github.com/caue-siqueira) - Anonymous - [https://github.com/weblate](https://github.com/weblate) +- The_Quintino - [https://github.com/paqgamer](https://github.com/paqgamer) +- Edson Wolf - [https://github.com/edsonblwolf](https://github.com/edsonblwolf) - Wilton Rodrigues - Guilherme Salomão - [https://github.com/salomaoparkour](https://github.com/salomaoparkour) - Bruno de Moura - [https://github.com/bruunomooura](https://github.com/bruunomooura) @@ -283,9 +375,14 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Portuguese (Brazil) +- Diego Menezes +- Rafael Acurcio - [https://github.com/faellacurcio](https://github.com/faellacurcio) +- Marina Aranha - [https://github.com/mariaranha](https://github.com/mariaranha) +- faciolihenrique - [https://github.com/faciolihenrique](https://github.com/faciolihenrique) +- Jênisson Alves de Andrade +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Ricardo Lima - [https://github.com/rhrlima](https://github.com/rhrlima) - Clerton Araujo - [https://github.com/clertonraf](https://github.com/clertonraf) -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Wilton Rodrigues - Nao interessa - Lucas Mezêncio - [https://github.com/lucasmezencio](https://github.com/lucasmezencio) @@ -295,15 +392,22 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Portuguese (Portugal) +- Ruben Sardinha +- Ninguém Mesmo +- FilipeAb - [https://github.com/FilipeAb](https://github.com/FilipeAb) - Anonymous - [https://github.com/weblate](https://github.com/weblate) ### Romanian +- Vlad Bejenaru - [https://github.com/vladbejenaru](https://github.com/vladbejenaru) - Bogdan Bujor - [https://github.com/qSharpy](https://github.com/qSharpy) - dimii27 - [https://github.com/dimii27](https://github.com/dimii27) ### Russian +- Iskander - [https://github.com/iskanderCabbie](https://github.com/iskanderCabbie) +- Aleksandr - [https://github.com/alexmikheen](https://github.com/alexmikheen) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Алексей Курышко - [https://github.com/alexkuryshko](https://github.com/alexkuryshko) - lightningcpu - [https://github.com/lightningcpu](https://github.com/lightningcpu) - Кирилл Александрович Злобин - [https://github.com/gungstarbeiter](https://github.com/gungstarbeiter) @@ -312,10 +416,24 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Serbian +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Mladen Trišić - [https://github.com/mtrisic](https://github.com/mtrisic) +### Slovak + +- Patrik - [https://github.com/P4TR1K1305](https://github.com/P4TR1K1305) + ### Spanish +- MarcMeRu11 - [https://github.com/marcmeru11](https://github.com/marcmeru11) +- v7mbz +- Pablo Sarabia Ortiz - [https://github.com/psarabiaortiz](https://github.com/psarabiaortiz) +- Daniel +- Alejandro Castro +- SirWerto +- Jose David Villegas (JoseDv1) - [https://github.com/JoseDv1](https://github.com/JoseDv1) +- Marco Diaz - [https://github.com/maditmx](https://github.com/maditmx) +- Oscar González - [https://github.com/ogrydc](https://github.com/ogrydc) - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Roberto Iglesias - [https://github.com/iglesiasroberto14](https://github.com/iglesiasroberto14) - c06c3abb8f @@ -329,10 +447,16 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Tamil -- தமிழ்நேரம் - [https://github.com/TamilNeram](https://github.com/TamilNeram) +- தமிழ்நேரம் +- Anonymous - [https://github.com/weblate](https://github.com/weblate) + +### Thai + +- Wiputdanai Pinkaew (Kang) - [https://github.com/kknownn](https://github.com/kknownn) ### Turkish +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Oğuz Ersen - [https://github.com/oersen](https://github.com/oersen) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) - Cem Avcı - [https://github.com/cem256](https://github.com/cem256) @@ -342,10 +466,13 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Ukrainian +- Максим Горпиніч - [https://github.com/maksim2005UKR](https://github.com/maksim2005UKR) +- Максим Горпиніч - [https://github.com/Maksim2005UA2](https://github.com/Maksim2005UA2) - Максим Горпиніч - [https://github.com/Maksim2005UA](https://github.com/Maksim2005UA) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) +- Максим Горпиніч - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) - Максим Горпиніч -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Dan - [https://github.com/Kefir2105](https://github.com/Kefir2105) - Dan - Tymofii Lytvynenko From 053243cd951ba02cc69014255f7a9d96ca5ced1e Mon Sep 17 00:00:00 2001 From: Github-Actions Date: Sun, 18 Jan 2026 12:29:56 +0000 Subject: [PATCH 47/48] Bump version to 1.10.0 --- flatpak/de.wger.flutter.metainfo.xml | 6 ++++++ pubspec.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/flatpak/de.wger.flutter.metainfo.xml b/flatpak/de.wger.flutter.metainfo.xml index badbff45d..799b045ba 100755 --- a/flatpak/de.wger.flutter.metainfo.xml +++ b/flatpak/de.wger.flutter.metainfo.xml @@ -84,6 +84,12 @@ + + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/1.10.0 +

Bug fixes and improvements.

diff --git a/pubspec.yaml b/pubspec.yaml index 613da16ca..a96c6690b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -21,7 +21,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # - the version number is taken from the git tag vX.Y.Z # - the build number is computed by reading the last one from the play store # and increasing by one -version: 1.9.6+160 +version: 1.10.0+170 environment: sdk: '>=3.8.0 <4.0.0' From 1d2bcc62dda2b9508c05e420cbf6e4879b547b44 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 19 Jan 2026 12:17:27 +0100 Subject: [PATCH 48/48] =?UTF-8?q?Set=20the=20current=20date=20when=20copyi?= =?UTF-8?q?ng=20a=20new=20log=20in=20the=20gym=20mode...=20=F0=9F=99=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #1084 --- lib/providers/gym_log_state.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/providers/gym_log_state.dart b/lib/providers/gym_log_state.dart index 96604c5b2..ec5e04521 100644 --- a/lib/providers/gym_log_state.dart +++ b/lib/providers/gym_log_state.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:wger/models/workouts/log.dart'; @@ -32,7 +33,8 @@ class GymLogNotifier extends _$GymLogNotifier { return null; } - void setLog(Log newLog) { + void setLog(Log log) { + final newLog = log.copyWith(id: null, date: clock.now()); state = newLog; }