Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Add the Ask an AI sheet and supplement stock editing (beta)
InlitX60ee4c034abd
diff --git a/lib/screens/nutrition/ai.dart b/lib/screens/nutrition/ai.dartnew file mode 100644index 0000000..558a12a--- /dev/null+++ b/lib/screens/nutrition/ai.dart@@ -0,0 +1,672 @@+part of '../nutrition_screen.dart';++Future<void> showMealAiSheet(BuildContext context, Meal meal, {ValueChanged<FoodEntry>? onPick}) =>+ _sheet<void>(context, (_) => _MealAiSheet(meal: meal, onPick: onPick));++const _aiTags = <(String, String)>[+ ('protein', 'high protein'),+ ('veggie', 'vegetarian'),+ ('vegan', 'vegan'),+ ('nogluten', 'gluten free'),+ ('nolactose', 'lactose free'),+ ('quick', 'quick to make, under 10 minutes'),+ ('nocook', 'no cooking needed'),+ ('cheap', 'cheap everyday ingredients'),+];++String _aiTagLabel(String id) => switch (id) {+ 'protein' => t.mealAiTagProtein,+ 'veggie' => t.mealAiTagVeggie,+ 'vegan' => t.mealAiTagVegan,+ 'nogluten' => t.mealAiTagNoGluten,+ 'nolactose' => t.mealAiTagNoLactose,+ 'quick' => t.mealAiTagQuick,+ 'nocook' => t.mealAiTagNoCook,+ _ => t.mealAiTagCheap,+ };++class _MealAiSheet extends StatefulWidget {+ const _MealAiSheet({required this.meal, this.onPick});++ final Meal meal;+ final ValueChanged<FoodEntry>? onPick;++ @override+ State<_MealAiSheet> createState() => _MealAiSheetState();+}++class _MealAiSheetState extends State<_MealAiSheet> {+ static String _lastNotes = '';+ static final Set<String> _lastTags = {};++ late final TextEditingController _notes = TextEditingController(text: _lastNotes);+ final _answer = TextEditingController();+ bool _day = false;+ int _step = 0;+ int _options = 3;+ int _kcal = 300;+ int _protein = 25;+ int _carbs = 30;+ int _fat = 10;+ int _left = 0;+ int _leftProtein = 0;+ bool _showText = false;+ bool _reviewed = false;+ bool _truncated = false;+ int _pick = 0;+ List<AiDraftOption> _drafts = const [];++ @override+ void initState() {+ super.initState();+ _retarget();+ }++ @override+ void dispose() {+ _notes.dispose();+ _answer.dispose();+ super.dispose();+ }++ void _retarget() {+ final g = fit.mealAiTargets(widget.meal, day: _day);+ _kcal = g.kcal;+ _protein = g.protein;+ _carbs = g.carbs;+ _fat = g.fat;+ _left = g.leftKcal;+ _leftProtein = g.leftProtein;+ }++ String get _prompt {+ final today = fit.entriesOn(fit.nutritionDay);+ final eaten = <String>[];+ for (final e in today) {+ if (!eaten.contains(e.name)) eaten.add(e.name);+ }+ return buildMealAiPrompt(MealAiBrief(+ language: languageNameOf(appLanguage),+ day: _day,+ mealId: widget.meal.id,+ mealLabel: mealName(widget.meal),+ slots: [for (final s in fit.mealSlots) (s.meal.id, mealName(s.meal))],+ kcal: _kcal,+ protein: _protein,+ carbs: _carbs,+ fat: _fat,+ options: _options,+ tags: [for (final tag in _aiTags) if (_lastTags.contains(tag.$1)) tag.$2],+ notes: _notes.text,+ eaten: eaten.take(10).toList(),+ ));+ }++ Future<void> _copy() async {+ _lastNotes = _notes.text;+ FocusScope.of(context).unfocus();+ await Clipboard.setData(ClipboardData(text: _prompt));+ if (!mounted) return;+ HapticFeedback.lightImpact();+ showNotchToast(context, t.mealAiCopied,+ subtitle: t.mealAiCopiedHint, icon: PhosphorIconsFill.copy, accent: context.gc.sage);+ setState(() => _step = 1);+ }++ Future<void> _paste() async {+ final data = await Clipboard.getData(Clipboard.kTextPlain);+ final text = data?.text;+ if (text == null || text.trim().isEmpty || !mounted) return;+ _answer.text = text;+ await _review();+ }++ Future<void> _file() async {+ final text = await pickTextFile();+ if (text == null || !mounted) return;+ _answer.text = text;+ await _review();+ }++ Future<void> _review() async {+ final raw = _answer.text;+ if (raw.trim().isEmpty) return;+ FocusScope.of(context).unfocus();+ if (!FoodLibrary.ready) await FoodLibrary.load();+ if (!mounted) return;+ final reply = parseMealAi(raw);+ final drafts = reply.isEmpty+ ? const <AiDraftOption>[]+ : resolveMealAi(reply,+ lang: appLanguage, meal: widget.meal, slots: fit.mealSlots, day: _day, own: fit.foods);+ HapticFeedback.selectionClick();+ setState(() {+ _reviewed = true;+ _drafts = drafts;+ _truncated = reply.truncated;+ _pick = 0;+ });+ }++ Future<void> _copyFix() async {+ await Clipboard.setData(const ClipboardData(text: mealAiRetrySentence));+ if (!mounted) return;+ showNotchToast(context, t.copiedDone, icon: PhosphorIconsFill.copy, accent: context.gc.sage);+ }++ Future<void> _editAmount(AiDraft d) async {+ final unit = _amtUnit(d.entry.liquid);+ final shown = d.shownGrams;+ if (shown <= 0) return;+ final display = fit.isLb ? shown / _ozOf(d.entry.liquid) : shown;+ final v = await askNumber(+ context,+ title: '${t.mealAiAmount} ($unit)',+ initial: fmt(fit.isLb ? (display * 10).round() / 10 : display.round().toDouble()),+ decimal: fit.isLb,+ );+ if (v == null || v <= 0 || !mounted) return;+ setState(() => d.scaleTo(fit.isLb ? v * _ozOf(d.entry.liquid) : v));+ }++ Future<void> _add(AiDraftOption o) async {+ final chosen = o.chosen;+ if (chosen.isEmpty) return;+ HapticFeedback.lightImpact();+ final host = Navigator.of(context, rootNavigator: true).context;+ final sage = context.gc.sage;+ final pick = widget.onPick;+ var n = 0;+ if (pick != null) {+ for (final d in chosen) {+ pick(d.entry.copyWith(meal: widget.meal));+ n++;+ }+ } else {+ final groups = <Meal, List<FoodEntry>>{};+ for (final d in chosen) {+ groups.putIfAbsent(d.entry.meal, () => []).add(d.entry);+ }+ for (final g in groups.entries) {+ n += fit.logEntries(g.value, g.key).length;+ }+ }+ Navigator.of(context).pop();+ if (host.mounted) showNotchToast(host, t.mealAiAdded(n), icon: PhosphorIconsFill.checkCircle, accent: sage);+ }++ Future<void> _save(AiDraftOption o) async {+ final chosen = o.chosen;+ if (chosen.isEmpty) return;+ final title = _day ? t.mealAiSavePlan : t.mealAiSaveRecipe;+ final name = await askText(context, title: title, initial: o.name);+ if (name == null || name.trim().isEmpty || !mounted) return;+ final host = Navigator.of(context, rootNavigator: true).context;+ final sage = context.gc.sage;+ if (_day) {+ fit.saveMealPlan(+ MealPlan(+ id: '',+ name: name,+ color: fit.mealPlans.length,+ items: [for (final d in chosen) d.entry.copyWith(id: fit.newPlanItemId())],+ ),+ const {},+ );+ } else {+ fit.saveRecipe(name, [for (final d in chosen) d.entry]);+ }+ HapticFeedback.lightImpact();+ Navigator.of(context).pop();+ if (host.mounted) {+ showNotchToast(host, _day ? t.mealAiPlanSaved : t.mealAiRecipeSaved,+ icon: PhosphorIconsFill.checkCircle, accent: sage);+ }+ }++ Widget _stepper(GymColors gc, String label, Widget control) => Row(children: [+ Expanded(child: Text(label, style: AppTheme.f(13.5, weight: FontWeight.w600, color: gc.text))),+ control,+ ]);++ Widget _askPage(GymColors gc) {+ final steppers = !_day;+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ _kicker(gc, t.mealAiTarget.toUpperCase()),+ const SizedBox(height: 10),+ Center(+ child: SegToggle([+ SegOption(titleCase(mealName(widget.meal)), !_day, () {+ if (!_day) return;+ setState(() {+ _day = false;+ _options = 3;+ _retarget();+ });+ }),+ SegOption(t.mealAiWholeDay, _day, () {+ if (_day) return;+ setState(() {+ _day = true;+ _options = 1;+ _retarget();+ });+ }),+ ], hPad: 18, vPad: 9, fontSize: 13),+ ),+ const SizedBox(height: 14),+ Container(+ padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ if (steppers) ...[+ _stepper(+ gc,+ sentenceCase(t.kcalLabel),+ StepperControl(+ value: _energy(_kcal),+ minWidth: 86,+ fontSize: 15,+ onDec: () => setState(() => _kcal = (_kcal - 50).clamp(100, 3000)),+ onInc: () => setState(() => _kcal = (_kcal + 50).clamp(100, 3000)),+ ),+ ),+ const SizedBox(height: 8),+ _stepper(+ gc,+ sentenceCase(t.macroProtein),+ StepperControl(+ value: ltr('$_protein g'),+ minWidth: 86,+ fontSize: 15,+ onDec: () => setState(() => _protein = (_protein - 5).clamp(5, 250)),+ onInc: () => setState(() => _protein = (_protein + 5).clamp(5, 250)),+ ),+ ),+ const SizedBox(height: 10),+ Text(t.mealAiLeft(_energy(_left), _leftProtein),+ style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textTertiary, height: 1.35)),+ ] else+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 6),+ child: Text(+ '${_energy(_kcal)} · ${ltr('$_protein g')} ${t.macroProtein.toLowerCase()} · ${ltr('$_carbs g')} ${t.macroCarbs.toLowerCase()} · ${ltr('$_fat g')} ${t.macroFat.toLowerCase()}',+ style: AppTheme.f(13, weight: FontWeight.w600, color: gc.text, height: 1.4)),+ ),+ ]),+ ),+ const SizedBox(height: 22),+ _kicker(gc, t.mealAiStyle.toUpperCase()),+ const SizedBox(height: 10),+ Wrap(spacing: 7, runSpacing: 7, children: [+ for (final tag in _aiTags)+ _Chip(+ label: _aiTagLabel(tag.$1),+ selected: _lastTags.contains(tag.$1),+ onTap: () {+ HapticFeedback.selectionClick();+ setState(() => _lastTags.contains(tag.$1) ? _lastTags.remove(tag.$1) : _lastTags.add(tag.$1));+ },+ ),+ ]),+ const SizedBox(height: 12),+ TextField(+ controller: _notes,+ minLines: 2,+ maxLines: 4,+ textCapitalization: TextCapitalization.sentences,+ keyboardType: TextInputType.multiline,+ onChanged: (v) => _lastNotes = v,+ style: AppTheme.f(14, weight: FontWeight.w500, color: gc.text, height: 1.35),+ cursorColor: gc.accent,+ decoration: InputDecoration(+ hintText: t.mealAiNotesHint,+ hintStyle: AppTheme.f(14, weight: FontWeight.w500, color: gc.textTertiary),+ filled: true,+ fillColor: gc.bgRaised2,+ contentPadding: const EdgeInsets.all(16),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none),+ ),+ ),+ const SizedBox(height: 16),+ _stepper(+ gc,+ t.mealAiOptions,+ StepperControl(+ value: '$_options',+ minWidth: 40,+ fontSize: 15,+ onDec: () => setState(() => _options = (_options - 1).clamp(1, _day ? 3 : 4)),+ onInc: () => setState(() => _options = (_options + 1).clamp(1, _day ? 3 : 4)),+ ),+ ),+ const SizedBox(height: 20),+ PrimaryButton(label: t.mealAiCopy, onTap: _copy),+ const SizedBox(height: 4),+ Pressable(+ onTap: () => setState(() => _showText = !_showText),+ scale: 0.97,+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 12),+ child: Center(+ child: Text(_showText ? t.mealAiHideText : t.mealAiShowText,+ style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.accent)),+ ),+ ),+ ),+ AnimatedSize(+ duration: const Duration(milliseconds: 260),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: _showText+ ? Container(+ padding: const EdgeInsets.all(14),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),+ child: Ltr(+ child: SelectableText(_prompt,+ style: TextStyle(fontFamily: 'monospace', fontSize: 11, color: gc.textSecondary, height: 1.4)),+ ),+ )+ : const SizedBox(width: double.infinity),+ ),+ ]);+ }++ Widget _chipButton(GymColors gc, IconData icon, String label, VoidCallback onTap, {Color? bg}) => Pressable(+ onTap: onTap,+ scale: 0.95,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),+ decoration: BoxDecoration(color: bg ?? gc.bgRaised2, borderRadius: BorderRadius.circular(100)),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(icon, size: 15, color: gc.text),+ const SizedBox(width: 7),+ Text(label, style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.text)),+ ]),+ ),+ );++ Widget _pastePage(GymColors gc) {+ final empty = _answer.text.trim().isEmpty;+ final done = _reviewed && _drafts.isNotEmpty;+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ TextField(+ controller: _answer,+ minLines: done ? 2 : 5,+ maxLines: done ? 2 : 9,+ keyboardType: TextInputType.multiline,+ onChanged: (_) => setState(() {}),+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.text, height: 1.35),+ cursorColor: gc.accent,+ decoration: InputDecoration(+ hintText: t.mealAiPasteHint,+ hintStyle: AppTheme.f(14, weight: FontWeight.w500, color: gc.textTertiary),+ filled: true,+ fillColor: gc.bgRaised2,+ contentPadding: const EdgeInsets.all(16),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none),+ ),+ ),+ const SizedBox(height: 10),+ Row(children: [+ _chipButton(gc, PhosphorIconsRegular.clipboardText, t.pasteAction, _paste),+ const SizedBox(width: 8),+ _chipButton(gc, PhosphorIconsRegular.fileArrowUp, t.chooseFile, _file),+ ]),+ const SizedBox(height: 16),+ PrimaryButton(+ label: t.mealAiReview,+ bg: empty ? gc.bgRaised2 : gc.ember,+ fg: empty ? gc.textTertiary : gc.onEmber,+ onTap: _review,+ ),+ if (_reviewed) ...[const SizedBox(height: 22), _result(gc)],+ ]);+ }++ Widget _result(GymColors gc) {+ if (_drafts.isEmpty) {+ return Container(+ padding: const EdgeInsets.all(16),+ decoration: BoxDecoration(+ color: gc.bgRaised2,+ borderRadius: BorderRadius.circular(16),+ border: Border.all(color: gc.warn.withValues(alpha: 0.55)),+ ),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(t.mealAiUnreadable, style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),+ const SizedBox(height: 6),+ Text(t.mealAiUnreadableHint,+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.45)),+ const SizedBox(height: 12),+ _chipButton(gc, PhosphorIconsRegular.copy, t.mealAiCopyFix, _copyFix, bg: gc.bgRaised),+ ]),+ );+ }+ final o = _drafts[_pick.clamp(0, _drafts.length - 1)];+ final total = o.total;+ final chosen = o.chosen;+ final near = _kcal > 0 && (total.kcal - _kcal).abs() <= _kcal * 0.15;+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ if (_drafts.length > 1) ...[+ Center(+ child: SegToggle([+ for (var i = 0; i < _drafts.length; i++) SegOption(t.mealAiOption(i + 1), i == _pick, () => setState(() => _pick = i)),+ ], hPad: 14, vPad: 8, fontSize: 12.5),+ ),+ const SizedBox(height: 14),+ ],+ if (o.name.isNotEmpty) ...[+ Text(o.name, style: AppTheme.f(16, weight: FontWeight.w800, color: gc.text, height: 1.25)),+ const SizedBox(height: 10),+ ],+ Container(+ padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Ltr(+ child: Row(children: [+ Expanded(child: _total(gc, '${fit.energyOf(total.kcal)}', fit.energyUnit.toUpperCase(), big: true)),+ Expanded(child: _total(gc, '${total.protein.round()}', t.macroProtein)),+ Expanded(child: _total(gc, '${total.carbs.round()}', t.macroCarbs)),+ Expanded(child: _total(gc, '${total.fat.round()}', t.macroFat)),+ ]),+ ),+ if (!_day || _kcal > 0) ...[+ const SizedBox(height: 10),+ Text(t.mealAiTargetLine(_energy(_kcal)),+ style: AppTheme.f(11.5, weight: FontWeight.w700, color: near ? gc.sage : gc.textTertiary)),+ ],+ ]),+ ),+ const SizedBox(height: 10),+ for (final d in o.items) _itemRow(gc, d),+ if (_truncated) ...[+ const SizedBox(height: 6),+ Text(t.mealAiTruncated, style: AppTheme.f(12, weight: FontWeight.w600, color: gc.warn, height: 1.4)),+ ],+ const SizedBox(height: 16),+ if (chosen.isEmpty)+ PrimaryButton(label: t.mealAiNothingChosen, bg: gc.bgRaised2, fg: gc.textTertiary, onTap: () {})+ else+ PrimaryButton(+ label: widget.onPick != null+ ? '${t.mealAiAddPick} · ${_energy(total.kcal)}'+ : _day+ ? '${t.mealAiAddDay} · ${_energy(total.kcal)}'+ : '${t.mealAiAddTo(mealInSentence(widget.meal))} · ${_energy(total.kcal)}',+ onTap: () => _add(o),+ ),+ if (widget.onPick == null && chosen.isNotEmpty) ...[+ const SizedBox(height: 10),+ GhostButton(+ label: _day ? t.mealAiSavePlan : t.mealAiSaveRecipe,+ icon: _day ? PhosphorIconsRegular.calendarPlus : PhosphorIconsRegular.cookingPot,+ onTap: () => _save(o),+ ),+ ],+ ]);+ }++ Widget _total(GymColors gc, String value, String label, {bool big = false}) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ FittedBox(+ fit: BoxFit.scaleDown,+ alignment: AlignmentDirectional.centerStart,+ child: RollingText(value, style: AppTheme.f(big ? 26 : 19, weight: FontWeight.w800, color: gc.text, height: 1.1)),+ ),+ const SizedBox(height: 3),+ Text(label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(9.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.1)),+ ],+ );++ String? _flagText(AiDraft d) {+ if (d.flags.contains(AiFlag.noValues)) return t.mealAiFlagNoValues;+ if (d.flags.contains(AiFlag.doubtful)) return t.mealAiFlagDoubtful;+ if (d.flags.contains(AiFlag.adjusted)) return t.mealAiFlagAdjusted;+ if (d.flags.contains(AiFlag.noAmount)) return t.mealAiFlagNoAmount;+ if (d.source == AiSource.ai) return t.mealAiFlagEstimated;+ return null;+ }++ Widget _leading(GymColors gc, AiDraft d) {+ final photo = fit.photoForEntry(d.entry);+ if (photo.isNotEmpty) return FoodSticker(photo: photo, name: d.name, size: 38, tilt: false, shadow: false);+ return Container(+ width: 34,+ height: 34,+ decoration: BoxDecoration(color: gc.bgRaised, shape: BoxShape.circle),+ child: Icon(PhosphorIconsRegular.forkKnife, size: 16, color: gc.textTertiary),+ );+ }++ Widget _itemRow(GymColors gc, AiDraft d) {+ final flag = _flagText(d);+ final bad = d.flags.contains(AiFlag.doubtful) || d.flags.contains(AiFlag.noValues);+ final tone = bad ? gc.warn : (d.source == AiSource.ai ? gc.textTertiary : gc.textSecondary);+ final active = d.on && d.usable;+ final grams = d.shownGrams;+ return AnimatedOpacity(+ duration: const Duration(milliseconds: 180),+ opacity: active ? 1 : 0.5,+ child: Container(+ margin: const EdgeInsets.only(bottom: 6),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),+ child: Row(children: [+ Expanded(+ child: Pressable(+ onTap: d.usable && grams > 0 ? () => _editAmount(d) : () {},+ scale: 0.985,+ child: Padding(+ padding: const EdgeInsetsDirectional.fromSTEB(10, 9, 0, 9),+ child: Row(children: [+ SizedBox(width: 38, height: 38, child: Center(child: _leading(gc, d))),+ const SizedBox(width: 10),+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(d.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),+ const SizedBox(height: 2),+ Text(+ [+ if (grams > 0) _amount(grams, d.entry.liquid),+ if (d.usable) _energy(d.total.kcal),+ ].join(' · '),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textSecondary)),+ if (flag != null) ...[+ const SizedBox(height: 2),+ Text(flag,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(11, weight: FontWeight.w600, color: tone, height: 1.25)),+ ],+ ]),+ ),+ ]),+ ),+ ),+ ),+ Semantics(+ button: true,+ checked: active,+ label: d.name,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: d.usable+ ? () {+ HapticFeedback.selectionClick();+ setState(() => d.on = !d.on);+ }+ : null,+ child: SizedBox(+ width: 52,+ height: 52,+ child: Center(+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 180),+ width: 24,+ height: 24,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: active ? gc.accent : Colors.transparent,+ border: Border.all(color: active ? gc.accent : gc.textTertiary, width: 1.5),+ ),+ child: active ? Icon(PhosphorIconsBold.check, size: 13, color: gc.onEmber) : null,+ ),+ ),+ ),+ ),+ ),+ ]),+ ),+ );+ }++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ return _sheetFrame(context, [+ SheetTitle(t.mealAiTitle, subtitle: t.mealAiSubtitle),+ const SizedBox(height: 10),+ Center(child: BetaTag(t.sectionBeta, small: true)),+ const SizedBox(height: 16),+ Center(+ child: SegToggle([+ SegOption('1 · ${t.mealAiStepAsk}', _step == 0, () => setState(() => _step = 0)),+ SegOption('2 · ${t.mealAiStepPaste}', _step == 1, () => setState(() => _step = 1)),+ ], hPad: 18, vPad: 9, fontSize: 13),+ ),+ const SizedBox(height: 20),+ AnimatedSize(+ duration: const Duration(milliseconds: 340),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: AnimatedSwitcher(+ duration: const Duration(milliseconds: 240),+ switchInCurve: Curves.easeOutCubic,+ switchOutCurve: Curves.easeInCubic,+ layoutBuilder: (current, previous) => Stack(+ alignment: Alignment.topCenter,+ children: [+ for (final p in previous) Positioned(top: 0, left: 0, right: 0, child: p),+ ?current,+ ],+ ),+ transitionBuilder: (child, a) => FadeTransition(opacity: a, child: child),+ child: KeyedSubtree(+ key: ValueKey(_step),+ child: _step == 0 ? _askPage(gc) : _pastePage(gc),+ ),+ ),+ ),+ ]);+ }+}diff --git a/lib/screens/nutrition/cards.dart b/lib/screens/nutrition/cards.dartindex 40c38f6..b831131 100644--- a/lib/screens/nutrition/cards.dart+++ b/lib/screens/nutrition/cards.dart@@ -26,7 +26,7 @@ class _HeroCard extends StatelessWidget {);Widget macro(IconData icon, String label, double value, int goal, Color color) => Expanded(child: Column(children: [- Row(+ Ltr(child: Row(mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.baseline,textBaseline: TextBaseline.alphabetic,@@ -34,7 +34,7 @@ class _HeroCard extends StatelessWidget {RollingText('${value.round()}', style: AppTheme.f(15, weight: FontWeight.w800, color: gc.text)),Text('/${goal}g', style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary)),],- ),+ )),const SizedBox(height: 7),Padding(padding: const EdgeInsets.symmetric(horizontal: 8),@@ -147,14 +147,14 @@ class _RingCard extends StatelessWidget {FittedBox(fit: BoxFit.scaleDown,alignment: Alignment.centerLeft,- child: Row(+ child: Ltr(child: Row(crossAxisAlignment: CrossAxisAlignment.baseline,textBaseline: TextBaseline.alphabetic,children: [RollingText(value, style: AppTheme.f(21, weight: FontWeight.w800, color: gc.text, height: 1.05)),Text(' g', style: AppTheme.f(12, weight: FontWeight.w700, color: gc.textSecondary)),],- ),+ )),),const SizedBox(height: 2),Text(sub, maxLines: 1, style: AppTheme.f(11, weight: FontWeight.w600, color: gc.textSecondary)),@@ -612,7 +612,7 @@ class _Tile extends StatelessWidget {Center(child: vessel),const Spacer(),const SizedBox(height: 12),- Row(crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [+ Ltr(child: Row(crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [RollingText(value, style: AppTheme.f(26, weight: FontWeight.w800, color: gc.text, height: 1.2)),const SizedBox(width: 4),Flexible(@@ -621,7 +621,7 @@ class _Tile extends StatelessWidget {overflow: TextOverflow.ellipsis,style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary)),),- ]),+ ])),const SizedBox(height: 4),FitText(hint, style: AppTheme.f(11.5, weight: FontWeight.w700, color: hintColor)),]),@@ -1081,10 +1081,13 @@ class _SupplementRow extends StatelessWidget {Widget build(BuildContext context) {final gc = context.gc;final at = fit.supplementTime(supp);+ final dose = fit.suppDoseLabel(supp);final detail = [- if (supp.dose.isNotEmpty) supp.dose,+ if (dose.isNotEmpty) dose,_suppSchedule(context, supp, daily: false),].where((x) => x.isNotEmpty).join(' · ');+ final left = off ? null : fit.suppDaysLeft(supp);+ final low = left == null || left > 7 ? null : (left == 0 ? t.suppRanOut : t.suppLeftFor(left));return SizedBox(height: height,child: Pressable(@@ -1141,14 +1144,21 @@ class _SupplementRow extends StatelessWidget {maxLines: 1,overflow: TextOverflow.ellipsis,style: AppTheme.f(14.5, weight: FontWeight.w800, color: off ? gc.textSecondary : gc.text)),- if (detail.isNotEmpty) ...[+ if (detail.isNotEmpty || low != null) ...[const SizedBox(height: 2),Row(children: [Icon(at != null ? PhosphorIconsFill.bellSimpleRinging : PhosphorIconsFill.calendarBlank,size: 11, color: gc.textTertiary),const SizedBox(width: 4),Flexible(- child: Text(detail,+ child: Text.rich(+ TextSpan(children: [+ if (low != null)+ TextSpan(+ text: detail.isEmpty ? low : '$low · ',+ style: AppTheme.f(11.5, weight: FontWeight.w800, color: gc.accent)),+ TextSpan(text: detail),+ ]),maxLines: 1,overflow: TextOverflow.ellipsis,style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textSecondary)),@@ -1223,7 +1233,7 @@ Future<void> showSupplementInfo(BuildContext context, Supplement supp) => _sheetreturn _sheetFrame(sheet, [Center(child: FoodSticker(photo: _suppPhoto(s), name: s.name, size: 104, tilt: false)),const SizedBox(height: 12),- SheetTitle(s.name, subtitle: s.dose.isEmpty ? null : s.dose),+ SheetTitle(s.name, subtitle: fit.suppDoseLabel(s).isEmpty ? null : fit.suppDoseLabel(s)),const SizedBox(height: 16),Container(padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),@@ -1233,6 +1243,16 @@ Future<void> showSupplementInfo(BuildContext context, Supplement supp) => _sheetline(PhosphorIconsRegular.bellSimpleRinging, t.suppRemind, at == null ? t.suppNoReminder : _clock(sheet, at)),if (s.from != null && s.from!.isAfter(day)) line(PhosphorIconsRegular.flagBanner, t.suppStarts, t.shortDate(s.from!)),if (s.until != null) line(PhosphorIconsRegular.flagCheckered, t.suppEnds, t.shortDate(s.until!)),+ if (s.stock != null)+ line(+ PhosphorIconsRegular.package,+ t.suppLeft,+ switch (fit.suppDaysLeft(s)) {+ 0 => t.suppRanOut,+ null => fit.suppAmountLabel(s.stock!, s.unit),+ final d => '${fit.suppAmountLabel(s.stock!, s.unit)} · ${t.suppForDays(d)}',+ },+ ),]),),const SizedBox(height: 18),@@ -1311,7 +1331,25 @@ enum _Repeat { daily, days, every }class _SupplementEditorState extends State<_SupplementEditor> with _StickerDrafts {late final _name = TextEditingController(text: widget.supp?.name ?? widget.name);- late final _dose = TextEditingController(text: widget.supp?.dose ?? '');+ late final _amount = TextEditingController(text: _num(widget.supp?.amount));+ late final _stock = TextEditingController(text: _num(widget.supp?.stock));+ late String _unit = widget.supp?.unit ?? '';++ static String _num(double? v) => v == null ? '' : fmt((v * 100).round() / 100);++ double? _parsed(TextEditingController c) {+ final v = double.tryParse(c.text.trim().replaceAll(',', '.'));+ return v == null || v < 0 ? null : v;+ }++ @override+ void initState() {+ super.initState();+ _amount.addListener(_refresh);+ _stock.addListener(_refresh);+ }++ void _refresh() => setState(() {});@overridelate String _photo = widget.supp == null ? _suppPresets.first : _suppPhoto(widget.supp!);late int? _at = widget.supp == null ? 9 * 60 : fit.supplementTime(widget.supp!);@@ -1339,7 +1377,8 @@ class _SupplementEditorState extends State<_SupplementEditor> with _StickerDraft@overridevoid dispose() {_name.dispose();- _dose.dispose();+ _amount.dispose();+ _stock.dispose();_dropDrafts();super.dispose();}@@ -1358,14 +1397,29 @@ class _SupplementEditorState extends State<_SupplementEditor> with _StickerDraftfinal supp = widget.supp;final from = _from.isAfter(_today) || _repeat == _Repeat.every ? _from : null;final until = _until;+ final amount = _parsed(_amount);+ final stock = _parsed(_stock);if (supp == null) {fit.addSupplement(name,- dose: _dose.text, photo: _photo, at: _at, days: _savedDays, every: _savedEvery, from: from, until: until);+ amount: amount,+ unit: _unit,+ stock: stock,+ photo: _photo,+ at: _at,+ days: _savedDays,+ every: _savedEvery,+ from: from,+ until: until);} else {fit.updateSupplement(supp.id,name: name,- dose: _dose.text,+ dose: amount != null && amount > 0 ? '' : null,+ amount: amount,+ clearAmount: amount == null && _amount.text.trim().isEmpty,+ unit: _unit,+ stock: stock,+ clearStock: stock == null,photo: _photo,at: _at,clearAt: _at == null,@@ -1518,7 +1572,44 @@ class _SupplementEditorState extends State<_SupplementEditor> with _StickerDraftconst SizedBox(height: 16),_TextInput(controller: _name, hint: t.supplementNameHint, label: t.nameLabel),const SizedBox(height: 8),- _TextInput(controller: _dose, hint: t.suppDoseHint, label: t.suppDose),+ Row(children: [+ Expanded(+ child: _NumberField(+ label: t.suppDose.toUpperCase(),+ controller: _amount,+ color: gc.textTertiary,+ suffix: fit.suppUnitLabel(_unit, _parsed(_amount) ?? 1),+ hint: widget.supp?.amount == null && (widget.supp?.dose.isNotEmpty ?? false) ? widget.supp!.dose : '1',+ ),+ ),+ const SizedBox(width: 8),+ Expanded(+ child: _NumberField(+ label: t.suppLeft.toUpperCase(),+ controller: _stock,+ color: gc.textTertiary,+ suffix: _stock.text.trim().isEmpty ? '' : fit.suppUnitLabel(_unit, _parsed(_stock) ?? 2),+ hint: t.suppLeftHint,+ ),+ ),+ ]),+ const SizedBox(height: 8),+ SizedBox(+ height: 36,+ child: ListView(scrollDirection: Axis.horizontal, clipBehavior: Clip.none, children: [+ for (final u in kSuppUnits) ...[+ _Chip(+ label: fit.suppUnitLabel(u, _parsed(_amount) ?? 1),+ selected: _unit == u,+ onTap: () {+ HapticFeedback.selectionClick();+ setState(() => _unit = _unit == u ? '' : u);+ },+ ),+ const SizedBox(width: 7),+ ],+ ]),+ ),section(t.suppWhen),Center(child: SegToggle([@@ -1599,7 +1690,7 @@ class _SupplementEditorState extends State<_SupplementEditor> with _StickerDraft? const SizedBox(width: double.infinity): Padding(padding: const EdgeInsets.only(top: 14),- child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [+ child: Directionality(textDirection: TextDirection.ltr, child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [part((at ~/ 60).toString().padLeft(2, '0'), () => setState(() => _at = (at - 60 + 1440) % 1440),() => setState(() => _at = (at + 60) % 1440)),Padding(@@ -1608,7 +1699,7 @@ class _SupplementEditorState extends State<_SupplementEditor> with _StickerDraft),part((at % 60).toString().padLeft(2, '0'), () => setState(() => _at = (at - 5 + 1440) % 1440),() => setState(() => _at = (at + 5) % 1440)),- ]),+ ])),),),section(t.suppStarts),diff --git a/lib/screens/nutrition/food.dart b/lib/screens/nutrition/food.dartindex 7b618d5..5ec0dd8 100644--- a/lib/screens/nutrition/food.dart+++ b/lib/screens/nutrition/food.dart@@ -348,6 +348,24 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {]),const SizedBox(height: 14),_cats(gc),+ if (q.isEmpty && _cat == null && !grouped && !_dishes) ...[+ const SizedBox(height: 14),+ _FoodRow(+ leading: Container(+ width: 38,+ height: 38,+ decoration: BoxDecoration(color: gc.accent.withValues(alpha: 0.14), shape: BoxShape.circle),+ child: Icon(PhosphorIconsRegular.sparkle, size: 17, color: gc.accent),+ ),+ title: t.mealAiRow,+ detail: t.mealAiRowHint,+ badge: BetaTag(t.sectionBeta, small: true),+ onTap: () {+ Navigator.of(context).pop();+ showMealAiSheet(context, widget.meal, onPick: widget.onPick);+ },+ ),+ ],if (recipes.isNotEmpty || (!picking && _cat == null && !grouped && q.isEmpty)) ...[_section(gc, t.savedMeals),if (!picking && _cat == null && !grouped && q.isEmpty)@@ -525,12 +543,13 @@ class _FoodTile extends StatelessWidget {}class _FoodRow extends StatelessWidget {- const _FoodRow({required this.leading, required this.title, required this.detail, required this.onTap});+ const _FoodRow({required this.leading, required this.title, required this.detail, required this.onTap, this.badge});final Widget leading;final String title;final String detail;final VoidCallback onTap;+ final Widget? badge;@overrideWidget build(BuildContext context) {@@ -547,10 +566,15 @@ class _FoodRow extends StatelessWidget {const SizedBox(width: 10),Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Text(title,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),+ Row(children: [+ Flexible(+ child: Text(title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),+ ),+ if (badge != null) ...[const SizedBox(width: 8), badge!],+ ]),const SizedBox(height: 2),Text(detail,maxLines: 1,@@ -752,7 +776,7 @@ class _AmountDial extends StatelessWidget {GestureDetector(behavior: HitTestBehavior.opaque,onTap: () => _type(context),- child: Row(+ child: Ltr(child: Row(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.baseline,textBaseline: TextBaseline.alphabetic,@@ -763,7 +787,7 @@ class _AmountDial extends StatelessWidget {const SizedBox(width: 6),Icon(PhosphorIconsBold.pencilSimple, size: 13, color: gc.textTertiary),],- ),+ )),),const SizedBox(height: 6),RulerPicker(@@ -1430,12 +1454,14 @@ class _EntryValuesSheetState extends State<_EntryValuesSheet> {}class _NumberField extends StatelessWidget {- const _NumberField({required this.label, required this.controller, required this.color, this.suffix = 'g'});+ const _NumberField(+ {required this.label, required this.controller, required this.color, this.suffix = 'g', this.hint = '0'});final String label;final TextEditingController controller;final Color color;final String suffix;+ final String hint;@overrideWidget build(BuildContext context) {@@ -1456,8 +1482,8 @@ class _NumberField extends StatelessWidget {decoration: InputDecoration(isDense: true,border: InputBorder.none,- hintText: '0',- hintStyle: AppTheme.f(19, weight: FontWeight.w800, color: gc.textTertiary),+ hintText: hint,+ hintStyle: AppTheme.f(hint == '0' ? 19 : 15, weight: FontWeight.w800, color: gc.textTertiary),contentPadding: const EdgeInsets.only(top: 4),),),diff --git a/lib/screens/nutrition/meals.dart b/lib/screens/nutrition/meals.dartindex d22d73e..e91bbc7 100644--- a/lib/screens/nutrition/meals.dart+++ b/lib/screens/nutrition/meals.dart@@ -388,12 +388,12 @@ class _MealTabsState extends State<_MealTabs> {const SizedBox(width: 16),Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Row(crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [+ Ltr(child: Row(crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [RollingText('${fit.energyOf(total.kcal)}',style: AppTheme.f(30, weight: FontWeight.w800, color: gc.text, height: 1.2)),const SizedBox(width: 5),Text(fit.energyUnit, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.textSecondary)),- ]),+ ])),const SizedBox(height: 4),Text(shown.isEmpty ? t.nothingLogged : t.recipeItems(shown.length),diff --git a/lib/screens/nutrition_screen.dart b/lib/screens/nutrition_screen.dartindex 8339441..e6eb1bf 100644--- a/lib/screens/nutrition_screen.dart+++ b/lib/screens/nutrition_screen.dart@@ -13,6 +13,7 @@ import 'package:url_launcher/url_launcher.dart';import '../l10n/l10n.dart';import '../models/nutrition.dart';import '../services/food_library.dart';+import '../services/meal_ai.dart';import '../services/media_store.dart';import '../services/sticker_cutout.dart';import '../state/fit_state.dart';@@ -39,6 +40,7 @@ part 'nutrition/settings.dart';part 'nutrition/meals.dart';part 'nutrition/food.dart';part 'nutrition/plans.dart';+part 'nutrition/ai.dart';part 'nutrition/fasting.dart';String mealInSentence(Meal m) {@@ -82,7 +84,7 @@ String _amount(double grams, bool liquid) => fit.isLb? '${fmt((grams / _ozOf(liquid) * 10).round() / 10)} ${_amtUnit(liquid)}': '${fmt(grams.round().toDouble())} ${_unitOf(liquid)}';-String _energy(num kcal) => '${fit.energyOf(kcal)} ${fit.energyUnit}';+String _energy(num kcal) => ltr('${fit.energyOf(kcal)} ${fit.energyUnit}');String portionName(PortionKind k, [int n = 1]) => switch (k) {PortionKind.unit => t.portionUnit(n),@@ -403,14 +405,16 @@ class _DayDot extends StatelessWidget {Widget _sheetFrame(BuildContext context, List<Widget> children, {double heightFactor = 0}) {final gc = context.gc;+ final pad = sheetPad(context, bottom: 18);return Padding(padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),child: Container(constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.88),height: heightFactor > 0 ? MediaQuery.of(context).size.height * heightFactor : null,- padding: sheetPad(context, bottom: 18),+ padding: EdgeInsets.only(top: pad.top, bottom: pad.bottom),decoration: sheetDecoration(gc),child: SingleChildScrollView(+ padding: EdgeInsets.only(left: pad.left, right: pad.right),child: Column(mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.stretch,diff --git a/lib/state/nutrition_state.dart b/lib/state/nutrition_state.dartindex 52602e5..ff10f24 100644--- a/lib/state/nutrition_state.dart+++ b/lib/state/nutrition_state.dart@@ -454,6 +454,35 @@ mixin NutritionState on FitCore, ToolsState, StatsState {return e;}+ List<FoodEntry> logEntries(Iterable<FoodEntry> items, Meal meal) => _logCopies(items, meal);++ ({int kcal, int protein, int carbs, int fat, int leftKcal, int leftProtein}) mealAiTargets(Meal meal, {required bool day}) {+ final goals = goalsFor(nutritionDay);+ final today = entriesOn(nutritionDay);+ final eaten = totalOn(nutritionDay);+ final leftK = math.max(0.0, goals.kcal - eaten.kcal);+ final leftP = math.max(0.0, goals.protein - eaten.protein);+ final leftC = math.max(0.0, goals.carbs - eaten.carbs);+ final leftF = math.max(0.0, goals.fat - eaten.fat);+ if (day) {+ return (kcal: goals.kcal, protein: goals.protein, carbs: goals.carbs, fat: goals.fat, leftKcal: leftK.round(), leftProtein: leftP.round());+ }+ final empty = mealSlots.where((s) => !today.any((e) => e.meal == s.meal)).length;+ final targetEmpty = !today.any((e) => e.meal == meal);+ final divisor = math.max(1, targetEmpty ? empty : empty + 1);+ final slots = math.max(1, mealSlots.length);+ double share(double left, num goal) => left > 0 ? left / divisor : goal / slots;+ int tidy(double v, int lo, int hi, int step) => ((v / step).round() * step).clamp(lo, hi);+ return (+ kcal: tidy(share(leftK, goals.kcal), 80, 1500, 10),+ protein: tidy(share(leftP, goals.protein), 5, 150, 1),+ carbs: tidy(share(leftC, goals.carbs), 5, 300, 1),+ fat: tidy(share(leftF, goals.fat), 3, 150, 1),+ leftKcal: leftK.round(),+ leftProtein: leftP.round(),+ );+ }+FoodEntry? logQuick(String name, Macros macros, {Meal? meal}) {if (macros.isEmpty) return null;final e = FoodEntry(@@ -1376,6 +1405,9 @@ mixin NutritionState on FitCore, ToolsState, StatsState {Supplement? addSupplement(String name, {String dose = '',+ double? amount,+ String unit = '',+ double? stock,String photo = '',int? at,int days = 0,@@ -1389,6 +1421,9 @@ mixin NutritionState on FitCore, ToolsState, StatsState {id: _newId('s'),name: clean,dose: dose.trim(),+ amount: amount != null && amount > 0 ? amount : null,+ unit: kSuppUnits.contains(unit) ? unit : '',+ stock: stock == null ? null : math.max(0.0, stock),photo: photo,at: at,days: days,@@ -1407,6 +1442,11 @@ mixin NutritionState on FitCore, ToolsState, StatsState {String id, {String? name,String? dose,+ double? amount,+ bool clearAmount = false,+ String? unit,+ double? stock,+ bool clearStock = false,String? photo,int? at,bool clearAt = false,@@ -1422,6 +1462,11 @@ mixin NutritionState on FitCore, ToolsState, StatsState {var next = old.copyWith(name: name == null || name.trim().isEmpty ? null : name.trim(),dose: dose?.trim(),+ amount: amount != null && amount > 0 ? amount : null,+ clearAmount: clearAmount || (amount != null && amount <= 0),+ unit: unit == null ? null : (kSuppUnits.contains(unit) ? unit : ''),+ stock: stock == null ? null : math.max(0.0, stock),+ clearStock: clearStock,photo: photo,at: at,clearAt: clearAt,@@ -1441,6 +1486,49 @@ mixin NutritionState on FitCore, ToolsState, StatsState {int? supplementTime(Supplement s) => s.at ?? supplementReminderMin;+ String suppUnitLabel(String unit, double amount) {+ final n = amount == 1 ? 1 : 2;+ return switch (unit) {+ 'capsule' => t.suppUnitCapsule(n),+ 'pill' => t.suppUnitPill(n),+ 'scoop' => t.suppUnitScoop(n),+ 'drop' => t.suppUnitDrop(n),+ 'serving' => t.suppUnitServing(n),+ 'iu' => t.suppUnitIu,+ 'g' || 'mg' || 'ml' => unit,+ _ => '',+ };+ }++ String suppAmountLabel(double amount, String unit) {+ final word = suppUnitLabel(unit, amount);+ final n = amount >= 1000 && amount == amount.roundToDouble() ? groupedInt(amount.round()) : fmt((amount * 100).round() / 100);+ return word.isEmpty ? n : '$n $word';+ }++ String suppDoseLabel(Supplement s) => s.amount == null ? s.dose : suppAmountLabel(s.amount!, s.unit);++ int? suppDaysLeft(Supplement s, {DateTime? from}) {+ final stock = s.stock;+ if (stock == null) return null;+ var takes = (stock / s.perTake + 1e-9).floor();+ final today = _dayKey(from ?? DateTime.now());+ final takenToday = takenOn(today).contains(s.id);+ for (var i = 0; i < 1000; i++) {+ final day = shiftDays(today, i);+ if (s.until != null && day.isAfter(s.until!)) return null;+ if (!s.dueOn(day) || (i == 0 && takenToday)) continue;+ if (takes == 0) return i;+ takes--;+ }+ return null;+ }++ bool suppRunningLow(Supplement s) {+ final left = suppDaysLeft(s);+ return left != null && left <= 7;+ }+List<Supplement> supplementsDueOn(DateTime day) => [for (final s in activeSupplements) if (s.dueOn(day)) s];void removeSupplement(String id) {@@ -1460,8 +1548,15 @@ mixin NutritionState on FitCore, ToolsState, StatsState {void toggleSupplement(String id) {final key = _dk(nutritionDay);final taken = supplementsTaken.putIfAbsent(key, () => <String>{});- if (!taken.remove(id)) taken.add(id);+ final marked = !taken.remove(id);+ if (marked) taken.add(id);if (taken.isEmpty) supplementsTaken.remove(key);+ final i = supplements.indexWhere((s) => s.id == id);+ final stock = i < 0 ? null : supplements[i].stock;+ if (stock != null) {+ final s = supplements[i];+ supplements[i] = s.copyWith(stock: math.max(0.0, stock + (marked ? -s.perTake : s.perTake)));+ }syncSupplementReminder();_persist();notifyListeners();@@ -1506,11 +1601,27 @@ mixin NutritionState on FitCore, ToolsState, StatsState {(at: d.at,names: [for (final s in d.items) s.name],- doses: [for (final s in d.items) if (s.dose.isNotEmpty) '${s.name} ${s.dose}'],+ doses: [+ for (final s in d.items)+ if (suppDoseLabel(s).isNotEmpty || _lowOn(s, d.at) != null)+ [+ if (suppDoseLabel(s).isNotEmpty) '${s.name} ${suppDoseLabel(s)}',+ ?_lowOn(s, d.at),+ ].join(' · '),+ ],),]);}+ String? _lowOn(Supplement s, DateTime at) {+ final left = suppDaysLeft(s);+ if (left == null) return null;+ final ahead = _dayKey(at).difference(_dayKey(DateTime.now())).inDays;+ final then = left - ahead;+ if (then > 7) return null;+ return then <= 0 ? t.suppRanOut : t.suppLeftFor(then);+ }+List<DateTime> get nutritionWeek {final start = shiftDays(nutritionDay, -((nutritionDay.weekday - weekStartDay + 7) % 7));return [for (var i = 0; i < 7; i++) shiftDays(start, i)];diff --git a/test/meal_ai_test.dart b/test/meal_ai_test.dartnew file mode 100644index 0000000..5fc58e7--- /dev/null+++ b/test/meal_ai_test.dart@@ -0,0 +1,390 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/models/nutrition.dart';+import 'package:gymmane/services/food_library.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/meal_ai.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ setUpAll(() {+ FoodLibrary.parse(File('assets/data/foods.tsv').readAsStringSync());+ });++ List<AiDraftOption> resolve(String raw, {bool day = false, Meal meal = Meal.snacks, List<FoodItem> own = const []}) =>+ resolveMealAi(parseMealAi(raw), lang: 'en', meal: meal, slots: kDefaultMeals, day: day, own: own);++ const brief = MealAiBrief(+ language: 'English',+ day: false,+ mealId: 'snacks',+ mealLabel: 'Snack',+ slots: [('breakfast', 'Breakfast'), ('lunch', 'Lunch'), ('dinner', 'Dinner'), ('snacks', 'Snack')],+ kcal: 300,+ protein: 25,+ carbs: 30,+ fat: 10,+ options: 3,+ tags: ['High protein', 'Quick'],+ notes: 'I have oats and eggs. No peanuts.',+ eaten: ['Oats', 'Milk'],+ );++ group('prompt', () {+ test('lleva el objetivo, las comidas, los gustos y las reglas', () {+ final p = buildMealAiPrompt(brief);+ expect(p, contains('about 300 kcal, 25 g protein, 30 g carbs and 10 g fat'));+ expect(p, contains('ONE meal only: Snack (id "snacks")'));+ expect(p, contains('"breakfast", "lunch", "dinner", "snacks"'));+ expect(p, contains('High protein, Quick'));+ expect(p, contains('I have oats and eggs. No peanuts.'));+ expect(p, contains('Already eaten today'));+ expect(p, contains('3 different options'));+ expect(p, contains('English'));+ expect(p, contains(kMealAiTag));+ });++ test('el ejemplo del prompt se lee solo con el mismo lector de la app', () {+ for (final day in [false, true]) {+ final p = buildMealAiPrompt(MealAiBrief(+ language: 'Español',+ day: day,+ mealId: brief.mealId,+ mealLabel: brief.mealLabel,+ slots: brief.slots,+ kcal: 2000,+ protein: 150,+ carbs: 200,+ fat: 60,+ options: 1,+ ));+ final reply = parseMealAi(p);+ expect(reply.itemCount, 2, reason: 'day=$day');+ expect(reply.options.first.items.first.name, 'Greek yogurt');+ expect(reply.options.first.items.first.grams, 170);+ expect(reply.options.first.items.first.kcal, 100);+ }+ });++ test('una sola opción no pide varias y el día lo reparte', () {+ final one = buildMealAiPrompt(MealAiBrief(+ language: 'English',+ day: true,+ mealId: 'snacks',+ mealLabel: 'Snack',+ slots: brief.slots,+ kcal: 2200,+ protein: 140,+ carbs: 250,+ fat: 70,+ options: 1,+ ));+ expect(one, contains('a full day of eating'));+ expect(one, contains('Give 1 different option.'));+ expect(one, contains('Spread the foods across the meals'));+ });+ });++ group('lector', () {+ test('respuesta limpia con texto alrededor', () {+ final r = parseMealAi('Claro, aquí tienes:\n```json\n'+ '{"gymmane":"gymmane-meal","v":1,"options":[{"name":"Bowl","items":['+ '{"food":"Greek yogurt","grams":170,"kcal":100,"protein":17,"carbs":6,"fat":0.7,"meal":"snacks"}]}]}\n'+ '```\nEspero que te guste.');+ expect(r.options.length, 1);+ expect(r.options.first.name, 'Bowl');+ expect(r.options.first.items.single.protein, 17);+ });++ test('comillas tipográficas, comas finales y comentarios', () {+ final r = parseMealAi('{“options”: [ {“name”: “Plato”, “items”: [\n'+ ' {“food”: “Banana”, “grams”: 120, “kcal”: 107, “protein”: 1.3, “carbs”: 27, “fat”: 0.4,}, // fruta\n'+ ' /* otro */ {“food”: “Walnuts”, “grams”: 15, “kcal”: 98, “protein”: 2.3, “carbs”: 2.1, “fat”: 9.8},\n'+ ' ],},]}');+ expect(r.itemCount, 2);+ expect(r.options.first.items.last.name, 'Walnuts');+ });++ test('comillas simples, claves sin comillas y True/None', () {+ final r = parseMealAi("{options: [{name: 'Chef\\'s mix', items: [{food: 'Egg', grams: 60, kcal: 86, protein: 7.6, carbs: 0.4, fat: 5.7, liquid: False, note: None}]}]}");+ expect(r.itemCount, 1);+ expect(r.options.first.items.single.name, 'Egg');+ });++ test('cantidades con unidades y decimales con coma', () {+ final r = parseMealAi('{"items":['+ '{"food":"Milk","amount":"250 ml","kcal":"120 kcal","protein":"8,5 g","carbs":"12","fat":"4,8"},'+ '{"food":"Oats","quantity":"1/2 cup (45 g)","calories":170,"protein":6,"carbs":30,"fat":3},'+ '{"food":"Butter","grams":"1,5","kcal":11,"protein":0,"carbs":0,"fat":1.2},'+ '{"food":"Flour","weight":"2 oz","kcal":200,"protein":6,"carbs":42,"fat":1}]}');+ final items = r.options.first.items;+ expect(items[0].grams, 250);+ expect(items[0].liquid, isTrue);+ expect(items[0].protein, 8.5);+ expect(items[0].kcal, 120);+ expect(items[1].grams, 45);+ expect(items[2].grams, 1.5);+ expect(items[3].grams, closeTo(56.7, 0.01));+ });++ test('otros nombres de campos y macros anidados', () {+ final r = parseMealAi('{"menu":[{"title":"Cena","ingredients":['+ '{"name":"Salmon","grams":150,"nutrition":{"calories":280,"proteins":30,"carbohydrates":0,"fats":17}},'+ '{"alimento":"Arroz","gramos":"120 g","macros":{"kcal":156,"proteina":3,"hidratos":34,"grasa":0.4}}]}]}');+ expect(r.options.first.name, 'Cena');+ final items = r.options.first.items;+ expect(items[0].kcal, 280);+ expect(items[0].protein, 30);+ expect(items[0].fat, 17);+ expect(items[1].name, 'Arroz');+ expect(items[1].grams, 120);+ expect(items[1].carbs, 34);+ });++ test('lista suelta de alimentos y valores por 100 g', () {+ final list = parseMealAi('[{"food":"Banana","grams":100,"kcal":89,"protein":1,"carbs":23,"fat":0.3}]');+ expect(list.itemCount, 1);+ final per = parseMealAi('{"items":[{"food":"Rice","grams":200,"per100":{"kcal":130,"protein":2.7,"carbs":28,"fat":0.3}}]}');+ final f = per.options.first.items.single;+ expect(f.per100, isTrue);+ expect(f.kcal, 130);+ });++ test('un día entero por comidas', () {+ final r = parseMealAi('{"day":{"breakfast":[{"food":"Oats","grams":60,"kcal":227,"protein":8,"carbs":40,"fat":4}],'+ '"dinner":{"items":[{"food":"Salmon","grams":150,"kcal":280,"protein":30,"carbs":0,"fat":17}]}}}');+ expect(r.options.length, 1);+ final items = r.options.first.items;+ expect(items.map((e) => e.meal), ['breakfast', 'dinner']);+ });++ test('respuesta cortada: se queda con lo completo', () {+ final r = parseMealAi('{"options":[{"name":"A","items":['+ '{"food":"Banana","grams":120,"kcal":107,"protein":1.3,"carbs":27,"fat":0.4,"meal":"snacks"},'+ '{"food":"Almonds","grams":20,"kcal":116,"protein":4,"carbs":4');+ expect(r.truncated, isTrue);+ expect(r.itemCount, 2);+ });++ test('varios bloques: se queda con el más grande', () {+ final r = parseMealAi('Ejemplo: {"food":"x","grams":1,"kcal":1}\n'+ 'Respuesta: {"options":[{"items":[{"food":"Banana","grams":120,"kcal":107},{"food":"Egg","grams":60,"kcal":86}]}]}');+ expect(r.itemCount, 2);+ });++ test('si el JSON exterior está roto rescata los alimentos sueltos', () {+ final r = parseMealAi('options = ( {"food":"Banana","grams":120,"kcal":107,"protein":1,"carbs":27,"fat":0.4} ;; '+ '{"food":"Egg","grams":60,"kcal":86,"protein":7.6,"carbs":0.4,"fat":5.7} )');+ expect(r.itemCount, 2);+ });++ test('texto que no es una comida no da nada', () {+ for (final raw in ['', 'hola', '{}', '[]', '{"options": []}', '{"a": 1, "b": [1, 2]}', '```json\n```', '{{{{', '}}}}']) {+ expect(parseMealAi(raw).isEmpty, isTrue, reason: raw);+ }+ });++ test('no se cuelga con basura enorme ni con anidación absurda', () {+ expect(parseMealAi('[' * 5000).isEmpty, isTrue);+ expect(parseMealAi('{"a":' * 3000).isEmpty, isTrue);+ expect(parseMealAi('{' * 10000 + '}' * 10000).isEmpty, isTrue);+ });++ test('limita opciones y alimentos', () {+ final items = [for (var i = 0; i < 80; i++) '{"food":"Item $i","grams":10,"kcal":10,"protein":1,"carbs":1,"fat":0}'].join(',');+ final options = [for (var i = 0; i < 12; i++) '{"name":"O$i","items":[$items]}'].join(',');+ final r = parseMealAi('{"options":[$options]}');+ expect(r.options.length, kMealAiMaxOptions);+ expect(r.options.first.items.length, kMealAiMaxItems);+ });+ });++ group('estado', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ });++ test('el objetivo de una comida reparte lo que queda entre las comidas vacías', () {+ final all = fit.mealAiTargets(Meal.snacks, day: true);+ final goals = fit.goalsFor(fit.nutritionDay);+ expect(all.kcal, goals.kcal);+ final one = fit.mealAiTargets(Meal.snacks, day: false);+ expect(one.kcal, closeTo(goals.kcal / fit.mealSlots.length, 10));+ expect(one.leftKcal, goals.kcal);+ fit.logQuick('Algo', const Macros(kcal: 500, protein: 20), meal: Meal.breakfast);+ final after = fit.mealAiTargets(Meal.snacks, day: false);+ expect(after.leftKcal, goals.kcal - 500);+ expect(after.kcal, closeTo((goals.kcal - 500) / (fit.mealSlots.length - 1), 10));+ });++ test('lo importado se guarda en su comida con valores, gramos y foto de la biblioteca', () {+ final o = resolve('{"items":[{"food":"Greek yogurt","grams":170,"kcal":100,"protein":17,"carbs":6,"fat":0.7},'+ '{"food":"protein pudding","grams":200,"kcal":180,"protein":24,"carbs":14,"fat":3}]}',+ meal: Meal.dinner)+ .single;+ final added = fit.logEntries([for (final d in o.chosen) d.entry], Meal.dinner);+ expect(added.length, 2);+ final today = fit.entriesOn(fit.nutritionDay);+ expect(today.every((e) => e.meal == Meal.dinner), isTrue);+ expect(today.map((e) => e.name), containsAll(['Greek Yogurt', 'Protein pudding']));+ expect(fit.totalOn(fit.nutritionDay).kcal, closeTo(73 * 1.7 + 180, 1));+ expect(fit.photoForEntry(today.firstWhere((e) => e.foodId == 'a:greek-yogurt')), isNotEmpty);+ });++ test('guardado como receta y como plan', () {+ final o = resolve('{"items":[{"food":"Banana","grams":100,"kcal":89,"protein":1,"carbs":23,"fat":0.3},'+ '{"food":"Egg","grams":60,"kcal":86,"protein":7.6,"carbs":0.4,"fat":5.7}]}')+ .single;+ final r = fit.saveRecipe('Mi picoteo', [for (final d in o.chosen) d.entry]);+ expect(r, isNotNull);+ expect(r!.items.length, 2);+ final plan = fit.saveMealPlan(+ MealPlan(id: '', name: 'IA', items: [for (final d in o.chosen) d.entry.copyWith(id: fit.newPlanItemId())]),+ const {},+ );+ expect(fit.mealPlanById(plan.id)!.items.length, 2);+ });+ });++ group('resolución', () {+ test('un alimento de la biblioteca usa sus valores y su foto', () {+ final o = resolve('{"items":[{"food":"Greek yogurt","grams":170,"kcal":100,"protein":17,"carbs":6,"fat":0.7}]}').single;+ final d = o.items.single;+ expect(d.source, AiSource.library);+ expect(d.entry.foodId, 'a:greek-yogurt');+ expect(d.entry.meal, Meal.snacks);+ expect(d.total.kcal, closeTo(73 * 1.7, 0.5));+ expect(d.flags, isEmpty);+ expect(d.on, isTrue);+ });++ test('nombres en español, plurales y descripciones se encuentran', () {+ final r = resolveMealAi(+ parseMealAi('{"items":[{"food":"Huevos","grams":120,"kcal":172,"protein":15,"carbs":1,"fat":11},'+ '{"food":"Walnuts (shelled)","grams":20,"kcal":131,"protein":3,"carbs":3,"fat":13},'+ '{"food":"Rolled oats, dry","grams":50,"kcal":190,"protein":7,"carbs":34,"fat":3}]}'),+ lang: 'es',+ meal: Meal.breakfast,+ slots: kDefaultMeals,+ ).single;+ expect(r.items.map((e) => e.entry.foodId), ['a:egg', 'a:walnuts', 'a:rolled-oats']);+ expect(r.items.every((e) => e.source == AiSource.library), isTrue);+ });++ test('si los números de la IA no cuadran con la biblioteca se queda con los de la IA', () {+ final d = resolve('{"items":[{"food":"Banana","grams":100,"kcal":400,"protein":2,"carbs":90,"fat":1}]}').single.items.single;+ expect(d.source, AiSource.ai);+ expect(d.entry.foodId, isEmpty);+ expect(d.total.kcal, 400);+ });++ test('un alimento que no existe entra con los valores de la IA', () {+ final d = resolve('{"items":[{"food":"protein pudding","grams":200,"kcal":180,"protein":24,"carbs":14,"fat":3}]}')+ .single+ .items+ .single;+ expect(d.source, AiSource.ai);+ expect(d.entry.name, 'Protein pudding');+ expect(d.entry.totalGrams, 200);+ expect(d.total.protein, 24);+ expect(d.on, isTrue);+ });++ test('calorías que no cuadran con los macros se corrigen y se avisa', () {+ final d = resolve('{"items":[{"food":"mystery bar","grams":50,"kcal":900,"protein":10,"carbs":20,"fat":8}]}').single.items.single;+ expect(d.flags, contains(AiFlag.adjusted));+ expect(d.total.kcal, 10 * 4 + 20 * 4 + 8 * 9);+ });++ test('si faltan las calorías se calculan con los macros', () {+ final d = resolve('{"items":[{"food":"mystery bar","grams":50,"protein":10,"carbs":20,"fat":8}]}').single.items.single;+ expect(d.total.kcal, 192);+ expect(d.flags, isNot(contains(AiFlag.noValues)));+ });++ test('lo imposible o sin valores queda apagado por defecto', () {+ final o = resolve('{"items":['+ '{"food":"magic powder","grams":10,"kcal":900,"protein":50,"carbs":50,"fat":50},'+ '{"food":"mystery thing","grams":100},'+ '{"food":"lead brick","grams":100,"kcal":4000,"protein":0,"carbs":0,"fat":300}]}').single;+ expect(o.items[0].risky, isTrue);+ expect(o.items[0].on, isFalse);+ expect(o.items[1].usable, isFalse);+ expect(o.items[1].on, isFalse);+ expect(o.items[2].risky, isTrue);+ expect(o.chosen, isEmpty);+ expect(o.total.kcal, 0);+ });++ test('lo cocinado usa el peso cocinado de la biblioteca', () {+ final d = resolve('{"items":[{"food":"Chicken breast, grilled","grams":150,"kcal":200,"protein":38,"carbs":0,"fat":4}]}')+ .single+ .items+ .single;+ expect(d.source, AiSource.library);+ expect(d.entry.cooked, 0.75);+ expect(d.total.kcal, closeTo(120 * 150 / 0.75 / 100, 0.5));+ expect(d.shownGrams, closeTo(150, 0.01));+ });++ test('una comida: ignora la comida que ponga la IA y usa la pedida', () {+ final d = resolve('{"items":[{"food":"Banana","grams":100,"kcal":89,"protein":1,"carbs":23,"fat":0.3,"meal":"dinner"}]}',+ meal: Meal.snacks)+ .single+ .items+ .single;+ expect(d.entry.meal, Meal.snacks);+ });++ test('un día: reparte por comidas, con sinónimos y con una desconocida a la de por defecto', () {+ final o = resolve('{"day":{"desayuno":[{"food":"Banana","grams":100,"kcal":89,"protein":1,"carbs":23,"fat":0.3}],'+ '"Almuerzo":[{"food":"Egg","grams":60,"kcal":86,"protein":7.6,"carbs":0.4,"fat":5.7}],'+ '"cena":[{"food":"Almonds","grams":20,"kcal":116,"protein":4,"carbs":4,"fat":10}],'+ '"postre ligero":[{"food":"Banana","grams":50,"kcal":45,"protein":0.5,"carbs":11,"fat":0.2}],'+ '"zzz":[{"food":"Egg","grams":30,"kcal":43,"protein":3.8,"carbs":0.2,"fat":2.8}]}}',+ day: true,+ meal: Meal.lunch)+ .single;+ expect(o.items.map((e) => e.entry.meal.id), ['breakfast', 'lunch', 'dinner', 'snacks', 'lunch']);+ });++ test('un alimento propio gana a la biblioteca', () {+ const mine = FoodItem(+ id: 'f1',+ name: 'Greek yogurt',+ grams: 100,+ macros: Macros(kcal: 60, protein: 10, carbs: 4, fat: 0.2),+ );+ final d = resolve('{"items":[{"food":"greek yogurt","grams":200,"kcal":120,"protein":20,"carbs":8,"fat":0.4}]}', own: [mine])+ .single+ .items+ .single;+ expect(d.source, AiSource.mine);+ expect(d.entry.foodId, 'f1');+ expect(d.total.kcal, 120);+ });++ test('con piezas usa el peso de la pieza de la biblioteca', () {+ final d = resolve('{"items":[{"food":"Banana","count":2,"kcal":214,"protein":2.6,"carbs":54,"fat":0.7}]}').single.items.single;+ expect(d.source, AiSource.library);+ expect(d.entry.totalGrams, 240);+ });++ test('cambiar los gramos reescala sin romper nada', () {+ final lib = resolve('{"items":[{"food":"Greek yogurt","grams":100,"kcal":73,"protein":10,"carbs":4,"fat":2}]}').single.items.single;+ final before = lib.total.kcal;+ lib.scaleTo(200);+ expect(lib.total.kcal, closeTo(before * 2, 0.01));+ expect(lib.shownGrams, closeTo(200, 0.01));+ final ai = resolve('{"items":[{"food":"protein pudding","grams":200,"kcal":180,"protein":24,"carbs":14,"fat":3}]}').single.items.single;+ ai.scaleTo(100);+ expect(ai.total.kcal, closeTo(90, 0.01));+ expect(ai.total.protein, closeTo(12, 0.01));+ expect(ai.entry.totalGrams, closeTo(100, 0.01));+ });+ });+}