From cbf6884a309eabb1cabcc776cb85aa7783c5a7d9 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 20 May 2026 14:14:00 +0200 Subject: [PATCH] Update the online connectivity gates Some of these models can now be edited completely locally, others only partly (e.g. the gallery entries can only be created online) --- lib/screens/nutritional_plan_screen.dart | 66 ++++++------- lib/screens/nutritional_plans_screen.dart | 28 +++--- lib/widgets/gallery/forms.dart | 14 ++- lib/widgets/gallery/overview.dart | 36 +++---- lib/widgets/nutrition/meal.dart | 26 +++-- .../nutrition/nutritional_plans_list.dart | 92 +++++++++--------- lib/widgets/routines/app_bar.dart | 1 - lib/widgets/routines/forms/routine.dart | 4 +- lib/widgets/routines/routines_list.dart | 96 +++++++++---------- test/gallery/gallery_form_test.dart | 33 ++++++- test/gallery/gallery_screen_test.dart | 15 ++- test/nutrition/meal_test.dart | 71 ++++++++++++++ .../nutritional_plan_screen_test.dart | 38 +++++++- .../nutritional_plans_screen_test.dart | 31 ++++-- test/routine/routine_form_test.dart | 23 ++++- test/routine/routine_screen_test.dart | 45 ++++++++- test/routine/routines_screen_test.dart | 12 ++- 17 files changed, 417 insertions(+), 214 deletions(-) create mode 100644 test/nutrition/meal_test.dart diff --git a/lib/screens/nutritional_plan_screen.dart b/lib/screens/nutritional_plan_screen.dart index a9211b30c..8f8448f01 100644 --- a/lib/screens/nutritional_plan_screen.dart +++ b/lib/screens/nutritional_plan_screen.dart @@ -21,7 +21,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg_icons/flutter_svg_icons.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/log_meals_screen.dart'; @@ -55,7 +54,6 @@ class _NutritionalPlanScreenState extends ConsumerState { @override Widget build(BuildContext context) { const appBarForeground = Colors.white; - final isOnline = ref.watch(networkStatusProvider); // Resolve the freshest plan from state so meal/diary edits reflect // immediately. Falls back to the route argument if state hasn't streamed // yet (e.g. cold open, deep link). @@ -70,20 +68,17 @@ class _NutritionalPlanScreenState extends ConsumerState { FloatingActionButton( heroTag: null, tooltip: AppLocalizations.of(context).logIngredient, - backgroundColor: isOnline ? null : Colors.grey, - onPressed: isOnline - ? () { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).logIngredient, - getIngredientLogForm(_nutritionalPlan), - hasListView: true, - ), - ); - } - : null, + onPressed: () { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).logIngredient, + getIngredientLogForm(_nutritionalPlan), + hasListView: true, + ), + ); + }, child: const SvgIcon( icon: SvgIconData('assets/icons/ingredient-diary.svg'), color: Colors.white, @@ -93,15 +88,12 @@ class _NutritionalPlanScreenState extends ConsumerState { FloatingActionButton( heroTag: null, tooltip: AppLocalizations.of(context).logMeal, - backgroundColor: isOnline ? null : Colors.grey, - onPressed: isOnline - ? () { - Navigator.of(context).pushNamed( - LogMealsScreen.routeName, - arguments: _nutritionalPlan, - ); - } - : null, + onPressed: () { + Navigator.of(context).pushNamed( + LogMealsScreen.routeName, + arguments: _nutritionalPlan, + ); + }, child: const SvgIcon( icon: SvgIconData('assets/icons/meal-diary.svg'), color: Colors.white, @@ -121,18 +113,16 @@ class _NutritionalPlanScreenState extends ConsumerState { icon: const SvgIcon( icon: SvgIconData('assets/icons/meal-add.svg'), ), - onPressed: isOnline - ? () { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).addMeal, - MealForm(_nutritionalPlan.id!), - ), - ); - } - : null, + onPressed: () { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).addMeal, + MealForm(_nutritionalPlan.id!), + ), + ); + }, ), PopupMenuButton( icon: const Icon(Icons.more_vert, color: appBarForeground), @@ -159,7 +149,6 @@ class _NutritionalPlanScreenState extends ConsumerState { return [ PopupMenuItem( value: NutritionalPlanOptions.edit, - enabled: isOnline, child: ListTile( leading: const Icon(Icons.edit), title: Text(AppLocalizations.of(context).edit), @@ -168,7 +157,6 @@ class _NutritionalPlanScreenState extends ConsumerState { const PopupMenuDivider(), PopupMenuItem( value: NutritionalPlanOptions.delete, - enabled: isOnline, child: ListTile( leading: const Icon(Icons.delete), title: Text(AppLocalizations.of(context).delete), diff --git a/lib/screens/nutritional_plans_screen.dart b/lib/screens/nutritional_plans_screen.dart index 60499c899..23ff56570 100644 --- a/lib/screens/nutritional_plans_screen.dart +++ b/lib/screens/nutritional_plans_screen.dart @@ -20,7 +20,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/providers/network_provider.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/core/app_bar.dart'; import 'package:wger/widgets/nutrition/forms.dart'; @@ -33,25 +32,20 @@ class NutritionalPlansScreen extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final isOnline = ref.watch(networkStatusProvider); - return Scaffold( appBar: EmptyAppBar(AppLocalizations.of(context).nutritionalPlans), floatingActionButton: FloatingActionButton( - backgroundColor: isOnline ? null : Colors.grey, - onPressed: isOnline - ? () { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).newNutritionalPlan, - hasListView: true, - PlanForm(), - ), - ); - } - : null, + onPressed: () { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).newNutritionalPlan, + hasListView: true, + PlanForm(), + ), + ); + }, child: const Icon(Icons.add, color: Colors.white), ), body: const WidescreenWrapper(child: NutritionalPlansList()), diff --git a/lib/widgets/gallery/forms.dart b/lib/widgets/gallery/forms.dart index 90ac1ec03..0a856f12d 100644 --- a/lib/widgets/gallery/forms.dart +++ b/lib/widgets/gallery/forms.dart @@ -103,6 +103,10 @@ class _ImageFormState extends ConsumerState { Widget build(BuildContext context) { final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); final isOnline = ref.watch(networkStatusProvider); + // Creating an image or replacing its photo is a binary REST upload and + // needs connectivity. A metadata-only edit syncs through PowerSync and + // works offline. + final requiresUpload = widget._image.id == null || _file != null; if (dateController.text.isEmpty) { dateController.text = dateFormat.format(widget._image.date); @@ -199,9 +203,9 @@ class _ImageFormState extends ConsumerState { ), ElevatedButton( key: const Key(SUBMIT_BUTTON_KEY_NAME), - child: Text(AppLocalizations.of(context).save), - onPressed: isOnline - ? () async { + onPressed: (requiresUpload && !isOnline) + ? null + : () async { // Validate and save final isValid = _form.currentState!.validate(); if (!isValid) { @@ -216,8 +220,8 @@ class _ImageFormState extends ConsumerState { notifier.editImage(widget._image, _file); } Navigator.of(context).pop(); - } - : null, + }, + child: Text(AppLocalizations.of(context).save), ), ], ), diff --git a/lib/widgets/gallery/overview.dart b/lib/widgets/gallery/overview.dart index 250fc35e2..9240328c8 100644 --- a/lib/widgets/gallery/overview.dart +++ b/lib/widgets/gallery/overview.dart @@ -24,7 +24,6 @@ import 'package:wger/helpers/platform.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/gallery/image.dart'; import 'package:wger/providers/gallery_notifier.dart'; -import 'package:wger/providers/network_provider.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/core/text_prompt.dart'; import 'package:wger/widgets/core/wger_image.dart'; @@ -79,7 +78,6 @@ class ImageDetail extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final isOnline = ref.watch(networkStatusProvider); return Container( key: Key('image-${image.id!}-detail'), padding: const EdgeInsets.all(10), @@ -104,29 +102,25 @@ class ImageDetail extends ConsumerWidget { children: [ IconButton( icon: const Icon(Icons.delete), - onPressed: isOnline - ? () { - ref.read(galleryProvider.notifier).deleteImage(image); - Navigator.of(context).pop(); - } - : null, + onPressed: () { + ref.read(galleryProvider.notifier).deleteImage(image); + Navigator.of(context).pop(); + }, ), if (!isDesktop) IconButton( icon: const Icon(Icons.edit), - onPressed: isOnline - ? () { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).edit, - ImageForm(image), - hasListView: true, - ), - ); - } - : null, + onPressed: () { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).edit, + ImageForm(image), + hasListView: true, + ), + ); + }, ), ], ), diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index e8e6a0f9e..c2ebf0717 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -23,7 +23,6 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; -import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/log_meal_screen.dart'; @@ -87,7 +86,6 @@ class _MealWidgetState extends ConsumerState { @override Widget build(BuildContext context) { - final isOnline = ref.watch(networkStatusProvider); return Container( padding: const EdgeInsets.all(3), child: Card( @@ -112,19 +110,17 @@ class _MealWidgetState extends ConsumerState { TextButton.icon( icon: const Icon(Icons.add), label: Text(AppLocalizations.of(context).addIngredient), - onPressed: isOnline - ? () { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).addIngredient, - getMealItemForm(widget._meal, widget._recentMealItems), - hasListView: true, - ), - ); - } - : null, + onPressed: () { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).addIngredient, + getMealItemForm(widget._meal, widget._recentMealItems), + hasListView: true, + ), + ); + }, ), TextButton.icon( label: Text(AppLocalizations.of(context).edit), diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index 35863ece5..4bf0d08c0 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -22,7 +22,6 @@ import 'package:intl/intl.dart'; import 'package:wger/helpers/measurements.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/body_weight_notifier.dart'; -import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/providers/user_profile_notifier.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; @@ -100,7 +99,6 @@ class NutritionalPlansList extends riverpod.ConsumerWidget { Widget build(BuildContext context, riverpod.WidgetRef ref) { final plansAsync = ref.watch(nutritionProvider); final notifier = ref.read(nutritionProvider.notifier); - final isOnline = ref.watch(networkStatusProvider); return AsyncValueWidget( value: plansAsync, @@ -153,56 +151,54 @@ class NutritionalPlansList extends riverpod.ConsumerWidget { IconButton( icon: const Icon(Icons.delete), tooltip: AppLocalizations.of(context).delete, - onPressed: isOnline - ? () async { - // Delete the plan from DB - await showDialog( - context: context, - builder: (BuildContext contextDialog) { - return AlertDialog( - content: Text( - AppLocalizations.of( - context, - ).confirmDelete(currentPlan.description), + onPressed: () async { + // Delete the plan from DB + await showDialog( + context: context, + builder: (BuildContext contextDialog) { + return AlertDialog( + content: Text( + AppLocalizations.of( + context, + ).confirmDelete(currentPlan.description), + ), + actions: [ + TextButton( + child: Text( + MaterialLocalizations.of(context).cancelButtonLabel, + ), + onPressed: () => Navigator.of(contextDialog).pop(), + ), + TextButton( + child: Text( + AppLocalizations.of(context).delete, + style: TextStyle( + color: Theme.of(context).colorScheme.error, ), - actions: [ - TextButton( - child: Text( - MaterialLocalizations.of(context).cancelButtonLabel, - ), - onPressed: () => Navigator.of(contextDialog).pop(), - ), - TextButton( - child: Text( - AppLocalizations.of(context).delete, - style: TextStyle( - color: Theme.of(context).colorScheme.error, - ), - ), - onPressed: () { - // Confirmed, delete the plan - notifier.deletePlan(currentPlan.id!); + ), + onPressed: () { + // Confirmed, delete the plan + notifier.deletePlan(currentPlan.id!); - // Close the popup - Navigator.of(contextDialog).pop(); + // Close the popup + Navigator.of(contextDialog).pop(); - // and inform the user - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - AppLocalizations.of(context).successfullyDeleted, - textAlign: TextAlign.center, - ), - ), - ); - }, + // and inform the user + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + AppLocalizations.of(context).successfullyDeleted, + textAlign: TextAlign.center, + ), ), - ], - ); - }, - ); - } - : null, + ); + }, + ), + ], + ); + }, + ); + }, ), ], ), diff --git a/lib/widgets/routines/app_bar.dart b/lib/widgets/routines/app_bar.dart index f6856c570..1cef14a72 100644 --- a/lib/widgets/routines/app_bar.dart +++ b/lib/widgets/routines/app_bar.dart @@ -108,7 +108,6 @@ class RoutineDetailAppBar extends ConsumerWidget implements PreferredSizeWidget ), PopupMenuItem<_RoutineDetailBarOptions>( value: _RoutineDetailBarOptions.delete, - enabled: isOnline, child: Text(i18n.delete), ), ]; diff --git a/lib/widgets/routines/forms/routine.dart b/lib/widgets/routines/forms/routine.dart index 638748d38..63ead852a 100644 --- a/lib/widgets/routines/forms/routine.dart +++ b/lib/widgets/routines/forms/routine.dart @@ -219,9 +219,11 @@ class _RoutineFormState extends ConsumerState { }, ), const SizedBox(height: 5), + // Creating a routine needs the server to assign an integer PK; editing an + // existing one syncs through PowerSync and works offline. ElevatedButton( key: const Key(SUBMIT_BUTTON_KEY_NAME), - onPressed: isSaving || !isOnline + onPressed: isSaving || (widget._routine.id == null && !isOnline) ? null : () async { // Validate and save diff --git a/lib/widgets/routines/routines_list.dart b/lib/widgets/routines/routines_list.dart index 312160275..f37bc903f 100644 --- a/lib/widgets/routines/routines_list.dart +++ b/lib/widgets/routines/routines_list.dart @@ -20,7 +20,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/routines_notifier.dart'; import 'package:wger/screens/routine_screen.dart'; import 'package:wger/widgets/core/async_value_widget.dart'; @@ -38,7 +37,6 @@ class _RoutinesListState extends ConsumerState { @override Widget build(BuildContext context) { - final isOnline = ref.watch(networkStatusProvider); final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); final routineProvider = ref.read(routinesRiverpodProvider.notifier); final routinesAsync = ref.watch(routinesRiverpodProvider); @@ -96,58 +94,56 @@ class _RoutinesListState extends ConsumerState { IconButton( icon: const Icon(Icons.delete), tooltip: AppLocalizations.of(context).delete, - onPressed: isOnline - ? () async { - // Delete workout from DB - await showDialog( - context: context, - builder: (BuildContext contextDialog) { - return AlertDialog( - content: Text( - AppLocalizations.of( - context, - ).confirmDelete(currentRoutine.name), + onPressed: () async { + // Delete workout from DB + await showDialog( + context: context, + builder: (BuildContext contextDialog) { + return AlertDialog( + content: Text( + AppLocalizations.of( + context, + ).confirmDelete(currentRoutine.name), + ), + actions: [ + TextButton( + child: Text( + MaterialLocalizations.of(context).cancelButtonLabel, + ), + onPressed: () => Navigator.of(contextDialog).pop(), + ), + TextButton( + child: Text( + AppLocalizations.of(context).delete, + style: TextStyle( + color: Theme.of(context).colorScheme.error, ), - actions: [ - TextButton( - child: Text( - MaterialLocalizations.of(context).cancelButtonLabel, - ), - onPressed: () => Navigator.of(contextDialog).pop(), - ), - TextButton( - child: Text( - AppLocalizations.of(context).delete, - style: TextStyle( - color: Theme.of(context).colorScheme.error, - ), - ), - onPressed: () { - // Confirmed, delete the workout - routineProvider.deleteRoutine(currentRoutine.id!); + ), + onPressed: () { + // Confirmed, delete the workout + routineProvider.deleteRoutine(currentRoutine.id!); - // Close the popup - Navigator.of(contextDialog).pop(); + // Close the popup + Navigator.of(contextDialog).pop(); - // and inform the user - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - AppLocalizations.of( - context, - ).successfullyDeleted, - textAlign: TextAlign.center, - ), - ), - ); - }, + // and inform the user + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + AppLocalizations.of( + context, + ).successfullyDeleted, + textAlign: TextAlign.center, + ), ), - ], - ); - }, - ); - } - : null, + ); + }, + ), + ], + ); + }, + ); + }, ), ], ), diff --git a/test/gallery/gallery_form_test.dart b/test/gallery/gallery_form_test.dart index 4da944a33..58102fc3e 100644 --- a/test/gallery/gallery_form_test.dart +++ b/test/gallery/gallery_form_test.dart @@ -26,6 +26,7 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/gallery/image.dart'; import 'package:wger/providers/gallery_repository.dart'; +import 'package:wger/providers/network_provider.dart'; import 'package:wger/widgets/gallery/forms.dart'; import '../../test_data/gallery.dart'; @@ -43,9 +44,10 @@ void main() { when(mockGalleryRepository.editLocalDrift(any)).thenAnswer((_) async {}); }); - Widget createScreen({useImage = true, locale = 'en'}) { + Widget createScreen({useImage = true, locale = 'en', bool isOnline = true}) { return ProviderScope( overrides: [ + networkStatusProvider.overrideWithValue(isOnline), galleryRepositoryProvider.overrideWithValue(mockGalleryRepository), ], child: MaterialApp( @@ -85,4 +87,33 @@ void main() { expect(find.text('Please select an image'), findsOneWidget); expect(find.byIcon(Icons.photo_camera), findsOneWidget); }); + + testWidgets('Submit stays enabled offline for a metadata-only edit', ( + WidgetTester tester, + ) async { + // Editing an existing image without replacing the photo syncs through + // PowerSync, so it works offline. + await mockNetworkImagesFor( + () => tester.pumpWidget(createScreen(useImage: true, isOnline: false)), + ); + await tester.pumpAndSettle(); + + final button = tester.widget( + find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), + ); + expect(button.onPressed, isNotNull); + }); + + testWidgets('Submit is disabled offline for a new image', (WidgetTester tester) async { + // Creating an image is a binary REST upload and needs connectivity. + await mockNetworkImagesFor( + () => tester.pumpWidget(createScreen(useImage: false, isOnline: false)), + ); + await tester.pumpAndSettle(); + + final button = tester.widget( + find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), + ); + expect(button.onPressed, isNull); + }); } diff --git a/test/gallery/gallery_screen_test.dart b/test/gallery/gallery_screen_test.dart index 2041b1678..299674632 100644 --- a/test/gallery/gallery_screen_test.dart +++ b/test/gallery/gallery_screen_test.dart @@ -25,6 +25,7 @@ import 'package:mockito/mockito.dart'; import 'package:network_image_mock/network_image_mock.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/gallery_repository.dart'; +import 'package:wger/providers/network_provider.dart'; import 'package:wger/widgets/gallery/overview.dart'; import '../../test_data/gallery.dart'; @@ -55,9 +56,10 @@ void main() { ); } - Widget renderDetail({locale = 'en'}) { + Widget renderDetail({locale = 'en', bool isOnline = true}) { return ProviderScope( overrides: [ + networkStatusProvider.overrideWithValue(isOnline), galleryRepositoryProvider.overrideWithValue(mockGalleryRepository), ], child: MaterialApp( @@ -92,4 +94,15 @@ void main() { expect(find.text('30.5.2021'), findsOneWidget); }); + + testWidgets('Delete stays enabled when offline', (WidgetTester tester) async { + // Image deletion syncs through PowerSync, so it works offline. + await mockNetworkImagesFor(() => tester.pumpWidget(renderDetail(isOnline: false))); + await tester.pumpAndSettle(); + + final deleteButton = tester.widget( + find.widgetWithIcon(IconButton, Icons.delete), + ); + expect(deleteButton.onPressed, isNotNull); + }); } diff --git a/test/nutrition/meal_test.dart b/test/nutrition/meal_test.dart new file mode 100644 index 000000000..5ef44b464 --- /dev/null +++ b/test/nutrition/meal_test.dart @@ -0,0 +1,71 @@ +/* + * 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_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/nutrition/meal.dart'; +import 'package:wger/providers/network_provider.dart'; +import 'package:wger/widgets/nutrition/meal.dart'; + +void main() { + Meal buildMeal() => Meal( + id: 'aa000000-0000-4000-8000-000000000001', + plan: 'bb000000-0000-4000-8000-000000000001', + name: 'Breakfast', + time: const TimeOfDay(hour: 8, minute: 0), + ); + + Widget renderMeal({bool isOnline = true}) { + return ProviderScope( + // The meal widget does not gate its actions on connectivity. Pinning the + // network status to offline makes a re-introduced connectivity gate fail + // this test. + overrides: [networkStatusProvider.overrideWithValue(isOnline)], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SingleChildScrollView( + child: MealWidget(buildMeal(), const [], false, false), + ), + ), + ), + ); + } + + testWidgets('Add-ingredient button stays enabled when offline', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(renderMeal(isOnline: false)); + await tester.pumpAndSettle(); + + // Reveal the meal action buttons by entering editing mode. + await tester.tap(find.byIcon(Icons.edit)); + await tester.pumpAndSettle(); + + final addButton = tester.widget( + find.ancestor( + of: find.byIcon(Icons.add), + matching: find.byType(TextButton), + ), + ); + expect(addButton.onPressed, isNotNull); + }); +} diff --git a/test/nutrition/nutritional_plan_screen_test.dart b/test/nutrition/nutritional_plan_screen_test.dart index 303829d10..4f0d54ad6 100644 --- a/test/nutrition/nutritional_plan_screen_test.dart +++ b/test/nutrition/nutritional_plan_screen_test.dart @@ -29,6 +29,7 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/providers/body_weight_repository.dart'; import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; @@ -82,9 +83,10 @@ void main() { when(mockIngredientRepo.watchById(any)).thenAnswer((_) => Stream.value(fetchedIngredient)); }); - ProviderContainer makeContainer() { + ProviderContainer makeContainer({bool isOnline = true}) { final container = ProviderContainer( overrides: [ + networkStatusProvider.overrideWithValue(isOnline), bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository), nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo), ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), @@ -196,6 +198,40 @@ void main() { tags: ['golden'], ); + testWidgets('Logging and meal actions stay enabled when offline', (tester) async { + tester.view.physicalSize = const Size(500, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + final container = makeContainer(isOnline: false); + await tester.pumpWidget(createNutritionalPlan(container: container)); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + + // Diary logging and meal management all sync through PowerSync. + final fabs = tester.widgetList( + find.byType(FloatingActionButton), + ); + expect(fabs, isNotEmpty); + for (final fab in fabs) { + expect(fab.onPressed, isNotNull); + } + + // The plan edit/delete actions in the app bar menu. + await tester.tap(find.byIcon(Icons.more_vert)); + await tester.pumpAndSettle(); + final menuItems = tester.widgetList>( + find.byType(PopupMenuItem), + ); + expect(menuItems, hasLength(2)); + for (final item in menuItems) { + expect(item.enabled, isTrue); + } + }); + testWidgets('Tests the localization of times - EN', (WidgetTester tester) async { final container = makeContainer(); await tester.pumpWidget(createNutritionalPlan(container: container)); diff --git a/test/nutrition/nutritional_plans_screen_test.dart b/test/nutrition/nutritional_plans_screen_test.dart index 5c8fc1b30..8704d8022 100644 --- a/test/nutrition/nutritional_plans_screen_test.dart +++ b/test/nutrition/nutritional_plans_screen_test.dart @@ -150,19 +150,36 @@ void main() { expect(find.byType(PlanForm), findsOneWidget); }); - testWidgets('Add-plan FAB is disabled when offline', (WidgetTester tester) async { - // Plan creation still goes through REST, so the FAB must not let users - // navigate into a form they can't submit. + testWidgets('Add-plan FAB stays enabled when offline', (WidgetTester tester) async { + // Plan creation goes through PowerSync, so it works offline. await tester.pumpWidget(createHomeScreen(isOnline: false)); await tester.pumpAndSettle(); final fab = tester.widget(find.byType(FloatingActionButton)); - expect(fab.onPressed, isNull); + expect(fab.onPressed, isNotNull); - // Tapping must not push the form route. - await tester.tap(find.byType(FloatingActionButton), warnIfMissed: false); + // Tapping opens the form. + await tester.tap(find.byType(FloatingActionButton)); await tester.pumpAndSettle(); - expect(find.byType(PlanForm), findsNothing); + expect(find.byType(PlanForm), findsOneWidget); + }); + + testWidgets('Delete button stays enabled when offline', (WidgetTester tester) async { + // Plan deletion syncs through PowerSync, so it works offline. + await tester.pumpWidget(createHomeScreen(isOnline: false)); + await tester.pumpAndSettle(); + + final deleteButton = tester.widget( + find.widgetWithIcon(IconButton, Icons.delete).first, + ); + expect(deleteButton.onPressed, isNotNull); + + await tester.tap(find.byIcon(Icons.delete).first); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + await tester.tap(find.text('Delete')); + await tester.pumpAndSettle(); + verify(mockNutritionRepo.deleteLocalDrift(any)).called(1); }); testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { diff --git a/test/routine/routine_form_test.dart b/test/routine/routine_form_test.dart index 4d89d579c..dbc12a6ac 100644 --- a/test/routine/routine_form_test.dart +++ b/test/routine/routine_form_test.dart @@ -253,18 +253,35 @@ void main() { expect(find.text('The name is not valid'), findsOneWidget, reason: 'Error message is shown'); }); - testWidgets('Submit button is disabled when offline', (WidgetTester tester) async { + testWidgets('Submit stays enabled offline when editing a routine', (WidgetTester tester) async { + // Editing a routine syncs through PowerSync and works offline. await tester.pumpWidget(renderWidget(existingRoutine, isOnline: false)); await tester.pumpAndSettle(); + final button = tester.widget( + find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), + ); + expect(button.onPressed, isNotNull); + + await tester.enterText(find.byKey(const Key('field-name')), 'New name'); + await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); + await tester.pump(); + verify(mockRoutinesRepository.editLocalDrift(any)); + }); + + testWidgets('Submit is disabled offline when creating a routine', (WidgetTester tester) async { + // Creating a routine needs the server to assign the integer PK. + await tester.pumpWidget(renderWidget(newRoutine, isOnline: false)); + await tester.pumpAndSettle(); + final button = tester.widget( find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), ); expect(button.onPressed, isNull); - // And tapping it must not trigger the edit request. + // And tapping it must not trigger the create request. await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), warnIfMissed: false); await tester.pump(); - verifyNever(mockRoutinesRepository.editLocalDrift(any)); + verifyNever(mockRoutinesRepository.addRoutineServer(any)); }); } diff --git a/test/routine/routine_screen_test.dart b/test/routine/routine_screen_test.dart index 9ef18eb27..1d11caf8d 100644 --- a/test/routine/routine_screen_test.dart +++ b/test/routine/routine_screen_test.dart @@ -38,12 +38,12 @@ class _StubRoutinesRiverpod extends RoutinesRiverpod { } void main() { - Widget renderWidget({locale = 'en'}) { + Widget renderWidget({locale = 'en', bool isOnline = true}) { final key = GlobalKey(); final container = ProviderContainer.test( overrides: [ - networkStatusProvider.overrideWithValue(true), + networkStatusProvider.overrideWithValue(isOnline), routinesRiverpodProvider.overrideWith( () => _StubRoutinesRiverpod([getTestRoutine()]), ), @@ -101,4 +101,45 @@ void main() { }, tags: ['golden'], ); + + testWidgets('App bar menu: delete works offline, edit needs online', ( + WidgetTester tester, + ) async { + tester.view.physicalSize = const Size(500, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + await tester.pumpWidget(renderWidget(isOnline: false)); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + + // Open the routine detail app bar menu. + await tester.tap( + find.descendant( + of: find.byType(AppBar), + matching: find.byWidgetPredicate((w) => w is PopupMenuButton), + ), + ); + await tester.pumpAndSettle(); + + // itemBuilder order: workout logs, edit, delete. + final items = tester + .widgetList(find.byWidgetPredicate((w) => w is PopupMenuItem)) + .cast() + .toList(); + expect(items, hasLength(3)); + expect( + items[1].enabled, + isFalse, + reason: 'Edit opens the structure editor (REST), needs connectivity', + ); + expect( + items[2].enabled, + isTrue, + reason: 'Delete syncs through PowerSync and works offline', + ); + }); } diff --git a/test/routine/routines_screen_test.dart b/test/routine/routines_screen_test.dart index ffbccb5b4..2cfa7f156 100644 --- a/test/routine/routines_screen_test.dart +++ b/test/routine/routines_screen_test.dart @@ -115,14 +115,22 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('Handle offline status', (WidgetTester tester) async { + testWidgets('Delete button stays enabled when offline', (WidgetTester tester) async { + // Routine deletion syncs through PowerSync, so it must work offline. await tester.pumpWidget(renderWidget(isOnline: false)); await tester.pumpAndSettle(); final deleteButton = tester.widget( find.widgetWithIcon(IconButton, Icons.delete).first, ); - expect(deleteButton.onPressed, isNull); + expect(deleteButton.onPressed, isNotNull); + + // The confirmation dialog opens and the delete flow runs through. + await tester.tap(find.byIcon(Icons.delete).first); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + await tester.tap(find.text('Delete')); + await tester.pumpAndSettle(); }); testWidgets('Test the form on the workout plan screen', (WidgetTester tester) async {