Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Nutrition: fasting, per 100 g quick add, food groups and archived dishes
InlitX29233fa1b8f1
diff --git a/lib/models/nutrition.dart b/lib/models/nutrition.dartindex 2aee3d3..931efbc 100644--- a/lib/models/nutrition.dart+++ b/lib/models/nutrition.dart@@ -206,6 +206,21 @@ String assetOfPhoto(String photo) => photo.substring(6);enum FoodCat { fruit, veg, meat, fish, egg, dairy, grain, bakery, legume, nut, oil, pantry, drink, sauce, spice }+class FoodGroup {+ FoodGroup(this.id, this.name);++ final String id;+ String name;++ Map<String, dynamic> toJson() => {'id': id, 'n': name};++ static FoodGroup? fromJson(Map<String, dynamic> j) {+ final id = j['id'] as String? ?? '';+ final name = (j['n'] as String? ?? '').trim();+ return id.isEmpty || name.isEmpty ? null : FoodGroup(id, name);+ }+}+class FoodItem {const FoodItem({required this.id,@@ -220,6 +235,8 @@ class FoodItem {this.cookedYield = 0,this.approx = false,this.cat,+ this.water = 0,+ this.group = '',});final String id;@@ -228,12 +245,14 @@ class FoodItem {final String serving;final double grams;final bool liquid;+ final int water;final PortionKind? portion;final double portionGrams;final Macros macros;final double cookedYield;final bool approx;final FoodCat? cat;+ final String group;bool get isLibrary => id.startsWith(kLibraryPrefix);@@ -250,6 +269,8 @@ class FoodItem {Macros? macros,double? cookedYield,FoodCat? Function()? cat,+ int? water,+ String? group,}) =>FoodItem(id: id,@@ -264,6 +285,8 @@ class FoodItem {cookedYield: cookedYield ?? this.cookedYield,approx: approx,cat: cat == null ? this.cat : cat(),+ water: water ?? this.water,+ group: group ?? this.group,);Map<String, dynamic> toJson() => {@@ -275,6 +298,8 @@ class FoodItem {if (liquid) 'lq': true,if (cookedYield > 0) 'cy': cookedYield,if (cat != null) 'c': cat!.name,+ if (water > 0) 'w': water,+ if (group.isNotEmpty) 'uc': group,'m': macros.toJson(),};@@ -288,9 +313,13 @@ class FoodItem {cookedYield: _num(j['cy']).clamp(0, 5).toDouble(),macros: Macros.fromJson((j['m'] as Map?)?.cast<String, dynamic>()),cat: FoodCat.values.asNameMap()[j['c']],+ water: _waterMl(j['w']),+ group: j['uc'] as String? ?? '',);}+int _waterMl(Object? v) => ((v as num?)?.toInt() ?? 0).clamp(0, 5000);+class FoodEntry {const FoodEntry({required this.id,@@ -303,6 +332,7 @@ class FoodEntry {this.liquid = false,this.cooked = 0,this.per = Macros.zero,+ this.water = 0,});final String id;@@ -315,9 +345,12 @@ class FoodEntry {final bool liquid;final double cooked;final Macros per;+ final int water;Macros get total => per * servings;+ int get waterMl => water <= 0 ? 0 : (water * servings).round();+double get totalGrams => grams * servings;double get shownGrams => cooked > 0 ? totalGrams * cooked : totalGrams;@@ -333,6 +366,7 @@ class FoodEntry {liquid: liquid,cooked: cooked,per: per ?? this.per,+ water: water,);Map<String, dynamic> toJson() => {@@ -345,6 +379,7 @@ class FoodEntry {if (grams > 0) 'g': grams,if (liquid) 'lq': true,if (cooked > 0) 'ck': cooked,+ if (water > 0) 'w': water,'m': per.toJson(),};@@ -359,6 +394,7 @@ class FoodEntry {liquid: j['lq'] as bool? ?? false,cooked: _num(j['ck']).clamp(0, 5).toDouble(),per: Macros.fromJson((j['m'] as Map?)?.cast<String, dynamic>()),+ water: _waterMl(j['w']),);}@@ -673,6 +709,26 @@ class Batch {}}+class FastRecord {+ const FastRecord(this.start, this.end, this.goalHours);+ final DateTime start;+ final DateTime end;+ final int goalHours;++ Duration get length => end.difference(start);+ bool get reached => length.inMinutes >= goalHours * 60;++ Map<String, dynamic> toJson() => {'s': start.toIso8601String(), 'e': end.toIso8601String(), 'g': goalHours};++ static FastRecord? fromJson(Map<String, dynamic> j) {+ final s = DateTime.tryParse(j['s'] as String? ?? '');+ final e = DateTime.tryParse(j['e'] as String? ?? '');+ final g = (j['g'] as num?)?.toInt() ?? 16;+ if (s == null || e == null || !e.isAfter(s)) return null;+ return FastRecord(s, e, g.clamp(1, 72));+ }+}+enum Tracker {calories,protein,@@ -691,6 +747,14 @@ enum Tracker {prep,foods,plans,+ fasting,}-const kTrackersOffByDefault = {Tracker.fiber, Tracker.animal, Tracker.quality, Tracker.fats, Tracker.sugarSodium};+const kTrackersOffByDefault = {+ Tracker.fiber,+ Tracker.animal,+ Tracker.quality,+ Tracker.fats,+ Tracker.sugarSodium,+ Tracker.fasting,+};diff --git a/lib/screens/nutrition/cards.dart b/lib/screens/nutrition/cards.dartindex 973b0c2..b74571f 100644--- a/lib/screens/nutrition/cards.dart+++ b/lib/screens/nutrition/cards.dart@@ -290,7 +290,7 @@ class _QualityCard extends StatelessWidget {Text('${_g(grams)} g', style: AppTheme.f(13, weight: FontWeight.w800, color: gc.text)),]);return SoftCard(- radius: 24,+ radius: 22,padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [@@ -530,7 +530,7 @@ class _FatTypesCard extends StatelessWidget {]),);return SoftCard(- radius: 24,+ radius: 22,padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [@@ -694,6 +694,7 @@ Future<void> showWaterSheet(BuildContext context) => _sheet<void>(context, (contfinal day = fit.nutritionDay;final g = fit.activeGoals;final sips = fit.waterSipsOn(day).reversed.toList();+ final drinks = [for (final e in fit.entriesOn(day).reversed) if (e.waterMl > 0) e];final big = fit.isLb ? 473 : 500;String time(DateTime d) => '${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';return _sheetFrame(context, [@@ -714,7 +715,7 @@ Future<void> showWaterSheet(BuildContext context) => _sheet<void>(context, (contconst SizedBox(height: 18),_kicker(gc, (fit.nutritionOnToday ? t.nutritionToday : t.longDate(day)).toUpperCase()),const SizedBox(height: 8),- if (sips.isEmpty)+ if (sips.isEmpty && drinks.isEmpty)Padding(padding: const EdgeInsets.symmetric(vertical: 8),child: Text(t.waterNone, style: AppTheme.s(13, color: gc.textTertiary)),@@ -723,9 +724,26 @@ Future<void> showWaterSheet(BuildContext context) => _sheet<void>(context, (contConstrainedBox(constraints: const BoxConstraints(maxHeight: 220),child: SoftCard(- radius: 20,+ radius: 22,padding: const EdgeInsets.symmetric(vertical: 4),child: ListView(shrinkWrap: true, padding: EdgeInsets.zero, children: [+ for (final e in drinks)+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 14, 20, 14),+ child: Row(children: [+ Icon(PhosphorIconsFill.forkKnife, size: 15, color: gc.water),+ const SizedBox(width: 10),+ Text(fit.waterLabel(e.waterMl), style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),+ const SizedBox(width: 8),+ Expanded(+ child: Text(e.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.textSecondary)),+ ),+ Text(time(e.at), style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textTertiary)),+ ]),+ ),for (final w in sips)Padding(padding: const EdgeInsets.fromLTRB(16, 6, 6, 6),@@ -855,7 +873,7 @@ Future<void> showShakePicker(BuildContext context) => _sheet<void>(context, (conif (others.isNotEmpty) ...[const SizedBox(height: 18),Text(t.shakeMarkLabel,- style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.1)),+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),const SizedBox(height: 8),SizedBox(height: 44,@@ -1658,7 +1676,7 @@ class _ChartCard extends StatelessWidget {onLongPress: onLongPress,scale: 0.98,child: SoftCard(- radius: 24,+ radius: 22,padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [diff --git a/lib/screens/nutrition/fasting.dart b/lib/screens/nutrition/fasting.dartnew file mode 100644index 0000000..20d52ee--- /dev/null+++ b/lib/screens/nutrition/fasting.dart@@ -0,0 +1,311 @@+part of '../nutrition_screen.dart';++String _span(Duration d) {+ final m = d.inMinutes.abs();+ final h = m ~/ 60, rest = m % 60;+ if (h == 0) return t.fastMinutes(rest);+ if (rest == 0) return t.fastHours(h);+ return t.fastHoursMinutes(h, rest);+}++Future<DateTime?> _pickFastStart(BuildContext context, DateTime initial) async {+ final picked = await showTimePicker(+ context: context,+ initialTime: TimeOfDay.fromDateTime(initial),+ initialEntryMode: TimePickerEntryMode.inputOnly,+ helpText: t.fastStartedAt,+ );+ if (picked == null) return null;+ final now = DateTime.now();+ var at = DateTime(now.year, now.month, now.day, picked.hour, picked.minute);+ if (at.isAfter(now)) at = at.subtract(const Duration(days: 1));+ return at;+}++class _FastingCard extends StatefulWidget {+ const _FastingCard();++ @override+ State<_FastingCard> createState() => _FastingCardState();+}++class _FastingCardState extends State<_FastingCard> {+ Timer? _tick;++ @override+ void initState() {+ super.initState();+ _tick = Timer.periodic(const Duration(seconds: 20), (_) {+ if (mounted && fit.fasting) setState(() {});+ });+ }++ @override+ void dispose() {+ _tick?.cancel();+ super.dispose();+ }++ Future<void> _editStart(BuildContext context) async {+ final at = await _pickFastStart(context, fit.fastStart ?? DateTime.now());+ if (at != null) fit.moveFastStart(at);+ }++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final start = fit.fastStart;+ final goal = Duration(hours: fit.fastGoalHours);+ final now = DateTime.now();+ final elapsed = start == null ? Duration.zero : now.difference(start);+ final progress = start == null ? 0.0 : (elapsed.inSeconds / goal.inSeconds).clamp(0.0, 1.0);+ final reached = start != null && elapsed >= goal;+ final color = reached ? gc.sage : gc.brass;+ final last = fit.fasts.isEmpty ? null : fit.fasts.last;+ final meal = fit.lastMealAt;+ final streak = fit.fastStreak;++ final String big;+ final String line;+ if (start == null) {+ big = '${fit.fastGoalHours}:${24 - fit.fastGoalHours}';+ line = last == null+ ? t.fastIdle+ : [t.fastLast(_span(last.length)), if (streak >= 2) t.fastStreak(streak)].join(' · ');+ } else if (reached) {+ big = _span(elapsed);+ line = t.fastReached(_span(elapsed - goal));+ } else {+ big = _span(goal - elapsed);+ line = t.fastEndsAt(t.clockTime(start.add(goal)));+ }++ return SoftCard(+ radius: 26,+ padding: const EdgeInsets.fromLTRB(16, 14, 14, 14),+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Row(children: [+ Icon(PhosphorIconsRegular.hourglassMedium, size: 16, color: start == null ? gc.textSecondary : color),+ const SizedBox(width: 8),+ Expanded(child: _kicker(gc, t.fastTitle(fit.fastGoalHours, 24 - fit.fastGoalHours).toUpperCase())),+ _roundIcon(PhosphorIconsBold.dotsThree, gc.textSecondary, () => showFastingSheet(context), label: t.fastOptions),+ ]),+ const SizedBox(height: 10),+ Row(children: [+ SizedBox(+ width: 74,+ height: 74,+ child: TweenAnimationBuilder<double>(+ tween: Tween(end: progress),+ duration: const Duration(milliseconds: 600),+ curve: Curves.easeOutCubic,+ builder: (_, v, _) => CustomPaint(+ painter: _FastRing(v, track: gc.bgRaised2, color: color),+ child: Center(+ child: Icon(+ start == null+ ? PhosphorIconsRegular.forkKnife+ : reached+ ? PhosphorIconsBold.check+ : PhosphorIconsRegular.moonStars,+ size: 22,+ color: start == null ? gc.textTertiary : color,+ ),+ ),+ ),+ ),+ ),+ const SizedBox(width: 14),+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(start == null ? t.fastWindowOpen : (reached ? t.fastDoneLabel : t.fastLeft),+ style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textSecondary)),+ const SizedBox(height: 2),+ FitText(big, style: AppTheme.d(26, weight: FontWeight.w800, color: gc.text, height: 1.15)),+ const SizedBox(height: 2),+ Text(line,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.s(12, color: reached ? gc.sage : gc.textSecondary, height: 1.3)),+ ]),+ ),+ ]),+ const SizedBox(height: 14),+ if (start == null)+ Row(children: [+ Expanded(+ child: PrimaryButton(+ label: t.fastStart,+ height: 44,+ onTap: () {+ HapticFeedback.mediumImpact();+ fit.startFast();+ },+ ),+ ),+ if (meal != null && now.difference(meal).inMinutes >= 15) ...[+ const SizedBox(width: 8),+ _Chip(+ label: t.fastFromMeal(t.clockTime(meal)),+ icon: PhosphorIconsBold.clockCounterClockwise,+ onTap: () {+ HapticFeedback.mediumImpact();+ fit.startFast(at: meal);+ },+ ),+ ],+ ])+ else+ Row(children: [+ Expanded(+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () => _editStart(context),+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 10),+ child: Row(children: [+ Flexible(+ child: Text(t.fastSince(t.clockTime(start)),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.textSecondary)),+ ),+ const SizedBox(width: 6),+ Icon(PhosphorIconsRegular.pencilSimple, size: 13, color: gc.textTertiary),+ ]),+ ),+ ),+ ),+ const SizedBox(width: 8),+ SizedBox(+ width: 132,+ child: PrimaryButton(+ label: t.fastEnd,+ height: 44,+ bg: reached ? null : gc.bgRaised2,+ fg: reached ? null : gc.text,+ onTap: () {+ HapticFeedback.mediumImpact();+ fit.endFast();+ },+ ),+ ),+ ]),+ ]),+ );+ }+}++class _FastRing extends CustomPainter {+ _FastRing(this.value, {required this.track, required this.color});+ final double value;+ final Color track;+ final Color color;++ @override+ void paint(Canvas canvas, Size size) {+ const stroke = 7.0;+ final rect = Offset.zero & size;+ final arc = rect.deflate(stroke / 2);+ final base = Paint()+ ..style = PaintingStyle.stroke+ ..strokeWidth = stroke+ ..color = track;+ canvas.drawArc(arc, 0, math.pi * 2, false, base);+ if (value <= 0) return;+ final fill = Paint()+ ..style = PaintingStyle.stroke+ ..strokeWidth = stroke+ ..strokeCap = StrokeCap.round+ ..color = color;+ canvas.drawArc(arc, -math.pi / 2, math.pi * 2 * value, false, fill);+ }++ @override+ bool shouldRepaint(_FastRing old) => old.value != value || old.color != color || old.track != track;+}++Future<void> showFastingSheet(BuildContext context) => _sheet<void>(context, (context) {+ final gc = context.gc;+ return AnimatedBuilder(+ animation: fit,+ builder: (context, _) {+ final week = fit.fastWeek;+ final recent = fit.fasts.reversed.take(10).toList();+ return _sheetFrame(context, [+ SheetTitle(t.fastPlan, subtitle: t.fastPlanHint),+ const SizedBox(height: 16),+ Wrap(alignment: WrapAlignment.center, spacing: 8, runSpacing: 8, children: [+ for (final h in NutritionState.fastPresets)+ _QuickChip(+ label: '$h:${24 - h}',+ selected: fit.fastGoalHours == h,+ onTap: () => fit.setFastGoal(h),+ ),+ ]),+ if (week != null) ...[+ const SizedBox(height: 22),+ Padding(padding: const EdgeInsets.only(left: 4, bottom: 8), child: _kicker(gc, t.fastThisWeek.toUpperCase())),+ Row(children: [+ Expanded(child: _fastStat(gc, t.fastCount, '${week.count}')),+ const SizedBox(width: 8),+ Expanded(child: _fastStat(gc, t.fastReachedCount, '${week.reached}')),+ const SizedBox(width: 8),+ Expanded(child: _fastStat(gc, t.fastAverage, _span(week.avg))),+ ]),+ ],+ if (recent.isNotEmpty) ...[+ const SizedBox(height: 22),+ Padding(padding: const EdgeInsets.only(left: 4, bottom: 8), child: _kicker(gc, t.fastHistory.toUpperCase())),+ for (final r in recent)+ Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: Container(+ padding: const EdgeInsets.fromLTRB(14, 10, 6, 10),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),+ child: Row(children: [+ Icon(r.reached ? PhosphorIconsBold.check : PhosphorIconsRegular.hourglassMedium,+ size: 14, color: r.reached ? gc.sage : gc.textTertiary),+ const SizedBox(width: 10),+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(_span(r.length), style: AppTheme.f(13.5, weight: FontWeight.w700, color: gc.text)),+ Text('${t.shortDate(r.start)} · ${t.clockTime(r.start)} – ${t.clockTime(r.end)}',+ style: AppTheme.s(11.5, color: gc.textSecondary)),+ ]),+ ),+ RoundAction(+ label: t.delete,+ onTap: () => fit.removeFast(r),+ child: Icon(PhosphorIconsRegular.trash, size: 15, color: gc.textTertiary),+ ),+ ]),+ ),+ ),+ ],+ if (fit.fasting) ...[+ const SizedBox(height: 14),+ GhostButton(+ label: t.fastCancel,+ icon: PhosphorIconsRegular.x,+ onTap: () {+ fit.cancelFast();+ Navigator.of(context).pop();+ },+ ),+ ],+ const SizedBox(height: 6),+ ]);+ },+ );+ });++Widget _fastStat(GymColors gc, String label, String value) => Container(+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(14)),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ FitText(label, style: AppTheme.f(10.5, weight: FontWeight.w600, color: gc.textSecondary)),+ const SizedBox(height: 2),+ FitText(value, style: AppTheme.f(16, weight: FontWeight.w800, color: gc.text)),+ ]),+ );diff --git a/lib/screens/nutrition/food.dart b/lib/screens/nutrition/food.dartindex e39b140..5ebafc9 100644--- a/lib/screens/nutrition/food.dart+++ b/lib/screens/nutrition/food.dart@@ -56,6 +56,7 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {final _query = TextEditingController();final _focus = FocusNode();FoodCat? _cat;+ String? _group;bool _dishes = false;@override@@ -78,6 +79,16 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {Future<void> _open(FoodItem f) async =>_closeIf(await showLogFoodSheet(context, f, widget.meal, onPick: widget.onPick));+ Future<void> _create(String name) async {+ if (widget.onPick == null) {+ Navigator.of(context).pop();+ showFoodEditor(context, name: name);+ return;+ }+ final f = await showFoodEditor(context, name: name);+ if (f != null && mounted) await _open(f);+ }+Future<void> _info(FoodItem f) async =>_closeIf(await showFoodInfoSheet(context, f, widget.meal, onPick: widget.onPick));@@ -137,6 +148,7 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {onTap: () => setState(() {_dishes = !_dishes;_cat = null;+ _group = null;}),),const SizedBox(width: 6),@@ -147,6 +159,7 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {setState(() {_cat = _cat == c ? null : c;_dishes = false;+ _group = null;});},scale: 0.93,@@ -175,10 +188,73 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {),const SizedBox(width: 6),],+ for (final g in fit.foodGroups) ...[+ GestureDetector(+ onLongPress: () => _groupMenu(g),+ child: _catChip(+ gc,+ selected: _group == g.id,+ label: g.name,+ art: _groupArt(gc, g),+ onTap: () => setState(() {+ _group = _group == g.id ? null : g.id;+ _cat = null;+ _dishes = false;+ }),+ ),+ ),+ const SizedBox(width: 6),+ ],],),);+ Widget _groupArt(GymColors gc, FoodGroup g) {+ final withPhoto = [for (final f in fit.foodsInGroup(g.id)) if (f.photo.isNotEmpty) f];+ if (withPhoto.isNotEmpty) {+ return FoodSticker(photo: withPhoto.first.photo, name: withPhoto.first.name, size: 46, tilt: false, shadow: false);+ }+ return Text(g.name.characters.first.toUpperCase(),+ style: AppTheme.f(22, weight: FontWeight.w800, color: gc.textSecondary));+ }++ Future<void> _groupMenu(FoodGroup g) async {+ HapticFeedback.mediumImpact();+ final gc = context.gc;+ final action = await showAppSheet<String>(+ context: context,+ backgroundColor: Colors.transparent,+ builder: (sheet) => Container(+ padding: sheetPad(sheet),+ decoration: sheetDecoration(gc),+ child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ const SheetHandle(),+ const SizedBox(height: 16),+ SheetTitle(g.name, subtitle: t.foodGroupCount(fit.foodsInGroup(g.id).length)),+ const SizedBox(height: 14),+ OptionGroup([+ OptionItem(t.measureRename,+ icon: PhosphorIconsRegular.pencilSimple, onTap: () => Navigator.of(sheet).pop('rename')),+ OptionItem(t.delete,+ icon: PhosphorIconsRegular.trash, danger: true, onTap: () => Navigator.of(sheet).pop('delete')),+ ]),+ ]),+ ),+ );+ if (!mounted || action == null) return;+ if (action == 'rename') {+ final name = await askText(context, title: t.measureRename, initial: g.name);+ if (name != null) fit.renameFoodGroup(g.id, name);+ } else {+ final ok = await askConfirm(context,+ title: t.foodGroupDeleteTitle(g.name), body: t.foodGroupDeleteBody, confirmLabel: t.delete, danger: true);+ if (!ok) return;+ if (_group == g.id) _group = null;+ fit.deleteFoodGroup(g.id);+ }+ if (mounted) setState(() {});+ }+Widget _catChip(GymColors gc,{required bool selected, required String label, required Widget art, required VoidCallback onTap}) =>Pressable(@@ -223,12 +299,13 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {final gc = context.gc;final q = _query.text.trim();final picking = widget.onPick != null;- final browsing = q.isNotEmpty || _cat != null || _dishes;- final recipes = _cat != null ? const <Recipe>[] : fit.searchRecipes(q);- final dishes = _cat != null || (q.isEmpty && !_dishes) ? const <Recipe>[] : fit.searchDishes(q);- final mine = _dishes ? const <FoodItem>[] : fit.searchFoods(q, cat: _cat);+ final grouped = _group != null;+ final browsing = q.isNotEmpty || _cat != null || _dishes || grouped;+ final recipes = _cat != null || grouped ? const <Recipe>[] : fit.searchRecipes(q);+ final dishes = _cat != null || grouped || (q.isEmpty && !_dishes) ? const <Recipe>[] : fit.searchDishes(q);+ final mine = _dishes ? const <FoodItem>[] : fit.searchFoods(q, cat: _cat, group: _group);final library = [- if (!_dishes)+ if (!_dishes && !grouped)for (final f in FoodLibrary.search(q, appLanguage, cat: _cat, limit: _cat != null && q.isEmpty ? 200 : 60))f.item(appLanguage),];@@ -246,24 +323,19 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {onChanged: (_) => setState(() {}),),),- if (!picking) ...[- const SizedBox(width: 8),- RoundAction(- label: t.newFood,- size: 48,- onTap: () {- Navigator.of(context).pop();- showFoodEditor(context, name: q);- },- child: Icon(PhosphorIconsRegular.camera, size: 19, color: gc.text),- ),- ],+ const SizedBox(width: 8),+ RoundAction(+ label: t.newFood,+ size: 48,+ onTap: () => _create(q),+ child: Icon(PhosphorIconsBold.plus, size: 19, color: gc.text),+ ),]),const SizedBox(height: 14),_cats(gc),- if (recipes.isNotEmpty || (!picking && _cat == null && q.isEmpty)) ...[+ if (recipes.isNotEmpty || (!picking && _cat == null && !grouped && q.isEmpty)) ...[_section(gc, t.savedMeals),- if (!picking && _cat == null && q.isEmpty)+ if (!picking && _cat == null && !grouped && q.isEmpty)_FoodRow(leading: Container(width: 38,@@ -284,7 +356,11 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {_section(gc, t.readyDishes, trailing: _dishes && q.isEmpty ? '${dishes.length}' : null),for (final r in dishes) _recipeRow(r),],- if (mine.isNotEmpty) ...[_section(gc, t.myFoods), _grid(mine)],+ if (mine.isNotEmpty) ...[+ _section(gc, grouped ? (fit.foodGroupById(_group!)?.name ?? t.myFoods) : t.myFoods,+ trailing: grouped ? '${mine.length}' : null),+ _grid(mine),+ ],if (recents.isNotEmpty) ...[_section(gc, t.recentFoods), _grid(recents, quick: true)],if (library.isNotEmpty) ...[_section(gc, _cat == null ? t.foodDatabase : catName(_cat!), trailing: '${library.length}'),@@ -302,15 +378,12 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {child: Column(children: [Text(t.searchFoodsNone(q),textAlign: TextAlign.center, style: AppTheme.s(13, color: gc.textSecondary, height: 1.45)),- if (!picking && q.isNotEmpty) ...[+ if (q.isNotEmpty) ...[const SizedBox(height: 14),PrimaryButton(label: t.createFoodNamed(q),- height: 50,- onTap: () {- Navigator.of(context).pop();- showFoodEditor(context, name: q);- },+ height: 52,+ onTap: () => _create(q),),],]),@@ -1471,31 +1544,70 @@ class _QuickAddSheetState extends State<_QuickAddSheet> {final _p = TextEditingController();final _c = TextEditingController();final _f = TextEditingController();+ final _amount = TextEditingController();late Meal _meal = widget.meal;+ bool _per100 = false;@overridevoid dispose() {- for (final c in [_name, _kcal, _p, _c, _f]) {+ for (final c in [_name, _kcal, _p, _c, _f, _amount]) {c.dispose();}super.dispose();}+ void _setPer100(bool on) {+ if (on == _per100) return;+ HapticFeedback.selectionClick();+ setState(() => _per100 = on);+ }+@overrideWidget build(BuildContext context) {return _sheetFrame(context, [SheetTitle(t.quickAdd, subtitle: t.quickAddHint),const SizedBox(height: 18),_TextInput(controller: _name, hint: t.quickAddName),- const SizedBox(height: 10),+ const SizedBox(height: 14),+ Row(children: [+ Expanded(+ child: Text(_per100 ? t.per100(_unitOf(false)).toUpperCase() : t.perServing,+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: context.gc.textTertiary, letterSpacing: 1.4)),+ ),+ SegToggle([+ SegOption(t.perServingShort, !_per100, () => _setPer100(false)),+ SegOption('100 ${_unitOf(false)}', _per100, () => _setPer100(true)),+ ], hPad: 11, vPad: 5, fontSize: 11.5),+ ]),+ const SizedBox(height: 8),_MacroInputs(kcal: _kcal, protein: _p, carbs: _c, fat: _f),+ AnimatedSize(+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: _per100+ ? Padding(+ padding: const EdgeInsets.only(top: 8),+ child: _NumberField(+ label: t.quickAddAmount.toUpperCase(),+ controller: _amount,+ color: context.gc.textTertiary,+ suffix: _amtUnit(false)),+ )+ : const SizedBox(width: double.infinity),+ ),const SizedBox(height: 12),_MealPicker(value: _meal, onPick: (m) => setState(() => _meal = m)),const SizedBox(height: 18),PrimaryButton(label: t.logFood,onTap: () {- final e = fit.logQuick(_name.text, _macrosOf(_kcal, _p, _c, _f), meal: _meal);+ var macros = _macrosOf(_kcal, _p, _c, _f);+ if (_per100) {+ final grams = _read(_amount) * (fit.isLb ? _ozOf(false) : 1);+ macros = grams > 0 ? macros * (grams / 100) : Macros.zero;+ }+ final e = fit.logQuick(_name.text, macros, meal: _meal);if (e == null) {HapticFeedback.heavyImpact();return;@@ -1542,7 +1654,7 @@ class _TextInput extends StatelessWidget {}}-Future<void> showFoodEditor(+Future<FoodItem?> showFoodEditor(BuildContext context, {FoodItem? food,FoodItem? from,@@ -1550,7 +1662,7 @@ Future<void> showFoodEditor(bool asShake = false,String name = '',}) =>- _sheet<void>(context, (_) => _FoodEditor(food: food, from: from, meal: meal, asShake: asShake, name: name));+ _sheet<FoodItem?>(context, (_) => _FoodEditor(food: food, from: from, meal: meal, asShake: asShake, name: name));class _PhotoChoice extends StatelessWidget {const _PhotoChoice({@@ -1747,8 +1859,10 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {late final _poly = TextEditingController(text: _seed(_base?.macros.poly ?? 0));late bool _extras = (_base?.macros.hasExtras ?? false) || (_base?.macros.hasFatTypes ?? false);late bool _shake = widget.asShake || (widget.food != null && fit.isShakeFood(widget.food!.id));+ late int _water = _base?.water ?? 0;late double _animalShare = _shareOf(_base?.macros);late FoodCat? _cat = _base?.cat;+ late String _group = widget.food?.group ?? '';bool _per100 = false;late final _p = TextEditingController(text: _seed(_base?.macros.protein ?? 0));late final _c = TextEditingController(text: _seed(_base?.macros.carbs ?? 0));@@ -1792,13 +1906,15 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {cookedYield: _base?.cookedYield ?? 0,macros: _withSource(_keepDetail(_per100 ? typed * (grams / 100) : typed)),cat: _cat,+ water: _water,+ group: _group,);fit.setShakeTag(saved.id, _shake);if (widget.asShake) fit.setShakeFood(saved.id);_dropDrafts(keep: _photo);_photo = widget.food?.photo ?? '';final created = widget.food == null;- Navigator.of(context).pop();+ Navigator.of(context).pop(saved);if (created) HapticFeedback.lightImpact();final meal = widget.meal;if (meal != null) showLogFoodSheet(context, saved, meal);@@ -1832,11 +1948,45 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {fontSize: 12.5,onTap: () {HapticFeedback.selectionClick();- setState(() => _cat = _cat == c ? null : c);+ setState(() {+ _cat = _cat == c ? null : c;+ if (_cat != null) _group = '';+ });+ },+ ),+ const SizedBox(width: 6),+ ],+ for (final g in fit.foodGroups) ...[+ Pill(+ label: g.name,+ bg: _group == g.id ? gc.accentSoft : gc.bgRaised2,+ fg: _group == g.id ? gc.accent : gc.textSecondary,+ fontSize: 12.5,+ onTap: () {+ HapticFeedback.selectionClick();+ setState(() {+ _group = _group == g.id ? '' : g.id;+ if (_group.isNotEmpty) _cat = null;+ });},),const SizedBox(width: 6),],+ Pill(+ label: '+ ${t.foodGroupNew}',+ bg: Colors.transparent,+ fg: gc.textSecondary,+ fontSize: 12.5,+ onTap: () async {+ final name = await askText(context, title: t.foodGroupNew, hint: t.foodGroupHint);+ if (name == null || name.trim().isEmpty || !mounted) return;+ final id = fit.addFoodGroup(name);+ setState(() {+ _group = id;+ _cat = null;+ });+ },+ ),],),);@@ -1967,14 +2117,14 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {),]),const SizedBox(height: 14),- Text(t.foodCategory, style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.1)),+ Text(t.foodCategory, style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),const SizedBox(height: 8),_catPicker(gc),const SizedBox(height: 14),Row(children: [Expanded(child: Text(_per100 ? t.per100(_unitOf(_base?.liquid ?? false)).toUpperCase() : t.perServing,- style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.1)),+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),),SegToggle([SegOption(t.perServingShort, !_per100, () => _setPer100(false)),@@ -1997,7 +2147,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {]),const SizedBox(height: 14),Text(t.fatTypes.toUpperCase(),- style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.1)),+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),const SizedBox(height: 8),Row(children: [Expanded(child: _NumberField(label: t.fatSaturated.toUpperCase(), controller: _sat, color: gc.warn)),@@ -2041,6 +2191,18 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {],const SizedBox(height: 10),_ShakeToggle(on: _shake, onTap: () => setState(() => _shake = !_shake)),+ if (fit.trackerOn(Tracker.water)) ...[+ const SizedBox(height: 10),+ _WaterToggle(+ ml: _water,+ onChanged: (v) => setState(() => _water = v),+ suggest: () {+ final g = double.tryParse(_grams.text.replaceAll(',', '.')) ?? 0;+ final ml = (_base?.liquid ?? false) && g > 0 ? (g * _k).round() : 0;+ return ml > 0 ? ml : (_shake ? 400 : 250);+ },+ ),+ ],const SizedBox(height: 18),PrimaryButton(label: t.save, onTap: _working ? () {} : _save),if (widget.food != null) ...[@@ -2056,6 +2218,87 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {}}+class _WaterToggle extends StatelessWidget {+ const _WaterToggle({required this.ml, required this.onChanged, required this.suggest});++ final int ml;+ final ValueChanged<int> onChanged;+ final int Function() suggest;++ int get _step => fit.isLb ? 30 : 50;++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final on = ml > 0;+ return Semantics(+ toggled: on,+ button: true,+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 180),+ padding: const EdgeInsets.fromLTRB(12, 10, 14, 10),+ decoration: BoxDecoration(+ color: on ? gc.water.withValues(alpha: 0.1) : gc.bgRaised2,+ borderRadius: BorderRadius.circular(18),+ border: Border.all(color: on ? gc.water.withValues(alpha: 0.45) : gc.border),+ ),+ child: Column(children: [+ Pressable(+ onTap: () {+ HapticFeedback.selectionClick();+ onChanged(on ? 0 : suggest());+ },+ scale: 0.98,+ child: Row(children: [+ SizedBox(+ width: 30,+ height: 36,+ child: Icon(PhosphorIconsFill.drop, size: 22, color: on ? gc.water : gc.textTertiary),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(t.countsAsWater, style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),+ const SizedBox(height: 2),+ Text(t.countsAsWaterHint, style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textSecondary)),+ ]),+ ),+ const SizedBox(width: 10),+ TinySwitch(on: on),+ ]),+ ),+ AnimatedSize(+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: on+ ? Padding(+ padding: const EdgeInsets.only(top: 10),+ child: ToolRow(+ label: t.waterPerServing,+ control: StepperControl(+ value: fit.waterLabel(ml),+ minWidth: 86,+ onDec: () => onChanged((ml - _step).clamp(_step, 5000)),+ onInc: () => onChanged((ml + _step).clamp(_step, 5000)),+ onEdit: () async {+ final k = fit.isLb ? 29.5735 : 1.0;+ final v = await askNumber(context,+ title: '${t.waterPerServing} (${fit.isLb ? 'fl oz' : 'ml'})',+ initial: '${(ml / k).round()}', decimal: false);+ if (v != null && v > 0) onChanged((v * k).round().clamp(1, 5000));+ },+ ),+ ),+ )+ : const SizedBox(width: double.infinity),+ ),+ ]),+ ),+ );+ }+}+class _ShakeToggle extends StatelessWidget {const _ShakeToggle({required this.on, required this.onTap});diff --git a/lib/screens/nutrition/meals.dart b/lib/screens/nutrition/meals.dartindex 7314ffd..e6a01fa 100644--- a/lib/screens/nutrition/meals.dart+++ b/lib/screens/nutrition/meals.dart@@ -37,7 +37,7 @@ class _SearchBar extends StatelessWidget {label: t.newFood,size: 52,onTap: () => showFoodEditor(context),- child: Icon(PhosphorIconsRegular.camera, size: 20, color: gc.text),+ child: Icon(PhosphorIconsBold.plus, size: 20, color: gc.text),),]);}@@ -99,7 +99,7 @@ class _Folders extends StatelessWidget {@overrideWidget build(BuildContext context) {final favs = fit.favoriteFoodItems;- final meals = fit.recipes;+ final meals = fit.activeRecipes;return Row(crossAxisAlignment: CrossAxisAlignment.end, children: [Expanded(child: HomeFolder(@@ -190,6 +190,15 @@ Future<void> showFavoritesSheet(BuildContext context) => _sheet<void>(context, (Future<void> showSavedMealsSheet(BuildContext context) => _sheet<void>(context, (context) {final gc = context.gc;+ Widget recipeRow(Recipe r) => _FoodRow(+ leading: FoodPlate(items: _plateOf(r.items), size: 40),+ title: r.name,+ detail: '${_energy(r.total.kcal)} · ${t.recipeItems(r.items.length)}',+ onTap: () async {+ final done = await showRecipeSheet(context, r, fit.defaultMeal);+ if (done == true && context.mounted) Navigator.of(context).pop();+ },+ );return AnimatedBuilder(animation: fit,builder: (context, _) => _sheetFrame(context, [@@ -209,16 +218,39 @@ Future<void> showSavedMealsSheet(BuildContext context) => _sheet<void>(context,showDishEditor(context, meal: fit.defaultMeal);},),- for (final r in fit.recipes)- _FoodRow(- leading: FoodPlate(items: _plateOf(r.items), size: 40),- title: r.name,- detail: '${_energy(r.total.kcal)} · ${t.recipeItems(r.items.length)}',- onTap: () async {- final done = await showRecipeSheet(context, r, fit.defaultMeal);- if (done == true && context.mounted) Navigator.of(context).pop();+ for (final r in fit.activeRecipes) recipeRow(r),+ if (fit.archivedRecipes.isNotEmpty) ...[+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.selectionClick();+ fit.toggleArchivedRecipes();},+ child: Padding(+ padding: const EdgeInsets.fromLTRB(4, 14, 4, 10),+ child: Row(children: [+ Expanded(child: SectionLabel('${t.archivedFilter} · ${fit.archivedRecipes.length}')),+ AnimatedRotation(+ turns: fit.showArchivedRecipes ? 0.5 : 0,+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ child: Icon(PhosphorIconsBold.caretDown, size: 13, color: gc.textTertiary),+ ),+ ]),+ ),+ ),+ AnimatedSize(+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: fit.showArchivedRecipes+ ? Opacity(+ opacity: 0.6,+ child: Column(children: [for (final r in fit.archivedRecipeList) recipeRow(r)]),+ )+ : const SizedBox(width: double.infinity),),+ ],if (fit.recipes.isEmpty) ...[const SizedBox(height: 10),Text(t.savedMealsEmpty,@@ -352,7 +384,7 @@ class _MealTabsState extends State<_MealTabs> {),const SizedBox(height: 14),SoftCard(- radius: 28,+ radius: 26,padding: const EdgeInsets.fromLTRB(16, 16, 12, 16),child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [Row(children: [@@ -418,7 +450,7 @@ class _MealTabsState extends State<_MealTabs> {Expanded(child: PrimaryButton(label: t.addToMeal(mealInSentence(meal)),- height: 50,+ height: 52,onTap: () => showAddFoodSheet(context, meal),),),@@ -740,6 +772,23 @@ class _RecipeSheetState extends State<_RecipeSheet> {},child: Text(t.dishEdit, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.textSecondary)),),+ TextButton(+ onPressed: () {+ final on = !fit.isRecipeArchived(r.id);+ fit.setRecipeArchived(r.id, on);+ Navigator.of(context).pop();+ if (on) {+ showNotchToast(context, t.dishArchivedToast,+ subtitle: r.name,+ icon: PhosphorIconsFill.archive,+ accent: gc.textSecondary,+ action: t.undo,+ onTap: () => fit.setRecipeArchived(r.id, false));+ }+ },+ child: Text(fit.isRecipeArchived(r.id) ? t.dishUnarchive : t.dishArchive,+ style: AppTheme.f(13, weight: FontWeight.w700, color: gc.textSecondary)),+ ),TextButton(onPressed: _delete,child: Text(t.delete, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.danger)),@@ -1035,10 +1084,7 @@ class _DishEditorState extends State<_DishEditor> {child: Container(height: media.size.height * 0.88,padding: EdgeInsets.fromLTRB(20, 12, 20, 14 + media.padding.bottom),- decoration: BoxDecoration(- color: gc.bgRaised,- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),- ),+ decoration: sheetDecoration(gc),child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [const SheetHandle(),const SizedBox(height: 10),diff --git a/lib/screens/nutrition/plans.dart b/lib/screens/nutrition/plans.dartindex 9d1bdce..7543e0f 100644--- a/lib/screens/nutrition/plans.dart+++ b/lib/screens/nutrition/plans.dart@@ -60,7 +60,7 @@ class _PlansSection extends StatelessWidget {onTap: () => showNewPlanSheet(context),scale: 0.97,child: SoftCard(- radius: 24,+ radius: 22,padding: const EdgeInsets.fromLTRB(16, 16, 16, 16),child: Row(children: [Container(@@ -456,10 +456,7 @@ class _PlanEditorState extends State<_PlanEditor> {child: Container(height: media.size.height * 0.92,padding: EdgeInsets.fromLTRB(20, 12, 20, 14 + media.padding.bottom),- decoration: BoxDecoration(- color: gc.bgRaised,- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),- ),+ decoration: sheetDecoration(gc),child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [const SheetHandle(),const SizedBox(height: 10),diff --git a/lib/screens/nutrition/prep.dart b/lib/screens/nutrition/prep.dartindex 0a6888d..310a5cd 100644--- a/lib/screens/nutrition/prep.dart+++ b/lib/screens/nutrition/prep.dart@@ -242,6 +242,7 @@ class _BatchLogSheet extends StatefulWidget {class _BatchLogSheetState extends State<_BatchLogSheet> {late Meal _meal = widget.meal;+ late DateTime _day = fit.nutritionDay;int _mode = 0;double _share = 0.25;double _grams = 300;@@ -353,11 +354,13 @@ class _BatchLogSheetState extends State<_BatchLogSheet> {),const SizedBox(height: 12),_MealPicker(value: _meal, onPick: (m) => setState(() => _meal = m)),+ const SizedBox(height: 10),+ _DayStrip(value: _day, onPick: (d) => setState(() => _day = d)),const SizedBox(height: 18),PrimaryButton(label: t.prepLogAmount(_amount(_take, false)),onTap: () {- final e = fit.logFromBatch(b, _take, meal: _meal);+ final e = fit.logFromBatch(b, _take, meal: _meal, day: _day);if (e == null) {HapticFeedback.heavyImpact();return;@@ -384,3 +387,58 @@ class _BatchLogSheetState extends State<_BatchLogSheet> {]);}}++class _DayStrip extends StatelessWidget {+ const _DayStrip({required this.value, required this.onPick});++ final DateTime value;+ final ValueChanged<DateTime> onPick;++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final now = DateTime.now();+ final today = DateTime(now.year, now.month, now.day);+ final days = [+ if (value.isBefore(today)) value,+ for (var i = 0; i < 7; i++) shiftDays(today, i),+ ];+ String label(DateTime d) {+ if (d == today) return t.nutritionToday;+ if (d == shiftDays(today, 1)) return t.tomorrow;+ if (d == shiftDays(today, -1)) return t.nutritionYesterday;+ return t.weekdayShort(d.weekday);+ }++ return SingleChildScrollView(+ scrollDirection: Axis.horizontal,+ clipBehavior: Clip.none,+ child: Row(children: [+ for (final d in days)+ Pressable(+ onTap: () {+ HapticFeedback.selectionClick();+ onPick(d);+ },+ scale: 0.94,+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 180),+ margin: const EdgeInsets.symmetric(horizontal: 3),+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),+ decoration: BoxDecoration(+ color: d == value ? gc.accentSoft : gc.bgRaised2,+ borderRadius: BorderRadius.circular(14),+ border: Border.all(color: d == value ? gc.accent.withValues(alpha: 0.6) : Colors.transparent),+ ),+ child: Column(children: [+ Text(label(d),+ style: AppTheme.f(12, weight: FontWeight.w800, color: d == value ? gc.accent : gc.text)),+ Text('${d.day}',+ style: AppTheme.f(10, weight: FontWeight.w600, color: gc.textTertiary)),+ ]),+ ),+ ),+ ]),+ );+ }+}diff --git a/lib/screens/nutrition/settings.dart b/lib/screens/nutrition/settings.dartindex 2ce5b04..eeb3098 100644--- a/lib/screens/nutrition/settings.dart+++ b/lib/screens/nutrition/settings.dart@@ -36,29 +36,30 @@ Future<void> showTrackersSheet(BuildContext context) => _sheet<void>(context, (cSheetTitle(t.trackersTitle, subtitle: t.trackersHint),label(t.trackersDaily),ToolGroup([- toggle(Tracker.calories, PhosphorIconsFill.fire, gc.warn, sentenceCase(t.kcalLabel)),- toggle(Tracker.protein, PhosphorIconsFill.egg, gc.protein, sentenceCase(t.macroProtein)),- toggle(Tracker.carbs, PhosphorIconsFill.grains, gc.carbs, sentenceCase(t.macroCarbs)),- toggle(Tracker.fat, PhosphorIconsFill.drop, gc.fat, sentenceCase(t.macroFat)),+ toggle(Tracker.calories, PhosphorIconsRegular.fire, gc.warn, sentenceCase(t.kcalLabel)),+ toggle(Tracker.protein, PhosphorIconsRegular.egg, gc.protein, sentenceCase(t.macroProtein)),+ toggle(Tracker.carbs, PhosphorIconsRegular.grains, gc.carbs, sentenceCase(t.macroCarbs)),+ toggle(Tracker.fat, PhosphorIconsRegular.drop, gc.fat, sentenceCase(t.macroFat)),]),label(t.trackersDetail),ToolGroup([- toggle(Tracker.animal, PhosphorIconsFill.lightning, gc.warn, t.animalProtein),- toggle(Tracker.quality, PhosphorIconsFill.dna, gc.sage, t.proteinQuality),- toggle(Tracker.fats, PhosphorIconsFill.drop, gc.fat, t.fatTypes),- toggle(Tracker.fiber, PhosphorIconsFill.leaf, gc.sage, t.fiberLabel),- toggle(Tracker.sugarSodium, PhosphorIconsFill.cube, gc.carbs, t.sugarSodium),+ toggle(Tracker.animal, PhosphorIconsRegular.lightning, gc.warn, t.animalProtein),+ toggle(Tracker.quality, PhosphorIconsRegular.dna, gc.sage, t.proteinQuality),+ toggle(Tracker.fats, PhosphorIconsRegular.drop, gc.fat, t.fatTypes),+ toggle(Tracker.fiber, PhosphorIconsRegular.leaf, gc.sage, t.fiberLabel),+ toggle(Tracker.sugarSodium, PhosphorIconsRegular.cube, gc.carbs, t.sugarSodium),]),label(t.trackersCards),ToolGroup([- toggle(Tracker.water, PhosphorIconsFill.drop, gc.water, t.waterLabel),- toggle(Tracker.shake, PhosphorIconsFill.egg, gc.protein, t.shakeCard),- toggle(Tracker.supplements, PhosphorIconsFill.pill, gc.sage, t.supplementsLabel),- toggle(Tracker.weight, PhosphorIconsFill.scales, gc.water, t.bodyweightLabel),- toggle(Tracker.week, PhosphorIconsFill.chartLineUp, gc.sage, t.weekAverage),- toggle(Tracker.prep, PhosphorIconsFill.cookingPot, gc.warn, t.prepTitle),- toggle(Tracker.plans, PhosphorIconsFill.calendarBlank, gc.accent, t.mealPlansTitle),- toggle(Tracker.foods, PhosphorIconsFill.bookmarkSimple, gc.accent, t.myFoods),+ toggle(Tracker.water, PhosphorIconsRegular.drop, gc.water, t.waterLabel),+ toggle(Tracker.shake, PhosphorIconsRegular.egg, gc.protein, t.shakeCard),+ toggle(Tracker.supplements, PhosphorIconsRegular.pill, gc.sage, t.supplementsLabel),+ toggle(Tracker.fasting, PhosphorIconsRegular.hourglassMedium, gc.brass, t.fastTracker),+ toggle(Tracker.weight, PhosphorIconsRegular.scales, gc.water, t.bodyweightLabel),+ toggle(Tracker.week, PhosphorIconsRegular.chartLineUp, gc.sage, t.weekAverage),+ toggle(Tracker.prep, PhosphorIconsRegular.cookingPot, gc.warn, t.prepTitle),+ toggle(Tracker.plans, PhosphorIconsRegular.calendarBlank, gc.accent, t.mealPlansTitle),+ toggle(Tracker.foods, PhosphorIconsRegular.bookmarkSimple, gc.accent, t.myFoods),]),label(t.trackersScreen),ToolGroup([@@ -349,10 +350,10 @@ Future<void> showNutritionAbout(BuildContext context) => _sheet<void>(context, (return _sheetFrame(sheet, [SheetTitle(t.nutritionAboutTitle, subtitle: t.nutritionAboutSub),const SizedBox(height: 4),- point(PhosphorIconsFill.barbell, gc.accent, t.nutritionAboutWhatTitle, t.nutritionAboutWhat),- point(PhosphorIconsFill.shieldCheck, gc.sage, t.nutritionAboutScanTitle, t.nutritionAboutScan),- point(PhosphorIconsFill.deviceMobile, gc.protein, t.nutritionAboutLocalTitle, t.nutritionAboutLocal),- point(PhosphorIconsFill.flask, gc.warn, t.nutritionAboutBetaTitle, t.nutritionAboutBeta),+ point(PhosphorIconsRegular.barbell, gc.accent, t.nutritionAboutWhatTitle, t.nutritionAboutWhat),+ point(PhosphorIconsRegular.shieldCheck, gc.sage, t.nutritionAboutScanTitle, t.nutritionAboutScan),+ point(PhosphorIconsRegular.deviceMobile, gc.protein, t.nutritionAboutLocalTitle, t.nutritionAboutLocal),+ point(PhosphorIconsRegular.flask, gc.warn, t.nutritionAboutBetaTitle, t.nutritionAboutBeta),const SizedBox(height: 24),PrimaryButton(label: t.nutritionAboutOk, onTap: () => Navigator.of(sheet).pop()),const SizedBox(height: 10),diff --git a/lib/screens/nutrition_screen.dart b/lib/screens/nutrition_screen.dartindex f5fcfd3..a04df54 100644--- a/lib/screens/nutrition_screen.dart+++ b/lib/screens/nutrition_screen.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:io';import 'dart:math' as math;@@ -38,6 +39,7 @@ part 'nutrition/settings.dart';part 'nutrition/meals.dart';part 'nutrition/food.dart';part 'nutrition/plans.dart';+part 'nutrition/fasting.dart';String mealInSentence(Meal m) {final name = mealName(m);@@ -157,6 +159,7 @@ class _NutritionScreenState extends State<NutritionScreen> {final gc = context.gc;bool on(Tracker x) => fit.trackerOn(x);final cards = <Widget>[+ if (on(Tracker.fasting) && fit.nutritionOnToday) _FastingCard(),if (on(Tracker.water) || on(Tracker.shake))_pair(on(Tracker.water) ? _WaterTile() : null, on(Tracker.shake) ? _ShakeTile() : null),if (on(Tracker.supplements)) _SupplementsCard(),@@ -311,7 +314,7 @@ List<(String, String)> _plateOf(Iterable<FoodEntry> items) => [];Widget _kicker(GymColors gc, String text) =>- Text(text, style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.1));+ Text(text, style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4));class _WeekStrip extends StatelessWidget {const _WeekStrip();@@ -406,10 +409,7 @@ Widget _sheetFrame(BuildContext context, List<Widget> children, {double heightFaconstraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.88),height: heightFactor > 0 ? MediaQuery.of(context).size.height * heightFactor : null,padding: sheetPad(context, bottom: 18),- decoration: BoxDecoration(- color: fit.dark ? Color.lerp(gc.bg, gc.bgRaised, 0.55) : gc.bg,- borderRadius: const BorderRadius.vertical(top: Radius.circular(32)),- ),+ decoration: sheetDecoration(gc),child: SingleChildScrollView(child: Column(mainAxisSize: MainAxisSize.min,@@ -429,10 +429,7 @@ Widget _sheetSlivers(BuildContext context, List<Widget> slivers, {double heightFconstraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.88),height: heightFactor > 0 ? MediaQuery.of(context).size.height * heightFactor : null,padding: sheetPad(context, bottom: 18),- decoration: BoxDecoration(- color: gc.bgRaised,- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),- ),+ decoration: sheetDecoration(gc),child: CustomScrollView(shrinkWrap: heightFactor <= 0,slivers: [@@ -483,10 +480,20 @@ Widget _macroSummary(BuildContext context, Macros m) {void _loggedToast(BuildContext context, FoodEntry e) {HapticFeedback.lightImpact();+ final day = DateTime(e.at.year, e.at.month, e.at.day);+ final now = DateTime.now();+ final today = DateTime(now.year, now.month, now.day);+ final when = day == fit.nutritionDay+ ? null+ : day == shiftDays(today, 1)+ ? t.tomorrow+ : day == today+ ? t.nutritionToday+ : t.longDate(day);showNotchToast(context,t.loggedToast(mealInSentence(e.meal)),- subtitle: e.name.isEmpty ? null : e.name,+ subtitle: e.name.isEmpty && when == null ? null : [if (e.name.isNotEmpty) e.name, ?when].join(' · '),icon: PhosphorIconsFill.forkKnife,accent: context.gc.accent,action: t.undo,diff --git a/lib/state/nutrition_state.dart b/lib/state/nutrition_state.dartindex 1bb3ac9..1794163 100644--- a/lib/state/nutrition_state.dart+++ b/lib/state/nutrition_state.dart@@ -6,6 +6,8 @@ mixin NutritionState on FitCore, ToolsState, StatsState {final List<WaterSip> waterLog = [];final List<Supplement> supplements = [];final List<Recipe> recipes = [];+ final Set<String> archivedRecipes = {};+ bool showArchivedRecipes = false;final List<Batch> batches = [];final List<String> favoriteFoods = [];final List<MealPlan> mealPlans = [];@@ -145,6 +147,58 @@ mixin NutritionState on FitCore, ToolsState, StatsState {String get energyUnit => useKj ? 'kJ' : 'kcal';+ String weightAim = '';++ void setWeightAim(String aim) {+ weightAim = const {'lose', 'gain', 'hold'}.contains(aim) ? aim : '';+ _persist();+ notifyListeners();+ }++ String get effectiveWeightAim {+ if (weightAim.isNotEmpty) return weightAim;+ final kg = latestBodyweight?.kg ?? 0;+ if (weightGoalKg <= 0 || kg <= 0) return '';+ final gap = weightGoalKg - kg;+ if (gap.abs() < kg * 0.01) return 'hold';+ return gap < 0 ? 'lose' : 'gain';+ }++ static const paceCorridors = {'lose': (-1.0, -0.5), 'gain': (0.25, 0.5), 'hold': (-0.25, 0.25)};++ ({double kgPerWeek, double pctPerWeek})? get weightPace {+ final now = DateTime.now();+ final from = now.subtract(const Duration(days: 21));+ final pts = [for (final b in bodyweight) if (!b.date.isBefore(from)) b]+ ..sort((a, b) => a.date.compareTo(b.date));+ if (pts.length < 3 || pts.last.date.difference(pts.first.date).inDays < 7) return null;+ final xs = [for (final p in pts) p.date.difference(pts.first.date).inMinutes / 1440];+ final ys = [for (final p in pts) p.kg];+ final mx = xs.reduce((a, b) => a + b) / xs.length;+ final my = ys.reduce((a, b) => a + b) / ys.length;+ var num = 0.0, den = 0.0;+ for (var i = 0; i < xs.length; i++) {+ num += (xs[i] - mx) * (ys[i] - my);+ den += (xs[i] - mx) * (xs[i] - mx);+ }+ if (den <= 0 || my <= 0) return null;+ final perWeek = num / den * 7;+ return (kgPerWeek: perWeek, pctPerWeek: perWeek / my * 100);+ }++ String? get weightPaceStatus {+ final pace = weightPace;+ final band = paceCorridors[effectiveWeightAim];+ if (pace == null || band == null) return null;+ final p = pace.pctPerWeek;+ final (lo, hi) = band;+ if (p >= lo && p <= hi) return 'onPace';+ if (effectiveWeightAim == 'hold') return 'drifting';+ final towards = effectiveWeightAim == 'lose' ? p < 0 : p > 0;+ if (!towards) return 'wrongWay';+ return p.abs() > (effectiveWeightAim == 'lose' ? -lo : hi) ? 'tooFast' : 'tooSlow';+ }+void setWeightGoal(double kg) {weightGoalKg = kg > 0 ? _round3(kg) : 0;_persist();@@ -247,7 +301,17 @@ mixin NutritionState on FitCore, ToolsState, StatsState {return grams >= 1 ? grams : null;}- int waterOn(DateTime day) {+ int waterOn(DateTime day) => sipsOn(day) + waterFromFoodOn(day);++ int waterFromFoodOn(DateTime day) {+ var ml = 0;+ for (final e in entriesOn(day)) {+ ml += e.waterMl;+ }+ return ml;+ }++ int sipsOn(DateTime day) {var index = _waterByDay;if (index == null || _waterByDayLen != waterLog.length) {index = <DateTime, int>{};@@ -294,6 +358,7 @@ mixin NutritionState on FitCore, ToolsState, StatsState {} else {trackers.remove(t);}+ if (t == Tracker.fasting) _syncFast();_persist();notifyListeners();}@@ -372,6 +437,7 @@ mixin NutritionState on FitCore, ToolsState, StatsState {liquid: food.liquid,cooked: cooked && food.canCook ? food.cookedYield : 0,per: food.macros,+ water: food.water,);FoodEntry logFood(FoodItem food, {double servings = 1, Meal? meal, bool cooked = false}) {@@ -496,14 +562,18 @@ mixin NutritionState on FitCore, ToolsState, StatsState {return b;}- FoodEntry? logFromBatch(Batch batch, double grams, {Meal? meal}) {+ FoodEntry? logFromBatch(Batch batch, double grams, {Meal? meal, DateTime? day}) {final b = batchById(batch.id);if (b == null || grams <= 0 || b.totalGrams <= 0) return null;final take = math.min(grams, b.leftGrams);if (take <= 0) return null;+ final today = _dayKey(DateTime.now());+ var on = _dayKey(day ?? nutritionDay);+ final last = shiftDays(today, kNutritionDaysAhead);+ if (on.isAfter(last)) on = last;final e = FoodEntry(id: _newId('e'),- at: _stampFor(nutritionDay),+ at: _stampFor(on),meal: meal ?? defaultMeal,name: b.name,foodId: b.id,@@ -604,11 +674,11 @@ mixin NutritionState on FitCore, ToolsState, StatsState {String waterLabel(int ml) {if (isLb) return '${(ml / 29.5735).round()} fl oz';- if (ml >= 1000) return '${fmt((ml / 100).round() / 10)} L';+ if (ml >= 1000) return '${fmt((ml / 10).round() / 100)} L';return '$ml ml';}- String waterValue(int ml) => isLb ? '${(ml / 29.5735).round()}' : fmt((ml / 100).round() / 10);+ String waterValue(int ml) => isLb ? '${(ml / 29.5735).round()}' : fmt((ml / 10).round() / 100);String get waterUnit => isLb ? 'fl oz' : 'L';@@ -654,19 +724,65 @@ mixin NutritionState on FitCore, ToolsState, StatsState {List<Recipe> searchRecipes(String query) {final q = foldText(query.trim());return [- for (final r in recipes)+ for (final r in activeRecipes)if (q.isEmpty || foldText(r.name).contains(q)) r,];}- List<FoodItem> searchFoods(String query, {FoodCat? cat}) {+ List<FoodItem> searchFoods(String query, {FoodCat? cat, String? group}) {final q = foldText(query.trim());return [for (final f in foodsByUse)- if ((q.isEmpty || foldText(f.name).contains(q)) && (cat == null || f.cat == cat)) f,+ if ((q.isEmpty || foldText(f.name).contains(q)) &&+ (cat == null || f.cat == cat) &&+ (group == null || f.group == group))+ f,];}+ final List<FoodGroup> foodGroups = [];++ FoodGroup? foodGroupById(String id) {+ for (final g in foodGroups) {+ if (g.id == id) return g;+ }+ return null;+ }++ List<FoodItem> foodsInGroup(String id) => [for (final f in foodsByUse) if (f.group == id) f];++ String addFoodGroup(String name) {+ final clean = name.trim();+ if (clean.isEmpty) return '';+ for (final g in foodGroups) {+ if (foldText(g.name) == foldText(clean)) return g.id;+ }+ final g = FoodGroup(_newId('g'), clean.length > 30 ? clean.substring(0, 30) : clean);+ foodGroups.add(g);+ _persist();+ notifyListeners();+ return g.id;+ }++ void renameFoodGroup(String id, String name) {+ final g = foodGroupById(id);+ final clean = name.trim();+ if (g == null || clean.isEmpty) return;+ g.name = clean.length > 30 ? clean.substring(0, 30) : clean;+ _persist();+ notifyListeners();+ }++ void deleteFoodGroup(String id) {+ foodGroups.removeWhere((g) => g.id == id);+ for (var i = 0; i < foods.length; i++) {+ if (foods[i].group == id) foods[i] = foods[i].copyWith(group: '');+ }+ _dropCaches();+ _persist();+ notifyListeners();+ }+List<FoodItem> get recentLibraryFoods {_cacheStale();return _recent ??= _computeRecent();@@ -706,7 +822,26 @@ mixin NutritionState on FitCore, ToolsState, StatsState {notifyListeners();}+ List<Recipe> get activeRecipes => [for (final r in recipes) if (!archivedRecipes.contains(r.id)) r];++ List<Recipe> get archivedRecipeList => [for (final r in recipes) if (archivedRecipes.contains(r.id)) r];++ bool isRecipeArchived(String id) => archivedRecipes.contains(id);++ void setRecipeArchived(String id, bool on) {+ if (on ? !archivedRecipes.add(id) : !archivedRecipes.remove(id)) return;+ if (archivedRecipes.isEmpty) showArchivedRecipes = false;+ _persist();+ notifyListeners();+ }++ void toggleArchivedRecipes() {+ showArchivedRecipes = !showArchivedRecipes;+ notifyListeners();+ }+void deleteRecipe(String id) {+ archivedRecipes.remove(id);recipes.removeWhere((r) => r.id == id);_persist();notifyListeners();@@ -933,6 +1068,7 @@ mixin NutritionState on FitCore, ToolsState, StatsState {liquid: e.liquid,cooked: e.cooked,per: e.per,+ water: e.water,));}final name = (p['n'] as String? ?? '').trim();@@ -1087,8 +1223,11 @@ mixin NutritionState on FitCore, ToolsState, StatsState {double cookedYield = 0,Macros macros = Macros.zero,FoodCat? cat,+ int water = 0,+ String group = '',}) {final clean = name.trim();+ final groupId = foodGroupById(group) == null ? '' : group;final i = id == null ? -1 : foods.indexWhere((f) => f.id == id);if (i >= 0) {final old = foods[i];@@ -1101,7 +1240,9 @@ mixin NutritionState on FitCore, ToolsState, StatsState {liquid: liquid,macros: macros,cookedYield: cookedYield,- cat: () => cat);+ cat: () => cat,+ water: water.clamp(0, 5000),+ group: groupId);_persist();notifyListeners();return foods[i];@@ -1116,6 +1257,8 @@ mixin NutritionState on FitCore, ToolsState, StatsState {cookedYield: cookedYield,macros: macros,cat: cat,+ water: water.clamp(0, 5000),+ group: groupId,);foods.add(food);_persist();@@ -1336,6 +1479,7 @@ mixin NutritionState on FitCore, ToolsState, StatsState {void setNutritionBeta(bool on) {nutritionBeta = on;syncSupplementReminder();+ _syncFast();_persist();notifyListeners();}@@ -1350,6 +1494,111 @@ mixin NutritionState on FitCore, ToolsState, StatsState {void backFromNutrition() => popRoute();+ static const fastPresets = [12, 14, 16, 18, 20, 23];+ int fastGoalHours = 16;+ DateTime? fastStart;+ final List<FastRecord> fasts = [];++ bool get fasting => fastStart != null;++ DateTime? get fastEndsAt => fastStart?.add(Duration(hours: fastGoalHours));++ DateTime? get lastMealAt {+ final now = DateTime.now();+ final since = now.subtract(const Duration(hours: 24));+ DateTime? last;+ for (final e in foodLog) {+ if (e.at.isAfter(now) || e.at.isBefore(since) || e.at.hour == 12 && e.at.minute == 0 && e.at.second == 0) continue;+ if (last == null || e.at.isAfter(last)) last = e.at;+ }+ return last;+ }++ void startFast({DateTime? at}) {+ final now = DateTime.now();+ var start = at ?? now;+ if (start.isAfter(now)) start = now;+ final floor = now.subtract(const Duration(hours: 48));+ if (start.isBefore(floor)) start = floor;+ fastStart = start;+ _syncFast();+ _persist();+ notifyListeners();+ }++ void moveFastStart(DateTime at) {+ if (fastStart == null) return;+ startFast(at: at);+ }++ void endFast() {+ final start = fastStart;+ if (start == null) return;+ final end = DateTime.now();+ if (end.difference(start).inMinutes >= 10) {+ fasts.add(FastRecord(start, end, fastGoalHours));+ fasts.sort((a, b) => a.start.compareTo(b.start));+ if (fasts.length > 200) fasts.removeRange(0, fasts.length - 200);+ }+ fastStart = null;+ _syncFast();+ _persist();+ notifyListeners();+ }++ void cancelFast() {+ if (fastStart == null) return;+ fastStart = null;+ _syncFast();+ _persist();+ notifyListeners();+ }++ void removeFast(FastRecord r) {+ if (!fasts.remove(r)) return;+ _persist();+ notifyListeners();+ }++ void setFastGoal(int hours) {+ final h = hours.clamp(1, 72);+ if (h == fastGoalHours) return;+ fastGoalHours = h;+ _syncFast();+ _persist();+ notifyListeners();+ }++ int get fastStreak {+ var n = 0;+ for (final r in fasts.reversed) {+ if (!r.reached) break;+ n++;+ }+ return n;+ }++ ({int count, int reached, Duration avg})? get fastWeek {+ final since = DateTime.now().subtract(const Duration(days: 7));+ final recent = [for (final r in fasts) if (r.end.isAfter(since)) r];+ if (recent.isEmpty) return null;+ final total = recent.fold(Duration.zero, (a, r) => a + r.length);+ return (+ count: recent.length,+ reached: recent.where((r) => r.reached).length,+ avg: Duration(minutes: total.inMinutes ~/ recent.length),+ );+ }++ void _syncFast() {+ final start = fastStart, end = fastEndsAt;+ if (!nutritionBeta || !trackerOn(Tracker.fasting) || start == null || end == null) {+ ProgressReminder.instance.cancelFast();+ } else {+ ProgressReminder.instance.showFast(start, end);+ }+ }+Map<String, dynamic> nutritionJson() => {'foods': foods.map((f) => f.toJson()).toList(),'log': _stored('log', foodLog, (e) => e.toJson()),@@ -1364,8 +1613,10 @@ mixin NutritionState on FitCore, ToolsState, StatsState {if (useKj) 'kj': true,if (!vesselMotion) 'still': true,if (weightGoalKg > 0) 'wGoal': weightGoalKg,+ if (weightAim.isNotEmpty) 'wAim': weightAim,'suppAt': ?supplementReminderMin,if (recipes.isNotEmpty) 'recipes': recipes.map((r) => r.toJson()).toList(),+ if (archivedRecipes.isNotEmpty) 'recArch': archivedRecipes.toList(),if (favoriteFoods.isNotEmpty) 'fav': favoriteFoods,if (batches.isNotEmpty) 'batches': batches.map((b) => b.toJson()).toList(),'meals': mealSlots.map((m) => m.toJson()).toList(),@@ -1375,6 +1626,13 @@ mixin NutritionState on FitCore, ToolsState, StatsState {'trackers': [for (final t in Tracker.values) if (trackers.contains(t)) t.name],if (shakeFoodId.isNotEmpty) 'shake': shakeFoodId,'shakes': shakeFoods,+ if (foodGroups.isNotEmpty) 'groups': foodGroups.map((g) => g.toJson()).toList(),+ if (fastGoalHours != 16 || fastStart != null || fasts.isNotEmpty)+ 'fast': {+ 'h': fastGoalHours,+ if (fastStart != null) 'on': fastStart!.toIso8601String(),+ if (fasts.isNotEmpty) 'log': fasts.map((r) => r.toJson()).toList(),+ },};void loadNutrition(Map<String, dynamic>? j, {Map<String, String>? restored}) {@@ -1383,6 +1641,9 @@ mixin NutritionState on FitCore, ToolsState, StatsState {for (final e in (j?[k] as List?) ?? const [])if (e is Map) e.cast<String, dynamic>(),];+ foodGroups+ ..clear()+ ..addAll(list('groups').map(FoodGroup.fromJson).nonNulls);foods..clear()..addAll(list('foods').map(FoodItem.fromJson).where((f) => f.id.isNotEmpty).map((f) {@@ -1423,9 +1684,15 @@ mixin NutritionState on FitCore, ToolsState, StatsState {supplementReminderMin = suppAt?.clamp(0, 24 * 60 - 1);final wGoal = (j?['wGoal'] as num?)?.toDouble() ?? 0;weightGoalKg = wGoal.isFinite && wGoal > 0 && wGoal < 500 ? wGoal : 0;+ final aim = j?['wAim'];+ weightAim = const {'lose', 'gain', 'hold'}.contains(aim) ? aim as String : '';recipes..clear()..addAll(list('recipes').map(Recipe.fromJson).where((r) => r.id.isNotEmpty && r.items.isNotEmpty));+ archivedRecipes+ ..clear()+ ..addAll([for (final id in (j?['recArch'] as List?) ?? const []) if (id is String && recipes.any((r) => r.id == id)) id]);+ showArchivedRecipes = false;batches..clear()..addAll(list('batches').map(Batch.fromJson).nonNulls);@@ -1470,8 +1737,21 @@ mixin NutritionState on FitCore, ToolsState, StatsState {? {...tagged.whereType<String>().where((id) => foods.any((f) => f.id == id))}: [if (shakeFoodId.isNotEmpty) shakeFoodId]);if (!shakeFoods.contains(shakeFoodId)) shakeFoodId = shakeFoods.isEmpty ? '' : shakeFoods.first;+ final fast = j?['fast'];+ final fastMap = fast is Map ? fast.cast<String, dynamic>() : const <String, dynamic>{};+ fastGoalHours = ((fastMap['h'] as num?)?.toInt() ?? 16).clamp(1, 72);+ final on = DateTime.tryParse(fastMap['on'] as String? ?? '');+ fastStart = on != null && !on.isAfter(DateTime.now()) ? on : null;+ fasts+ ..clear()+ ..addAll([+ for (final e in (fastMap['log'] as List?) ?? const [])+ if (e is Map) FastRecord.fromJson(e.cast<String, dynamic>()),+ ].nonNulls)+ ..sort((a, b) => a.start.compareTo(b.start));nutritionDay = _dayKey(DateTime.now());_nutritionSetOn = nutritionDay;syncSupplementReminder();+ _syncFast();}}diff --git a/test/nutrition_test.dart b/test/nutrition_test.dartindex e4ebfcd..1b2115e 100644--- a/test/nutrition_test.dart+++ b/test/nutrition_test.dart@@ -86,6 +86,29 @@ void main() {expect(fit.waterOn(DateTime.now()), fit.activeGoals.glassMl);});+ test('#298 un batido con agua suma al agua del día y se va al quitarlo', () {+ final shake = fit.saveFood(name: 'Whey con agua', serving: '1 batido', macros: whey, water: 500);+ expect(FoodItem.fromJson(shake.toJson()).water, 500);+ final e = fit.logFood(shake, servings: 1.5);+ fit.addWater(250);+ expect(fit.waterFromFoodOn(DateTime.now()), 750);+ expect(fit.waterOn(DateTime.now()), 1000);+ expect(FoodEntry.fromJson(e.toJson()).waterMl, 750);+ fit.removeEntry(e.id);+ expect(fit.waterOn(DateTime.now()), 250);+ final milk = fit.saveFood(name: 'Whey con leche', macros: whey);+ fit.logFood(milk);+ expect(fit.waterOn(DateTime.now()), 250);+ });++ test('el agua en litros no pierde los cuartos', () {+ expect(fit.waterValue(250), '0.25');+ expect(fit.waterValue(1750), '1.75');+ expect(fit.waterValue(2000), '2');+ expect(fit.waterLabel(1250), '1.25 L');+ expect(fit.waterLabel(250), '250 ml');+ });+test('un suplemento se marca por día y al quitarlo se van sus marcas', () {final s = fit.addSupplement('Creatina', dose: '5 g')!;fit.toggleSupplement(s.id);@@ -107,6 +130,48 @@ void main() {});});+ group('ritmo semanal del peso', () {+ void weighIns(List<(int, double)> list) {+ final n = DateTime.now();+ for (final (ago, kg) in list) {+ fit.bodyweight.add(BodyweightEntry(DateTime(n.year, n.month, n.day - ago, 8), kg));+ }+ }++ test('con pocos pesajes no hay ritmo', () {+ weighIns([(2, 80), (1, 79.8)]);+ expect(fit.weightPace, isNull);+ expect(fit.weightPaceStatus, isNull);+ });++ test('mide kg y % por semana y lo compara con lo que buscas', () {+ weighIns([(14, 81), (7, 80.5), (0, 80)]);+ final pace = fit.weightPace!;+ expect(pace.kgPerWeek, closeTo(-0.5, 0.01));+ expect(pace.pctPerWeek, closeTo(-0.5 / 80.5 * 100, 0.01));+ expect(fit.weightPaceStatus, isNull, reason: 'sin objetivo no sabe qué buscas');+ fit.setWeightAim('lose');+ expect(fit.weightPaceStatus, 'onPace');+ fit.setWeightAim('gain');+ expect(fit.weightPaceStatus, 'wrongWay');+ fit.setWeightAim('hold');+ expect(fit.weightPaceStatus, 'drifting');+ fit.setWeightAim('');+ fit.setWeightGoal(75);+ expect(fit.effectiveWeightAim, 'lose');+ fit.setWeightAim('hold');+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.weightAim, 'hold');+ });++ test('perder demasiado rápido se avisa', () {+ weighIns([(14, 84), (7, 82), (0, 80)]);+ fit.setWeightAim('lose');+ expect(fit.weightPaceStatus, 'tooFast');+ });+ });+group('guardado', () {test('todo sobrevive a cerrar la app', () {final food = fit.saveFood(name: 'Whey', photo: 'food-x.png', serving: '30 g', macros: whey);@@ -257,6 +322,25 @@ void main() {expect(r.items.first.id, isNot(added.first.id));});+ test('un plato archivado sale de la estantería y del buscador, y se recuerda', () {+ fit.logQuick('Avena', const Macros(kcal: 300), meal: Meal.breakfast);+ final r = fit.saveRecipe('Gachas', fit.entriesOn(DateTime.now()))!;+ fit.setRecipeArchived(r.id, true);+ expect(fit.activeRecipes, isEmpty);+ expect(fit.searchRecipes('gach'), isEmpty);+ expect(fit.archivedRecipeList.single.id, r.id);++ fit.persistNow();+ fit.loadFromStore();+ expect(fit.isRecipeArchived(r.id), isTrue);++ fit.setRecipeArchived(r.id, false);+ expect(fit.activeRecipes.single.id, r.id);+ fit.setRecipeArchived(r.id, true);+ fit.deleteRecipe(r.id);+ expect(fit.archivedRecipes, isEmpty);+ });+test('repetir una comida de otro día la copia al día abierto', () {fit.setNutritionDay(shiftDays(DateTime.now(), -2));fit.logQuick('Pollo', const Macros(kcal: 500), meal: Meal.dinner);@@ -344,7 +428,8 @@ void main() {test('lo quemado solo se suma si lo activas y sin contar el reposo', () {fit.profile.weightKg = 80;fit.setNutritionGoals(const NutritionGoals(kcal: 2000));- fit.sessions.add(LoggedSession(DateTime.now(), 3600, const []));+ final n = DateTime.now();+ fit.sessions.add(LoggedSession(DateTime(n.year, n.month, n.day, 12), 3600, const []));expect(fit.burnedOn(DateTime.now()), 320);expect(fit.kcalBudgetOn(DateTime.now()), 2000);fit.setAddBurned(true);@@ -448,6 +533,20 @@ void main() {expect(fit.activeBatches, isEmpty);});+ test('#301 una ración del lote se puede dejar para mañana', () {+ final rice = fit.entryFor(lib('Arroz blanco'), servings: 10);+ final b = fit.saveBatch(name: 'Táper', items: [rice], cookedGrams: 1000)!;+ final now = DateTime.now();+ final tomorrow = DateTime(now.year, now.month, now.day + 1);+ final e = fit.logFromBatch(b, 250, meal: Meal.lunch, day: tomorrow)!;+ expect(DateTime(e.at.year, e.at.month, e.at.day), tomorrow);+ expect(fit.entriesOn(now), isEmpty);+ expect(fit.entriesOn(tomorrow).single.meal, Meal.lunch);+ expect(fit.batchById(b.id)!.leftGrams, 750);+ final far = fit.logFromBatch(b, 100, day: DateTime(now.year, now.month, now.day + 40))!;+ expect(DateTime(far.at.year, far.at.month, far.at.day), DateTime(now.year, now.month, now.day + 7));+ });+test('sin peso cocinado ni gramos no se crea el lote', () {final quick = FoodEntry(id: 'x', at: DateTime.now(), meal: Meal.lunch, name: 'a', per: const Macros(kcal: 100));expect(fit.saveBatch(name: 'Nada', items: [quick]), isNull);@@ -812,4 +911,83 @@ void main() {expect(Macros.fromJson(const Macros(trans: 1.2).toJson()).trans, 1.2);});});++ group('categorías propias', () {+ test('se crean, se asignan, filtran y vuelven al reabrir', () {+ final g = fit.addFoodGroup('Platos preparados');+ expect(fit.addFoodGroup(' platos PREPARADOS '), g, reason: 'el mismo nombre no duplica');+ final fish = fit.saveFood(name: 'Merluza congelada', macros: const Macros(kcal: 90, protein: 18), group: g);+ fit.saveFood(name: 'Manzana', macros: const Macros(kcal: 52));+ expect(fit.searchFoods('', group: g).map((f) => f.id), [fish.id]);+ expect(fit.foodsInGroup(g), hasLength(1));+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.foodGroupById(g)!.name, 'Platos preparados');+ expect(fit.foodById(fish.id)!.group, g);+ });++ test('borrar la categoría deja los alimentos sin ella', () {+ final g = fit.addFoodGroup('Congelados');+ final f = fit.saveFood(name: 'Pizza', macros: const Macros(kcal: 260), group: g);+ fit.renameFoodGroup(g, 'Del congelador');+ expect(fit.foodGroupById(g)!.name, 'Del congelador');+ fit.deleteFoodGroup(g);+ expect(fit.foodGroups, isEmpty);+ expect(fit.foodById(f.id)!.group, isEmpty);+ expect(fit.foodById(f.id)!.name, 'Pizza');+ });++ test('una categoría que no existe no se guarda en el alimento', () {+ final f = fit.saveFood(name: 'Pan', macros: const Macros(kcal: 250), group: 'g-nope');+ expect(f.group, isEmpty);+ expect(fit.addFoodGroup(' '), isEmpty);+ });+ });++ group('ayuno', () {+ test('viene apagado y se activa como el resto de tarjetas', () {+ expect(fit.trackerOn(Tracker.fasting), false);+ fit.setTracker(Tracker.fasting, true);+ expect(fit.trackerOn(Tracker.fasting), true);+ });++ test('un ayuno terminado se guarda y cuenta para la racha', () {+ fit.setFastGoal(16);+ fit.startFast(at: DateTime.now().subtract(const Duration(hours: 17)));+ expect(fit.fasting, true);+ expect(fit.fastEndsAt!.isBefore(DateTime.now()), true);+ fit.endFast();+ expect(fit.fasting, false);+ expect(fit.fasts.single.reached, true);+ expect(fit.fastStreak, 1);+ fit.startFast(at: DateTime.now().subtract(const Duration(hours: 3)));+ fit.endFast();+ expect(fit.fasts.last.reached, false);+ expect(fit.fastStreak, 0, reason: 'uno corto rompe la racha');+ expect(fit.fastWeek!.count, 2);+ });++ test('no se puede empezar en el futuro ni hace días', () {+ fit.startFast(at: DateTime.now().add(const Duration(hours: 2)));+ expect(fit.fastStart!.isAfter(DateTime.now()), false);+ fit.startFast(at: DateTime.now().subtract(const Duration(days: 5)));+ expect(DateTime.now().difference(fit.fastStart!).inHours, lessThanOrEqualTo(48));+ });++ test('un ayuno en curso sobrevive a cerrar la app', () {+ fit.setFastGoal(18);+ fit.startFast(at: DateTime.now().subtract(const Duration(hours: 2)));+ final saved = fit.nutritionJson();+ fit.cancelFast();+ fit.loadNutrition(saved);+ expect(fit.fasting, true);+ expect(fit.fastGoalHours, 18);+ });++ test('cancelar no deja rastro en el historial', () {+ fit.startFast(at: DateTime.now().subtract(const Duration(hours: 5)));+ fit.cancelFast();+ expect(fit.fasts, isEmpty);+ });+ });}