Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions lib/helpers/shared_preferences.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences/util/legacy_to_async_migration_util.dart';
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/providers/nutrition.dart';

/// A helper class that manages preferences using SharedPreferencesAsync
Expand Down Expand Up @@ -68,4 +69,24 @@ class PreferenceHelper {
);
}
}

//4.nutri-score worst acceptable grade (null means the filter is off)
Future<void> saveIngredientNutriscoreMax(NutriScore? value) async {
if (value == null) {
await PreferenceHelper.asyncPref.remove('ingredientNutriscoreMax');
} else {
await PreferenceHelper.asyncPref.setString('ingredientNutriscoreMax', value.name);
}
}

Future<NutriScore?> getIngredientNutriscoreMax() async {
final value = await PreferenceHelper.asyncPref.getString('ingredientNutriscoreMax');
if (value == null) {
return null;
}
return NutriScore.values.firstWhere(
(e) => e.name == value,
orElse: () => NutriScore.c,
);
}
}
24 changes: 23 additions & 1 deletion lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -1199,5 +1199,27 @@
}
},
"searchLanguageAll": "All languages",
"@searchLanguageAll": {}
"@searchLanguageAll": {},
"filterNutriscore": "Nutri-Score filter",
"@filterNutriscore": {
"description": "Heading for the Nutri-Score slider in the ingredient search filter dialog"
},
"filterNutriscoreOff": "Off",
"@filterNutriscoreOff": {
"description": "Label for the first slider stop, which disables the Nutri-Score filter"
},
"filterNutriscoreNoFilter": "No filter",
"@filterNutriscoreNoFilter": {
"description": "Helper text shown under the Nutri-Score slider when it is at the Off position"
},
"filterNutriscoreOrBetter": "{grade} or better",
"@filterNutriscoreOrBetter": {
"description": "Helper text shown under the Nutri-Score slider when a grade is selected (e.g. 'C or better')",
"placeholders": {
"grade": {
"type": "String",
"example": "C"
}
}
}
}
11 changes: 11 additions & 0 deletions lib/models/nutrition/ingredient_filters.dart
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
//model is used to store ingredient filters values
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/providers/nutrition.dart';

class IngredientFilters {
final bool isVegan;
final bool isVegetarian;
final IngredientSearchLanguage searchLanguage;

/// Worst acceptable Nutri-Score grade, sent to the backend as
/// `nutriscore__lte`. `null` means the filter is off (slider at the
/// "No filter" position).
final NutriScore? nutriscoreMax;

IngredientFilters({
required this.isVegan,
required this.isVegetarian,
required this.searchLanguage,
this.nutriscoreMax,
});

IngredientFilters copyWith({
bool? isVegan,
bool? isVegetarian,
IngredientSearchLanguage? searchLanguage,
NutriScore? nutriscoreMax,
bool clearNutriscoreMax = false,
}) {
return IngredientFilters(
isVegan: isVegan ?? this.isVegan,
isVegetarian: isVegetarian ?? this.isVegetarian,
searchLanguage: searchLanguage ?? this.searchLanguage,
nutriscoreMax: clearNutriscoreMax ? null : (nutriscoreMax ?? this.nutriscoreMax),
);
}
}
10 changes: 10 additions & 0 deletions lib/providers/nutrition.dart
Original file line number Diff line number Diff line change
Expand Up @@ -403,12 +403,18 @@ class NutritionPlansProvider with ChangeNotifier {
}

