// Food: one day — ‹ day ›, the week strip, the energy ring (eaten ÷ target, split by where the energy // came from: protein / carbs / fat) + the nutrient bars, and the four meals (tap a food = edit it, // long-press = drag it to another meal, + = add to that meal), Make a meal. Days up to 60 ahead for // planning, like the web page. import 'dart:math'; import 'package:flutter/material.dart'; import '../app/sync_service.dart'; import '../app/theme.dart'; import 'cycle_model.dart' show plus, today, daysBetween; import 'food_model.dart'; import 'food_sheet.dart'; import 'meal_builder.dart'; import 'summaries.dart'; import 'sugar.dart'; const proteinC = Color(0xFF5CC8FF), carbsC = Color(0xFFFFB33A), fatC = Color(0xFFC792EA); const macroColors = {'protein': proteinC, 'carbs': carbsC, 'fat': fatC}; const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const _dow = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; const ahead = 60; /// P / C / F as coloured dots + grams (the web page's macDots). Widget macroDots(Map t, {double size = 12.5}) => Row(mainAxisSize: MainAxisSize.min, children: [ for (final m in macros) ...[ Icon(Icons.circle, size: 7, color: macroColors[m]), Padding(padding: const EdgeInsets.only(left: 2, right: 7), child: Text('${(t[m] ?? 0).round()}', style: TextStyle(fontSize: size, color: muted))), ], ]); class FoodPage extends StatefulWidget { const FoodPage({super.key, required this.sync}); final SyncService sync; @override State createState() => _FoodPageState(); } class _FoodPageState extends State { DateTime d = today(); FoodDb? fdb; FoodSettings get s => FoodSettings.of(widget.sync.store); // Settings ▸ Food on the dashboard @override void initState() { super.initState(); FoodDb.open().then((x) => mounted ? setState(() => fdb = x) : null); } String _title() { final n = daysBetween(today(), d); final name = n == 0 ? 'Today' : n == -1 ? 'Yesterday' : n == 1 ? 'Tomorrow' : _dow[d.weekday - 1]; return '$name · ${d.day} ${_mon[d.month - 1]}${d.year != today().year ? ' ${d.year}' : ''}'; } Future _sheet({Entry? e, String? meal}) => showModalBottomSheet( context: context, isScrollControlled: true, backgroundColor: card, builder: (_) => FoodSheet(sync: widget.sync, fdb: fdb, day: dayIso(d), meal: meal ?? e?.meal ?? _mealNow(), entry: e), ); Future _makeMeal(List es) async { final picked = es.isEmpty ? [] : await pickEntries(context, es); if (picked == null || !mounted) return; Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: widget.sync, fdb: fdb, fromEntries: picked))); } static String _mealNow() { final h = DateTime.now().hour; return h < 10 ? 'breakfast' : h < 15 ? 'lunch' : h < 21 ? 'dinner' : 'snack'; } @override Widget build(BuildContext context) => ListenableBuilder( listenable: widget.sync, builder: (context, _) { final store = widget.sync.store; final es = entriesOn(store, dayIso(d)); final tg = targets(store, s); return LayoutBuilder(builder: (context, box) { final wide = box.maxWidth >= 700; final head = [_nav(), const SizedBox(height: 6), _week(tg['kcal']!.$1), const SizedBox(height: 10), FoodDayCard(sync: widget.sync, day: d, fdb: fdb)]; final meals = [ for (final m in [...mealKeys, if (es.any((e) => e.meal == '')) '']) Padding(padding: const EdgeInsets.only(bottom: 10), child: _meal(m, es.where((e) => e.meal == m).toList())), OutlinedButton.icon( onPressed: () => _makeMeal(es), icon: const Icon(Icons.soup_kitchen_outlined), label: Text(es.isEmpty ? 'Make a meal' : 'Make a meal (from this day’s entries)'), ), ]; // the arrows go by week; a swipe sideways goes by day return GestureDetector( onHorizontalDragEnd: (e) { final v = e.primaryVelocity ?? 0; if (v.abs() < 300) return; if (v > 0) { setState(() => d = plus(d, -1)); } else if (daysBetween(today(), d) < ahead) { setState(() => d = plus(d, 1)); } }, child: ListView(padding: const EdgeInsets.fromLTRB(12, 10, 12, 24), children: [ if (wide) Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded(child: Column(children: head)), const SizedBox(width: 12), Expanded(child: Column(children: meals)), ]) else ...[...head, const SizedBox(height: 10), ...meals], ]), ); }); }, ); Widget _nav() => Row(children: [ IconButton(tooltip: 'Week before', onPressed: () => setState(() => d = plus(d, -7)), icon: const Icon(Icons.chevron_left)), Expanded( child: GestureDetector( onTap: () => setState(() => d = today()), child: Text(_title(), textAlign: TextAlign.center, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), ), ), IconButton( tooltip: 'Week after', onPressed: daysBetween(today(), d) + 7 <= ahead ? () => setState(() => d = plus(d, 7)) : null, icon: const Icon(Icons.chevron_right)), ]); Widget _week(double target) { final mon = plus(d, -(d.weekday - 1)); final k = kcalByDay(widget.sync.store, dayIso(mon), dayIso(plus(mon, 6))); final m = dayTotals(widget.sync.store, dayIso(mon), dayIso(plus(mon, 6))); return Row(children: [ for (var i = 0; i < 7; i++) () { final x = plus(mon, i), kc = k[dayIso(x)]; final h = min(1.15, (kc ?? 0) / target); final sel = x == d, over = kc != null && kc > target * 1.05; return Expanded( child: GestureDetector( onTap: () => setState(() => d = x), child: Container( margin: const EdgeInsets.symmetric(horizontal: 2), padding: const EdgeInsets.symmetric(vertical: 5), decoration: BoxDecoration(color: sel ? card2 : null, borderRadius: BorderRadius.circular(8)), child: Column(children: [ Text(_dow[i].substring(0, 2), style: TextStyle(fontSize: 11.5, color: x == today() ? accent : muted)), const SizedBox(height: 3), Container( width: 12, height: 32, alignment: Alignment.bottomCenter, clipBehavior: Clip.antiAlias, decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(3)), child: FractionallySizedBox(heightFactor: h / 1.15, child: _macroFill(m[dayIso(x)], kc)), ), const SizedBox(height: 2), Text(kc == null ? '' : '${kc.round()}', style: TextStyle(fontSize: 10.5, color: over ? bad : muted, fontWeight: over ? FontWeight.bold : null)), ]), ), ), ); }(), ]); } /// A week pill's fill, bottom up: protein / carbs / fat by their share of the energy, the rest grey /// (views._macro_segs — as the History chart stacks them). Widget _macroFill(Map? t, double? kcal) { if (t == null || kcal == null || kcal <= 0) return const SizedBox(); final e = {for (final k in macros) k: (t[k] ?? 0) * kcalPerG[k]!}; final total = max(kcal, e.values.fold(0, (a, b) => a + b)); final rest = total - e.values.fold(0, (a, b) => a + b); return Column(children: [ if (rest / total > 0.005) Expanded(flex: (rest / total * 1000).round(), child: Container(color: muted.withValues(alpha: 0.5))), for (final k in macros.reversed) if (e[k]! > 0) Expanded(flex: (e[k]! / total * 1000).round(), child: Container(color: macroColors[k])), ]); } Widget _meal(String m, List es) { final t = totals(es); // a long-pressed food can be dropped on another meal's card (db.move: only the meal changes) return DragTarget( onWillAcceptWithDetails: (d) => m != '' && d.data.meal != m, onAcceptWithDetails: (d) { moveEntry(widget.sync.store, d.data.u, m); widget.sync.changed(); }, builder: (context, cand, _) => Card( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12), side: cand.isNotEmpty ? const BorderSide(color: accent, width: 2) : BorderSide.none), child: Padding( padding: const EdgeInsets.fromLTRB(14, 6, 6, 8), child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row(children: [ Text(mealLabels[m]!, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), const SizedBox(width: 10), if (es.isNotEmpty) Text('${(t['kcal'] ?? 0).round()} kcal', style: const TextStyle(color: accent)), const Spacer(), if (es.isNotEmpty) macroDots(t), if (m != '') IconButton(tooltip: 'Add to ${mealLabels[m]!.toLowerCase()}', onPressed: () => _sheet(meal: m), icon: const Icon(Icons.add_circle_outline, color: accent)), ]), if (es.isEmpty && m != '') InkWell( onTap: () => _sheet(meal: m), child: const Padding(padding: EdgeInsets.symmetric(vertical: 6), child: Text('Nothing yet — add', style: TextStyle(color: muted))), ), for (final e in es) LongPressDraggable( data: e, feedback: Material( color: card2, borderRadius: BorderRadius.circular(10), elevation: 6, child: Padding(padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), child: Text('${e.name} · ${e.kcal.round()} kcal', style: const TextStyle(color: Colors.white))), ), childWhenDragging: Opacity(opacity: 0.35, child: _row(e)), child: InkWell(onTap: () => _sheet(e: e), child: _row(e)), ), ]), ), ), ); } Widget _row(Entry e) => Padding( padding: const EdgeInsets.fromLTRB(0, 6, 8, 6), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(e.name), Row(children: [ if (e.portion.isNotEmpty) Padding(padding: const EdgeInsets.only(right: 8), child: Text(e.portion, style: const TextStyle(color: muted, fontSize: 12.5))), macroDots({for (final k in macros) k: e.n(k)}, size: 11.5), ]), ])), Text('${e.kcal.round()}', style: const TextStyle(fontWeight: FontWeight.bold)), ]), ); } /// The energy ring (views.ring): as far round as eaten ÷ target, split by the macros' share of /// the energy; past 105 % the track turns red. /// The day's energy ring (eaten ÷ target, split by macro), what's left, burned (Health) and the nutrient /// bars — the Food page's top card, also on Health ▸ Overview. class FoodDayCard extends StatelessWidget { const FoodDayCard({super.key, required this.sync, required this.day, this.fdb}); final SyncService sync; final DateTime day; final FoodDb? fdb; FoodSettings get s => FoodSettings.of(sync.store); @override Widget build(BuildContext context) { final store = sync.store; final es = entriesOn(store, dayIso(day)); final t = totals(es); if (fdb != null) { final fs = AddedSugar(store, fdb); t['added_sugar'] = es.fold(0, (a, e) => a + fs.entry(e)); } return _ringCard(t, targets(store, s), plan(store, s), es.isNotEmpty); } Widget _ringCard(Map t, Map tg, Plan p, bool any) { final target = tg['kcal']!.$1, kcal = t['kcal'] ?? 0, left = target - kcal; final rows = [('protein', 'Protein', 'g'), ('carbs', 'Carbs', 'g'), ('fat', 'Fat', 'g'), ('fiber', 'Fibre', 'g'), ('sugar', 'Sugar', 'g'), if (t['added_sugar'] != null) ('added_sugar', 'Added sugar ≈', 'g'), ('sat_fat', 'Saturated fat', 'g'), ('sodium_mg', 'Sodium', 'mg')]; return Card( child: Padding( padding: const EdgeInsets.all(14), child: Column(children: [ Row(children: [ Tooltip( triggerMode: TooltipTriggerMode.tap, showDuration: const Duration(seconds: 8), message: 'Target ${target.round()} kcal: ${p.basis}' '${p.maint != null ? ' = ${p.maint} kcal, minus ${p.deficit} to lose 0.5 % a week' : ''}' '${p.capped ? ' (limited)' : ''}.', child: SizedBox( width: 120, height: 120, child: CustomPaint( painter: _Ring(t, target), child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [ Text('${kcal.round()}', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), Text('of ${target.round()} kcal', style: const TextStyle(fontSize: 11.5, color: muted)), ])), ), ), ), const SizedBox(width: 16), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(left >= 0 ? '${left.round()} left' : '${(-left).round()} over', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: kcal > target * 1.05 ? bad : null)), const SizedBox(height: 6), if (any) macroDots(t, size: 14) else const Text('Nothing logged yet', style: TextStyle(color: muted)), ..._burned(kcal, any), ])), ]), const SizedBox(height: 12), for (final (k, label, unit) in rows) _bar(label, unit, t[k], tg[k]!, macroColors[k]), ]), ), ); } /// The day's activity from Health (the Pi's summary): "Burned ≈ N kcal" (breakdown on tap) and /// eaten − burned (only when something's logged) — past days and today ("so far"). List _burned(double kcal, bool any) { if (day.isAfter(today())) return []; final e = (Summaries(sync.store).day(dayIso(day))?['energy'] as Map?)?.cast(); if (e == null) return []; final total = (e['total'] as num).toDouble(), bal = kcal - total; return [ const SizedBox(height: 8), Tooltip( triggerMode: TooltipTriggerMode.tap, message: 'Resting ${e['bmr']} + walking ${e['walk']} + workouts ${e['workouts']} kcal — estimated from your band', child: Text('Burned ≈ ${total.round()} kcal${day == today() ? ' so far' : ''}', style: const TextStyle(color: muted)), ), if (any) Text('eaten − burned ${bal >= 0 ? '+' : '−'}${bal.abs().round()}', style: TextStyle(color: bal <= 0 ? good : accent, fontWeight: FontWeight.bold)), ]; } Widget _bar(String label, String unit, double? v, (double, String) tg, Color? c) { final (target, kind) = tg; if (kind == 'info') { // total sugar: the value, no limit return Tooltip( triggerMode: TooltipTriggerMode.tap, message: 'All sugar, natural sugar included (fruit, vegetables, milk) — the limit is on added sugar, below.', child: Padding( padding: const EdgeInsets.symmetric(vertical: 3.5), child: Row(children: [ SizedBox(width: 104, child: Text(label, style: const TextStyle(color: muted, fontSize: 13.5))), const Spacer(), Text('${v == null ? '—' : v.round()} $unit', style: const TextStyle(fontSize: 12.5)), ]), ), ); } final frac = target > 0 ? (v ?? 0) / target : 0.0; final over = kind == 'max' && (v ?? 0) > target, ok = kind == 'min' && (v ?? 0) >= target, high = kind == 'goal' && (v ?? 0) > target * 1.15; final color = over || high ? bad : ok ? good : (c ?? muted); final word = kind == 'min' ? 'at least ' : kind == 'max' ? 'at most ' : ''; final row = Padding( padding: const EdgeInsets.symmetric(vertical: 3.5), child: Row(children: [ SizedBox(width: 104, child: Text(label, style: const TextStyle(color: muted, fontSize: 13.5))), Expanded( child: ClipRRect( borderRadius: BorderRadius.circular(4), child: LinearProgressIndicator(value: min(1.0, frac), minHeight: 8, backgroundColor: card2, color: color), ), ), SizedBox( width: 118, child: Text('${v == null ? '—' : v.round()} / $word${target.round()} $unit', textAlign: TextAlign.right, style: TextStyle(fontSize: 12.5, color: over || high ? bad : null)), ), ]), ); if (label != 'Added sugar ≈') return row; return Tooltip( triggerMode: TooltipTriggerMode.tap, showDuration: const Duration(seconds: 8), message: 'Added sugar, estimated: sugar, honey, syrups added to food, plus fruit juice (WHO\'s "free sugars") — ' 'not the sugar inside whole fruit, ' 'vegetables and plain milk / yogurt. WHO: under 10 % of the energy.', child: row, ); } } class _Ring extends CustomPainter { _Ring(this.t, this.target); final Map t; final double target; @override void paint(Canvas c, Size size) { final r = size.width / 2 - 8, o = Offset(size.width / 2, size.height / 2); final kcal = t['kcal'] ?? 0; final over = kcal > target * 1.05; // rounded ends like the web page's ring (stroke-linecap: round) Paint p(Color col, {StrokeCap cap = StrokeCap.round}) => Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = 11..strokeCap = cap; c.drawCircle(o, r, p(over ? bad.withValues(alpha: .45) : card2, cap: StrokeCap.butt)); final frac = target > 0 ? min(1.0, kcal / target) : 0.0; if (frac == 0) return; final energy = {for (final m in macros) m: (t[m] ?? 0) * kcalPerG[m]!}; final known = energy.values.reduce((a, b) => a + b); final rect = Rect.fromCircle(center: o, radius: r); var at = -pi / 2; if (known == 0) { c.drawArc(rect, at, frac * 2 * pi, false, p(accent)); return; } // thin separators between the macros only (views.ring's gap: 0.006 of the circle each side), none at 12 o'clock final gap = frac > 0.05 ? 0.006 * 2 * pi : 0.0; final parts = [for (final m in macros) if (energy[m]! > 0) m]; for (var i = 0; i < parts.length; i++) { final sweep = frac * energy[parts[i]]! / known * 2 * pi; final g0 = i == 0 ? 0.0 : gap, g1 = i == parts.length - 1 ? 0.0 : gap; if (sweep > g0 + g1) c.drawArc(rect, at + g0, sweep - g0 - g1, false, p(macroColors[parts[i]]!)); at += sweep; } } @override bool shouldRepaint(covariant _Ring old) => true; }