/// Searches for an ingredient
///
/// [nutriscoreMax] — if non-null, the worst acceptable Nutri-Score grade,
/// sent to the backend as `nutriscore__lte`. The Django filterset
/// compares lexicographically on the `a`..`e` choices, so passing
/// [NutriScore.b] yields "only A or B".
Future<List<Ingredient>> searchIngredient(
String name, {
String languageCode = 'en',
IngredientSearchLanguage searchLanguage = IngredientSearchLanguage.current,
bool isVegan = false,
bool isVegetarian = false,
NutriScore? nutriscoreMax,
}) async {
if (name.length <= 1) {
return [];
Expand Down Expand Up @@ -447,6 +453,10 @@ class NutritionPlansProvider with ChangeNotifier {
query['is_vegetarian'] = 'true';
}

if (nutriscoreMax != null) {
query['nutriscore__lte'] = nutriscoreMax.name;
}

// Send the request
_logger.info('Fetching ingredients from server');
final response = await baseProvider.fetch(
Expand Down
13 changes: 13 additions & 0 deletions lib/providers/nutrition_ingredient_filters_riverpod.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import 'package:flutter_riverpod/flutter_riverpod.dart' show Provider;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:wger/helpers/shared_preferences.dart';
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/models/nutrition/ingredient_filters.dart';
import 'package:wger/providers/nutrition.dart';

Expand All @@ -33,10 +34,12 @@ class IngredientFiltersNotifier extends _$IngredientFiltersNotifier {
final isVegan = await preferenceHelper.getIngredientVeganFilter();
final isVegetarian = await preferenceHelper.getIngredientVegetarianFilter();
final searchLanguage = await preferenceHelper.getIngredientSearchLanguage();
final nutriscoreMax = await preferenceHelper.getIngredientNutriscoreMax();
return IngredientFilters(
isVegan: isVegan,
isVegetarian: isVegetarian,
searchLanguage: searchLanguage,
nutriscoreMax: nutriscoreMax,
);
}

Expand Down Expand Up @@ -67,6 +70,16 @@ class IngredientFiltersNotifier extends _$IngredientFiltersNotifier {
state = AsyncData(current.copyWith(searchLanguage: value));
await PreferenceHelper.instance.saveIngredientSearchLanguage(value);
}

Future<void> chooseNutriscoreMax(NutriScore? value) async {
final current = _current();
state = AsyncData(
value == null
? current.copyWith(clearNutriscoreMax: true)
: current.copyWith(nutriscoreMax: value),
);
await PreferenceHelper.instance.saveIngredientNutriscoreMax(value);
}
}

// Synchronous helper provider to unwrap the AsyncValue produced by `ingredientFiltersProvider`
Expand Down
12 changes: 8 additions & 4 deletions lib/providers/nutrition_ingredient_filters_riverpod.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

79 changes: 79 additions & 0 deletions lib/widgets/nutrition/widgets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ class _IngredientTypeaheadState extends ConsumerState<IngredientTypeahead> {
searchLanguage: filters.searchLanguage,
isVegan: filters.isVegan,
isVegetarian: filters.isVegetarian,
nutriscoreMax: filters.nutriscoreMax,
);
},
itemBuilder: (context, ingredient) {
Expand Down Expand Up @@ -375,6 +376,16 @@ class _IngredientTypeaheadState extends ConsumerState<IngredientTypeahead> {
});
},
),
_NutriscoreSlider(
value: filters.nutriscoreMax,
onChanged: (grade) {
setDialogState(() {
ref
.read(ingredientFiltersProvider.notifier)
.chooseNutriscoreMax(grade);
});
},
),
],
),
actions: [
Expand All @@ -395,6 +406,74 @@ class _IngredientTypeaheadState extends ConsumerState<IngredientTypeahead> {
}
}

/// Discrete slider that lets the user pick the worst acceptable [NutriScore]
/// grade. Index 0 is the "Off" position (no filter, `null` value) and
/// indices 1..N map to [NutriScore.values].
class _NutriscoreSlider extends StatelessWidget {
final NutriScore? value;
final ValueChanged<NutriScore?> onChanged;

const _NutriscoreSlider({required this.value, required this.onChanged});

static const int _offIndex = 0;

int _valueToIndex(NutriScore? v) => v == null ? _offIndex : NutriScore.values.indexOf(v) + 1;

NutriScore? _indexToValue(int i) => i == _offIndex ? null : NutriScore.values[i - 1];

@override
Widget build(BuildContext context) {
final i18n = AppLocalizations.of(context);
final index = _valueToIndex(value);
final maxIndex = NutriScore.values.length; // 0=Off, then A..E
final helperText = value == null
? i18n.filterNutriscoreNoFilter
: i18n.filterNutriscoreOrBetter(value!.name.toUpperCase());
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
i18n.filterNutriscore,
style: Theme.of(context).textTheme.bodyMedium,
),
Text(
helperText,
style: Theme.of(context).textTheme.bodySmall,
),
Slider(
value: index.toDouble(),
min: 0,
max: maxIndex.toDouble(),
divisions: maxIndex,
label: value == null ? i18n.filterNutriscoreOff : value!.name.toUpperCase(),
onChanged: (v) => onChanged(_indexToValue(v.round())),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
i18n.filterNutriscoreOff,
style: Theme.of(context).textTheme.labelSmall,
),
...NutriScore.values.map(
(score) => Text(
score.name.toUpperCase(),
style: Theme.of(context).textTheme.labelSmall,
),
),
],
),
),
],
),
);
}
}

class IngredientAvatar extends StatelessWidget {
final Ingredient ingredient;

Expand Down
2 changes: 2 additions & 0 deletions test/core/settings_test.mocks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,7 @@ class MockNutritionPlansProvider extends _i1.Mock implements _i20.NutritionPlans
_i20.IngredientSearchLanguage? searchLanguage = _i20.IngredientSearchLanguage.current,
bool? isVegan = false,
bool? isVegetarian = false,
_i13.NutriScore? nutriscoreMax,
}) =>
(super.noSuchMethod(
Invocation.method(
Expand All @@ -840,6 +841,7 @@ class MockNutritionPlansProvider extends _i1.Mock implements _i20.NutritionPlans
#searchLanguage: searchLanguage,
#isVegan: isVegan,
#isVegetarian: isVegetarian,
#nutriscoreMax: nutriscoreMax,
},
),
returnValue: _i18.Future<List<_i13.Ingredient>>.value(
Expand Down
Loading