dashPi: a self-hosted home dashboard, its sync server and phone app
The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
fb3c01cdd7
333 changed files with 45151 additions and 0 deletions
401
app/lib/health/activity_page.dart
Normal file
401
app/lib/health/activity_page.dart
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
// Health ▸ Activity (as on the web page's Activity tab), from the Pi's summaries: tiles (steps, workouts,
|
||||
// fitness · form, vitality), steps and energy per day, training (fitness / fatigue / form) and the
|
||||
// workouts — tap one for its heart rate on the zone bands and time in zones (WorkoutPage).
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import '../widgets/bar_chart.dart';
|
||||
import '../widgets/line_chart.dart';
|
||||
import 'body_page.dart' show dm, dmy;
|
||||
import 'cycle_model.dart' show iso, parseDay, today;
|
||||
import 'range.dart';
|
||||
import 'summaries.dart';
|
||||
|
||||
const vitalityGoal = 150; // intensity minutes a week (calc.VITALITY_GOAL, WHO)
|
||||
const zoneNames = ['Resting', 'Warm-up', 'Fat burn', 'Aerobic', 'Anaerobic', 'Maximum'];
|
||||
const zoneColors = [Color(0xFF4A5266), Color(0xFF8FA3BF), Color(0xFF5CC8FF), Color(0xFF7FD6A3), Color(0xFFFFB33A), Color(0xFFFF6B7A)];
|
||||
const _fitC = Color(0xFF5CC8FF), _fatC = Color(0xFFFF8FC8);
|
||||
|
||||
/// watch.FORM
|
||||
(String, String) formLabel(double v) => v < -30
|
||||
? ('Overload', 'fatigue far above fitness — rest soon')
|
||||
: v < -10
|
||||
? ('Building', 'training hard, fitness rising')
|
||||
: v < 10
|
||||
? ('Neutral', 'steady')
|
||||
: ('Fresh', 'rested, ready for a hard session');
|
||||
|
||||
/// watch.hm: minutes → "1h 05m"
|
||||
String hm(num? minutes) {
|
||||
if (minutes == null) return '—';
|
||||
final m = minutes.round();
|
||||
return '${m ~/ 60}h ${(m % 60).toString().padLeft(2, '0')}m';
|
||||
}
|
||||
|
||||
String thousands(num v) => v.round().toString().replaceAllMapped(RegExp(r'\B(?=(\d{3})+$)'), (_) => ',');
|
||||
|
||||
class ActivityPage extends StatelessWidget {
|
||||
const ActivityPage({super.key, required this.sync, required this.range});
|
||||
final SyncService sync;
|
||||
final HealthRange range;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: Listenable.merge([sync, range]),
|
||||
builder: (context, _) {
|
||||
final sm = Summaries(sync.store);
|
||||
final days = sm.all('day');
|
||||
final wks = sm.all('workout');
|
||||
if (days.isEmpty && wks.isEmpty) {
|
||||
return const Center(child: Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Text('Nothing from the band yet — it comes from the dashboard once it has synced.',
|
||||
textAlign: TextAlign.center, style: TextStyle(color: muted)),
|
||||
));
|
||||
}
|
||||
final now = today();
|
||||
final first = parseDay([...days, ...wks].map((x) => x['_day'] as String).reduce((a, b) => a.compareTo(b) < 0 ? a : b));
|
||||
final a = range.from(first, now);
|
||||
bool inRange(Map x) => !parseDay(x['_day'] as String).isBefore(a);
|
||||
final rd = days.where(inRange).toList(), rw = wks.where(inRange).toList();
|
||||
DateTime at(Map x) => parseDay(x['_day'] as String);
|
||||
|
||||
final steps = [for (final x in rd) if (x['steps'] != null) (at(x), (x['steps'] as num).toDouble())];
|
||||
final energy = [
|
||||
for (final x in rd)
|
||||
if (x['energy'] != null && (x['steps'] != null || rw.any((w) => w['_day'] == x['_day'])))
|
||||
(at(x), ((x['energy'] as Map)['total'] as num).toDouble())
|
||||
];
|
||||
final todays = days.isNotEmpty && days.last['_day'] == iso(now) ? days.last : null;
|
||||
final train = [for (final x in days) if (x['fitness'] != null) x];
|
||||
final cur = train.isEmpty ? null : train.last;
|
||||
final vit = days.where((x) => now.difference(at(x)).inDays < 7).fold<num>(0, (s, x) => s + ((x['vitality'] as num?) ?? 0));
|
||||
double avg(List<(DateTime, double)> xs) => xs.isEmpty ? 0 : xs.map((p) => p.$2).reduce((p, q) => p + q) / xs.length;
|
||||
final mins = rw.fold<num>(0, (s, w) => s + (w['minutes'] as num)), kcal = rw.fold<num>(0, (s, w) => s + ((w['kcal'] as num?) ?? 0));
|
||||
final wide = MediaQuery.of(context).size.width >= 700;
|
||||
|
||||
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
|
||||
GridView.count(
|
||||
crossAxisCount: wide ? 4 : 2,
|
||||
shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
|
||||
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.75,
|
||||
children: [
|
||||
_tile('Steps', steps.isEmpty ? '—' : thousands(avg(steps)), 'a day · today ${todays?['steps'] == null ? '—' : thousands(todays!['steps'] as num)}',
|
||||
'The band\'s steps, the average day of the ${steps.length} days with steps in this period'),
|
||||
_tile('Workouts', '${rw.length}', '${hm(mins)} · ${thousands(kcal)} kcal',
|
||||
'Workouts in this period: their time and the energy above resting (from heart rate)'),
|
||||
_tile('Fitness · form', cur == null ? '—' : '${(cur['fitness'] as num).round()} · ${(cur['form'] as num).round()}',
|
||||
cur == null ? 'no workouts yet' : formLabel((cur['form'] as num).toDouble()).$1,
|
||||
'Fitness = your training load over 42 days, fatigue over 7, form = fitness − fatigue.'
|
||||
'${cur == null ? '' : ' Now: ${formLabel((cur['form'] as num).toDouble()).$2}.'}'),
|
||||
_tile('Vitality', '${vit.round()} / $vitalityGoal', 'intensity minutes, 7 days',
|
||||
'Moderate minutes + 2 × vigorous ones, from the whole day\'s heart rate — WHO: at least 150 a week',
|
||||
color: vit >= vitalityGoal ? good : null),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_card('Steps', 'The band\'s steps per day (per week from 4 months: the average day)',
|
||||
BarChart(points: steps, from: a, to: now, color: good, range: range,
|
||||
fmt: (v) => '${thousands(v)} steps')),
|
||||
const SizedBox(height: 12),
|
||||
if (energy.isNotEmpty) ...[
|
||||
_card('Energy', 'Estimated energy a day: resting (Mifflin–St Jeor) + walking (steps outside workouts) '
|
||||
'+ workouts (heart rate). Average ${thousands(avg(energy))} kcal a day.',
|
||||
BarChart(points: energy, from: a, to: now, color: accent, fmt: (v) => '${thousands(v)} kcal')),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
if (train.isNotEmpty) ...[
|
||||
_card('Training', 'Fitness (42-day load), fatigue (7-day load) and form = fitness − fatigue. '
|
||||
'Below −10: building, below −30: overload; above 10: fresh.',
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Wrap(spacing: 14, children: [
|
||||
for (final (n, col) in [('Fitness', _fitC), ('Fatigue', _fatC), ('Form', accent)])
|
||||
Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Container(width: 10, height: 10, decoration: BoxDecoration(color: col, shape: BoxShape.circle)),
|
||||
const SizedBox(width: 5), Text(n, style: const TextStyle(color: muted, fontSize: 12.5)),
|
||||
]),
|
||||
]),
|
||||
const SizedBox(height: 6),
|
||||
LineChart(from: a, to: now, decimals: 0, series: [
|
||||
Series('Fitness', [for (final x in train) (at(x), (x['fitness'] as num).toDouble())], _fitC),
|
||||
Series('Fatigue', [for (final x in train) (at(x), (x['fatigue'] as num).toDouble())], _fatC),
|
||||
Series('Form', [for (final x in train) (at(x), (x['form'] as num).toDouble())], accent),
|
||||
]),
|
||||
])),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
_workouts(context, rw),
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
Widget _tile(String label, String value, String sub, String tip, {Color? color}) => Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
showDuration: const Duration(seconds: 6),
|
||||
message: tip,
|
||||
child: Card(child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||||
FittedBox(fit: BoxFit.scaleDown, child: Text(value, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: color))),
|
||||
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)),
|
||||
]),
|
||||
)),
|
||||
);
|
||||
|
||||
Widget _card(String title, String tip, Widget child) => Card(child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 8, 10, 10),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||||
_info(tip),
|
||||
]),
|
||||
child,
|
||||
]),
|
||||
));
|
||||
|
||||
Widget _workouts(BuildContext context, List<Map<String, dynamic>> rw) {
|
||||
final rows = rw.reversed.take(60).toList();
|
||||
return Card(child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 8, 10, 6),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
const Expanded(child: Text('Workouts', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||||
_info('Calories = above resting, from heart rate. Effect = this workout\'s load vs your usual one (6 weeks before). '
|
||||
'The strip = time in each heart-rate zone.'),
|
||||
]),
|
||||
if (rows.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 12), child: Text('None in this period', style: TextStyle(color: muted))),
|
||||
for (final w in rows)
|
||||
InkWell(
|
||||
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => WorkoutPage(w: w))),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
Expanded(child: Text(w['name'] as String, style: const TextStyle(fontWeight: FontWeight.bold))),
|
||||
Text('${(w['kcal'] as num?)?.round() ?? '—'} kcal', style: const TextStyle(color: accent)),
|
||||
]),
|
||||
Text([dmy(parseDay(w['_day'] as String)), hm(w['minutes'] as num), if (w['avg_hr'] != null) '${(w['avg_hr'] as num).round()} bpm', if (w['effect'] != null) w['effect']].join(' · '),
|
||||
style: const TextStyle(color: muted, fontSize: 12.5)),
|
||||
const SizedBox(height: 5),
|
||||
ZoneStrip(pct: ((w['zone_pct'] as List?) ?? const []).cast<num>()),
|
||||
]),
|
||||
),
|
||||
),
|
||||
if (rw.length > rows.length)
|
||||
Padding(padding: const EdgeInsets.only(bottom: 6), child: Text('… and ${rw.length - rows.length} more', style: const TextStyle(color: muted))),
|
||||
]),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Widget _info(String tip) => Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
showDuration: const Duration(seconds: 8),
|
||||
message: tip,
|
||||
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
|
||||
);
|
||||
|
||||
class ZoneStrip extends StatelessWidget {
|
||||
const ZoneStrip({super.key, required this.pct, this.height = 6});
|
||||
final List<num> pct;
|
||||
final double height;
|
||||
@override
|
||||
Widget build(BuildContext context) => ClipRRect(
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
child: SizedBox(height: height, child: Row(children: [
|
||||
for (var i = 0; i < pct.length && i < zoneColors.length; i++)
|
||||
if (pct[i] > 0) Expanded(flex: max(1, pct[i].round()), child: Container(color: zoneColors[i])),
|
||||
if (pct.every((p) => p <= 0)) Expanded(child: Container(color: card2)),
|
||||
])),
|
||||
);
|
||||
}
|
||||
|
||||
/// One workout (the web's workout page): stats, heart rate on the zone bands, time in zones.
|
||||
class WorkoutPage extends StatelessWidget {
|
||||
const WorkoutPage({super.key, required this.w});
|
||||
final Map<String, dynamic> w;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final start = DateTime.parse(w['start'] as String);
|
||||
final zones = ((w['zones'] as List?) ?? const []).cast<num>(), pct = ((w['zone_pct'] as List?) ?? const []).cast<num>();
|
||||
final bounds = ((w['bounds'] as List?) ?? const []).cast<num>();
|
||||
final hr = [for (final p in (w['hr'] as List? ?? const [])) ((p as List)[0] as num, p[1] as num)];
|
||||
String t(DateTime d) => d.toIso8601String().substring(11, 16);
|
||||
final end = DateTime.parse(w['end'] as String);
|
||||
final stats = [
|
||||
('Time', hm(w['minutes'] as num)),
|
||||
('Calories', '${(w['kcal'] as num?)?.round() ?? '—'} kcal'),
|
||||
('Average', w['avg_hr'] == null ? '—' : '${(w['avg_hr'] as num).round()} bpm'),
|
||||
('Highest', w['max_hr'] == null ? '—' : '${w['max_hr']} bpm'),
|
||||
if (w['distance'] != null) ('Distance', '${((w['distance'] as num) / 1000).toStringAsFixed(2)} km'),
|
||||
if (w['steps'] != null && (w['steps'] as num) > 0) ('Steps', thousands(w['steps'] as num)),
|
||||
if (w['load'] != null) ('Load', '${(w['load'] as num).round()}'),
|
||||
if (w['effect'] != null) ('Effect', w['effect'] as String),
|
||||
];
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(w['name'] as String)),
|
||||
body: ListView(padding: const EdgeInsets.all(12), children: [
|
||||
Text('${dm(start)} ${start.year} · ${t(start)} – ${t(end)}', style: const TextStyle(color: muted)),
|
||||
const SizedBox(height: 10),
|
||||
Card(child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Wrap(spacing: 18, runSpacing: 10, children: [
|
||||
for (final (l, v) in stats)
|
||||
Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
message: switch (l) {
|
||||
'Calories' => 'Above resting, from your heart rate (with resting: ${(w['kcal_total'] as num?)?.round() ?? '—'} kcal)',
|
||||
'Load' => 'Training load (TRIMP): minutes × how hard, from heart rate',
|
||||
'Effect' => 'This load vs your usual one (the workouts of the 6 weeks before${w['usual'] == null ? '' : ': ${(w['usual'] as num).round()}'})',
|
||||
_ => l,
|
||||
},
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(l.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11)),
|
||||
Text(v, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold)),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)),
|
||||
const SizedBox(height: 12),
|
||||
if (hr.length > 1)
|
||||
Card(child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 12, 12, 8),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
const Padding(padding: EdgeInsets.only(left: 6, bottom: 8), child: Text('Heart rate', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||||
_HrGraph(hr: hr, bounds: bounds, start: start, seconds: end.difference(start).inSeconds.toDouble()),
|
||||
]),
|
||||
)),
|
||||
const SizedBox(height: 12),
|
||||
if (zones.isNotEmpty)
|
||||
Card(child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
const Text('Time in zones', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 8),
|
||||
for (var i = zones.length - 1; i >= 0; i--)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(children: [
|
||||
SizedBox(width: 118, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(zoneNames[i]),
|
||||
Text(_range(i, bounds), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||||
])),
|
||||
Expanded(child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
child: LinearProgressIndicator(value: (i < pct.length ? pct[i] : 0) / 100, minHeight: 8,
|
||||
color: zoneColors[i], backgroundColor: card2),
|
||||
)),
|
||||
SizedBox(width: 90, child: Text('${(zones[i] / 60).round()} min · ${i < pct.length ? pct[i] : 0} %',
|
||||
textAlign: TextAlign.right, style: const TextStyle(fontSize: 12.5))),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
static String _range(int i, List<num> b) {
|
||||
if (b.isEmpty) return '';
|
||||
if (i == 0) return 'under ${b[0]}';
|
||||
return i < b.length ? '${b[i - 1]}–${b[i] - 1} bpm' : '${b[i - 1]}+ bpm';
|
||||
}
|
||||
}
|
||||
|
||||
class _HrGraph extends StatefulWidget {
|
||||
const _HrGraph({required this.hr, required this.bounds, required this.start, required this.seconds});
|
||||
final List<(num, num)> hr; // (seconds from start, bpm)
|
||||
final List<num> bounds;
|
||||
final DateTime start;
|
||||
final double seconds;
|
||||
@override
|
||||
State<_HrGraph> createState() => _HrGraphState();
|
||||
}
|
||||
|
||||
class _HrGraphState extends State<_HrGraph> {
|
||||
int? hit;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final h = hit == null ? null : widget.hr[hit!];
|
||||
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
LayoutBuilder(builder: (context, box) {
|
||||
void pick(Offset o) {
|
||||
final s = (o.dx - 34) / (box.maxWidth - 34) * widget.seconds;
|
||||
var best = 0;
|
||||
for (var i = 1; i < widget.hr.length; i++) {
|
||||
if ((widget.hr[i].$1 - s).abs() < (widget.hr[best].$1 - s).abs()) best = i;
|
||||
}
|
||||
setState(() => hit = best);
|
||||
}
|
||||
|
||||
return GestureDetector(
|
||||
onTapDown: (d) => pick(d.localPosition),
|
||||
onHorizontalDragUpdate: (d) => pick(d.localPosition),
|
||||
child: CustomPaint(size: Size(box.maxWidth, 200), painter: _HrPainter(widget, hit)),
|
||||
);
|
||||
}),
|
||||
SizedBox(
|
||||
height: 20,
|
||||
child: h == null
|
||||
? const Text('Tap the graph for a minute\'s heart rate', textAlign: TextAlign.center, style: TextStyle(color: muted, fontSize: 12.5))
|
||||
: Text('${(h.$1 / 60).floor()} min: ${h.$2} bpm', textAlign: TextAlign.center, style: const TextStyle(fontSize: 13)),
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
class _HrPainter extends CustomPainter {
|
||||
_HrPainter(this.g, this.hit);
|
||||
final _HrGraph g;
|
||||
final int? hit;
|
||||
|
||||
@override
|
||||
void paint(Canvas c, Size size) {
|
||||
const ml = 34.0, mb = 16.0, mt = 4.0;
|
||||
final vs = g.hr.map((p) => p.$2.toDouble());
|
||||
final lo = (min(vs.reduce(min), g.bounds.isEmpty ? 999 : g.bounds.first.toDouble()) / 10).floor() * 10.0 - 5;
|
||||
final hi = (vs.reduce(max) / 10).ceil() * 10.0 + 5;
|
||||
final h = size.height - mb - mt, w = size.width - ml;
|
||||
double y(double v) => mt + h - h * (v - lo) / (hi - lo);
|
||||
double x(num s) => ml + w * s / max(1, g.seconds);
|
||||
// zone bands (z1…z5), faint
|
||||
for (var i = 0; i < g.bounds.length; i++) {
|
||||
final top = i + 1 < g.bounds.length ? g.bounds[i + 1].toDouble() : hi;
|
||||
final a = y(min(top, hi)), b = y(max(g.bounds[i].toDouble(), lo));
|
||||
if (b > a) c.drawRect(Rect.fromLTRB(ml, a, size.width, b), Paint()..color = zoneColors[i + 1].withValues(alpha: .13));
|
||||
}
|
||||
final txt = const TextStyle(color: muted, fontSize: 10.5);
|
||||
void label(String s, Offset o, {bool right = false}) {
|
||||
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
|
||||
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
|
||||
}
|
||||
|
||||
for (var v = (lo / 20).ceil() * 20.0; v <= hi; v += 20) {
|
||||
label('${v.round()}', Offset(ml - 4, y(v)), right: true);
|
||||
}
|
||||
final mins = g.seconds / 60, every = mins <= 30 ? 5 : mins <= 75 ? 15 : mins <= 150 ? 30 : 60;
|
||||
for (var m = 0; m <= mins; m += every) {
|
||||
label('$m′', Offset(x(m * 60), size.height - mb + 3));
|
||||
}
|
||||
final path = Path();
|
||||
for (var i = 0; i < g.hr.length; i++) {
|
||||
final p = Offset(x(g.hr[i].$1), y(g.hr[i].$2.toDouble()));
|
||||
i == 0 ? path.moveTo(p.dx, p.dy) : path.lineTo(p.dx, p.dy);
|
||||
}
|
||||
c.drawPath(path, Paint()..color = const Color(0xFFFF6B7A)..strokeWidth = 2..style = PaintingStyle.stroke..strokeJoin = StrokeJoin.round);
|
||||
if (hit != null) {
|
||||
final p = Offset(x(g.hr[hit!].$1), y(g.hr[hit!].$2.toDouble()));
|
||||
c.drawLine(Offset(p.dx, mt), Offset(p.dx, size.height - mb), Paint()..color = muted.withValues(alpha: .5));
|
||||
c.drawCircle(p, 4, Paint()..color = Colors.white);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _HrPainter old) => true;
|
||||
}
|
||||
344
app/lib/health/body_model.dart
Normal file
344
app/lib/health/body_model.dart
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
// Body measurements + vitals — a port of the dashboard's plugins/health calc.py (formulas,
|
||||
// categories), views.py (latest per field, changes, series) and db.py (what a save does).
|
||||
// Keep them in step with the web pages.
|
||||
//
|
||||
// Synced rows: "health.measure" id "measure:<day>" {day, weight, waist, hip, neck, chest, arm,
|
||||
// thigh, fat_scale, note, updated}; "health.vital" {t "YYYY-MM-DD HH:MM", sys, dia, spo2, pulse,
|
||||
// note, source} — imported ones have id "vital:<t>", ones typed here a random id.
|
||||
import 'dart:math';
|
||||
|
||||
import '../sync/store.dart';
|
||||
import 'cycle_model.dart' show iso, parseDay, daysBetween, today;
|
||||
import 'summaries.dart';
|
||||
|
||||
const female = 'female';
|
||||
const stale = 90; // days a measurement is still used for "now" / carried forward
|
||||
|
||||
/// key: (label, unit, min, max)
|
||||
const fields = {
|
||||
'weight': ('Weight', 'kg', 20.0, 400.0),
|
||||
'waist': ('Waist', 'cm', 30.0, 250.0),
|
||||
'hip': ('Hips', 'cm', 30.0, 250.0),
|
||||
'neck': ('Neck', 'cm', 15.0, 80.0),
|
||||
'chest': ('Chest', 'cm', 40.0, 250.0),
|
||||
'arm': ('Upper arm', 'cm', 10.0, 80.0),
|
||||
'thigh': ('Thigh', 'cm', 20.0, 120.0),
|
||||
'fat_scale': ('Body fat from a scale', '%', 2.0, 75.0),
|
||||
};
|
||||
const fatDayFields = {'weight', 'waist', 'hip', 'neck', 'fat_scale'};
|
||||
|
||||
/// The values set on the dashboard (Settings ▸ Health), from its person summary (profileOf).
|
||||
class Profile {
|
||||
const Profile({this.sex = female, this.birth, this.height});
|
||||
final String sex;
|
||||
final DateTime? birth;
|
||||
final double? height;
|
||||
int? ageOn(DateTime d) {
|
||||
final b = birth;
|
||||
if (b == null) return null;
|
||||
return d.year - b.year - ((d.month < b.month || (d.month == b.month && d.day < b.day)) ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The dashboard's Settings ▸ Health (sex, birth date, height) as its summary brings them; none yet = no age / height.
|
||||
Profile profileOf(SyncStore store) {
|
||||
final p = Summaries(store).meta('person') ?? {};
|
||||
final b = DateTime.tryParse('${p['birth'] ?? ''}');
|
||||
final h = (p['height'] as num?)?.toDouble();
|
||||
return Profile(sex: p['sex'] == 'male' ? 'male' : female,
|
||||
birth: b == null ? null : DateTime.utc(b.year, b.month, b.day), height: h == null || h <= 0 ? null : h);
|
||||
}
|
||||
|
||||
// ---- formulas (calc.py) ---------------------------------------------------------------------
|
||||
|
||||
double _log10(double x) => log(x) / ln10;
|
||||
|
||||
double? bmi(double? w, double? h) => (w == null || h == null || w == 0 || h == 0) ? null : w / pow(h / 100, 2);
|
||||
|
||||
const bmiClasses = [(18.5, 'underweight'), (25.0, 'normal'), (30.0, 'overweight'), (35.0, 'obese (class I)'),
|
||||
(40.0, 'obese (class II)'), (999.0, 'obese (class III)')];
|
||||
String? bmiClass(double? b) => b == null ? null : bmiClasses.firstWhere((c) => b < c.$1).$2;
|
||||
|
||||
(double, double)? healthyWeight(double? h) => h == null ? null : (18.5 * pow(h / 100, 2), 24.9 * pow(h / 100, 2));
|
||||
|
||||
double? whtr(double? waist, double? h) => waist != null && h != null ? waist / h : null;
|
||||
String? whtrClass(double? r) => r == null ? null : r < 0.4 ? 'low' : r < 0.5 ? 'healthy' : r < 0.6 ? 'raised' : 'high';
|
||||
double? whr(double? waist, double? hip) => waist != null && hip != null ? waist / hip : null;
|
||||
String? whrClass(double? r, String sex) => r == null ? null : r >= (sex == female ? 0.85 : 0.90) ? 'raised (WHO)' : 'healthy';
|
||||
String? waistClass(double? w, String sex) {
|
||||
if (w == null) return null;
|
||||
final (a, b) = sex == female ? (80, 88) : (94, 102);
|
||||
return w < a ? 'healthy' : w < b ? 'raised' : 'high';
|
||||
}
|
||||
|
||||
double? navy(Map<String, double> m, double? h, String sex) {
|
||||
final w = m['waist'], n = m['neck'], hip = m['hip'];
|
||||
if (w == null || n == null || h == null) return null;
|
||||
if (sex == female) {
|
||||
if (hip == null || w + hip - n <= 0) return null;
|
||||
return 495 / (1.29579 - 0.35004 * _log10(w + hip - n) + 0.22100 * _log10(h)) - 450;
|
||||
}
|
||||
if (w - n <= 0) return null;
|
||||
return 495 / (1.0324 - 0.19077 * _log10(w - n) + 0.15456 * _log10(h)) - 450;
|
||||
}
|
||||
|
||||
double? rfm(Map<String, double> m, double? h, String sex) {
|
||||
final w = m['waist'];
|
||||
return w == null || h == null ? null : (sex == female ? 76 : 64) - 20 * h / w;
|
||||
}
|
||||
|
||||
double? ymca(Map<String, double> m, double? h, String sex) {
|
||||
final w = m['waist'], kg = m['weight'];
|
||||
if (w == null || kg == null) return null;
|
||||
final lb = kg * 2.20462, inch = w / 2.54;
|
||||
return (4.15 * inch - 0.082 * lb - (sex == female ? 76.76 : 98.42)) / lb * 100;
|
||||
}
|
||||
|
||||
class FatResult {
|
||||
FatResult(this.key, this.name, this.value, this.missing, this.note);
|
||||
final String key, name, note;
|
||||
final double? value;
|
||||
final List<String> missing;
|
||||
}
|
||||
|
||||
/// (key, name, needs, note) — BMI-based formulas and skinfolds left out on purpose (calc.FAT).
|
||||
const fatFormulas = [
|
||||
('navy', 'U.S. Navy', ['waist', 'neck', 'hip?', 'height'], 'tape: waist, neck, hips · about ±3–4 % in studies'),
|
||||
('rfm', 'Relative fat mass', ['waist', 'height'], 'waist and height · checked against DEXA scans'),
|
||||
('ymca', 'YMCA', ['waist', 'weight'], 'waist and weight · simple, less tested in women'),
|
||||
('scale', 'Your scale', ['fat_scale'], 'bioimpedance · shifts with water, time of day'),
|
||||
];
|
||||
|
||||
List<FatResult> fatAll(Map<String, double> m, double? h, String sex) => [
|
||||
for (final (key, name, needs, note) in fatFormulas)
|
||||
() {
|
||||
var v = switch (key) {
|
||||
'navy' => navy(m, h, sex),
|
||||
'rfm' => rfm(m, h, sex),
|
||||
'ymca' => ymca(m, h, sex),
|
||||
_ => m['fat_scale'],
|
||||
};
|
||||
if (v != null && (v < 2 || v > 75)) v = null; // implausible: bad inputs
|
||||
final missing = <String>[];
|
||||
if (v == null) {
|
||||
for (final n in needs) {
|
||||
if (n == 'hip?') {
|
||||
if (sex == female && m['hip'] == null) missing.add('hip');
|
||||
} else if (n == 'height') {
|
||||
if (h == null) missing.add('height');
|
||||
} else if (m[n] == null) {
|
||||
missing.add(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
return FatResult(key, name, v, missing, note);
|
||||
}()
|
||||
];
|
||||
|
||||
/// Healthy body-fat ranges (Gallagher et al. 2000): (age from, to, healthy from, high from, very high from).
|
||||
const fatRanges = {
|
||||
female: [(20, 39, 21.0, 33.0, 39.0), (40, 59, 23.0, 34.0, 40.0), (60, 79, 24.0, 36.0, 42.0)],
|
||||
'male': [(20, 39, 8.0, 20.0, 25.0), (40, 59, 11.0, 22.0, 28.0), (60, 79, 13.0, 25.0, 30.0)],
|
||||
};
|
||||
const fatNames = ['low', 'healthy', 'high', 'very high'];
|
||||
|
||||
(int, int, double, double, double)? fatBand(String sex, int? age) {
|
||||
if (age == null || age < 20) return null;
|
||||
final rows = fatRanges[sex == female ? female : 'male']!;
|
||||
return rows.firstWhere((r) => r.$1 <= age && age <= r.$2, orElse: () => rows.last);
|
||||
}
|
||||
|
||||
String? fatClass(double? v, String sex, int? age) {
|
||||
final b = fatBand(sex, age);
|
||||
if (v == null || b == null) return null;
|
||||
return fatNames[[b.$3, b.$4, b.$5].where((x) => v >= x).length];
|
||||
}
|
||||
|
||||
/// Desirable BMI by age (NRC 1989): (age from, to, lo, hi).
|
||||
const bmiAge = [(19, 24, 19, 24), (25, 34, 20, 25), (35, 44, 21, 26), (45, 54, 22, 27), (55, 64, 23, 28), (65, 200, 24, 29)];
|
||||
(int, int, int, int)? bmiAgeBand(int? age) =>
|
||||
age == null || age < 19 ? null : bmiAge.firstWhere((r) => r.$1 <= age && age <= r.$2);
|
||||
|
||||
double? bmrMifflin(double? w, double? h, String sex, int? age) =>
|
||||
w == null || h == null || age == null ? null : 10 * w + 6.25 * h - 5 * age + (sex == female ? -161 : 5);
|
||||
double? bmrKatch(double? w, double? fat) => w == null || fat == null ? null : 370 + 21.6 * w * (1 - fat / 100);
|
||||
|
||||
double? median(List<double> xs) {
|
||||
if (xs.isEmpty) return null;
|
||||
final s = [...xs]..sort();
|
||||
final n = s.length;
|
||||
return n.isOdd ? s[n ~/ 2] : (s[n ~/ 2 - 1] + s[n ~/ 2]) / 2;
|
||||
}
|
||||
|
||||
// ---- the page's numbers (views.py) ----------------------------------------------------------
|
||||
|
||||
class Measure {
|
||||
Measure(this.row) : day = parseDay(row['day'] as String);
|
||||
final Map<String, dynamic> row;
|
||||
final DateTime day;
|
||||
double? operator [](String k) => (row[k] as num?)?.toDouble();
|
||||
String get note => (row['note'] as String?) ?? '';
|
||||
}
|
||||
|
||||
class Latest {
|
||||
Latest(this.v, this.day, this.stale);
|
||||
final double v;
|
||||
final DateTime day;
|
||||
final bool stale;
|
||||
}
|
||||
|
||||
class BodyView {
|
||||
BodyView(SyncStore store, this.p, {DateTime? now}) : now = now ?? today() {
|
||||
rows = [for (final r in store.rows('health.measure')) Measure(r)]..sort((a, b) => a.day.compareTo(b.day));
|
||||
for (final r in rows) {
|
||||
for (final k in fields.keys) {
|
||||
if (r[k] != null) cur[k] = Latest(r[k]!, r.day, daysBetween(r.day, this.now) > stale);
|
||||
}
|
||||
}
|
||||
final m = {for (final e in cur.entries) if (!e.value.stale) e.key: e.value.v};
|
||||
fresh = m;
|
||||
age = p.ageOn(this.now);
|
||||
fat = fatAll(m, p.height, p.sex);
|
||||
final est = [for (final f in fat) if (f.value != null) f.value!];
|
||||
fatMid = median(est);
|
||||
fatRange = est.length > 1 ? (est.reduce(min), est.reduce(max)) : null;
|
||||
}
|
||||
|
||||
final Profile p;
|
||||
final DateTime now;
|
||||
late final List<Measure> rows;
|
||||
final cur = <String, Latest>{};
|
||||
late final Map<String, double> fresh;
|
||||
late final int? age;
|
||||
late final List<FatResult> fat;
|
||||
late final double? fatMid;
|
||||
late final (double, double)? fatRange;
|
||||
|
||||
double? get weight => fresh['weight'];
|
||||
double? get waist => fresh['waist'];
|
||||
double? get hip => fresh['hip'];
|
||||
double? get bmiNow => bmi(weight, p.height);
|
||||
|
||||
/// Change of [key] from the value nearest [days] ago (at least 7 days back) to the latest.
|
||||
(double, DateTime, int)? change(String key, {int days = 30}) {
|
||||
final pts = [for (final r in rows) if (r[key] != null) (r.day, r[key]!)];
|
||||
if (pts.length < 2) return null;
|
||||
final (lastD, lastV) = pts.last;
|
||||
final old = pts.where((p) => daysBetween(p.$1, lastD) >= 7).toList();
|
||||
if (old.isEmpty) return null;
|
||||
old.sort((a, b) => (daysBetween(a.$1, lastD) - days).abs().compareTo((daysBetween(b.$1, lastD) - days).abs()));
|
||||
final (d, v) = old.first;
|
||||
return (lastV - v, d, daysBetween(d, lastD));
|
||||
}
|
||||
|
||||
/// Per measured day: weight, waist, BMI and each fat formula (other inputs carried forward ≤ stale days).
|
||||
Map<String, List<(DateTime, double)>> series() {
|
||||
final out = <String, List<(DateTime, double)>>{
|
||||
'weight': [], 'waist': [], 'bmi': [], for (final f in fatFormulas) f.$1: []};
|
||||
final last = <String, (double, DateTime)>{};
|
||||
for (final r in rows) {
|
||||
for (final k in fields.keys) {
|
||||
if (r[k] != null) last[k] = (r[k]!, r.day);
|
||||
}
|
||||
final m = {for (final e in last.entries) if (daysBetween(e.value.$2, r.day) <= stale) e.key: e.value.$1};
|
||||
for (final k in ['weight', 'waist']) {
|
||||
if (r[k] != null) out[k]!.add((r.day, r[k]!));
|
||||
}
|
||||
if (r['weight'] != null && p.height != null) out['bmi']!.add((r.day, bmi(r['weight'], p.height)!));
|
||||
if (fatDayFields.any((k) => r[k] != null)) {
|
||||
for (final f in fatAll(m, p.height, p.sex)) {
|
||||
if (f.value != null) out[f.key]!.add((r.day, f.value!));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/// db.save: replace the day's row; `was` (another day) moves it; nothing in it → deleted.
|
||||
String? saveMeasure(SyncStore store, DateTime d, Map<String, double?> vals, String note, {DateTime? was}) {
|
||||
if (d.isAfter(today())) return "That day hasn't happened yet.";
|
||||
for (final e in vals.entries) {
|
||||
final f = fields[e.key]!;
|
||||
if (e.value != null && (e.value! < f.$3 || e.value! > f.$4)) return '${f.$1}: between ${f.$3.round()} and ${f.$4.round()} ${f.$2}.';
|
||||
}
|
||||
final u = 'measure:${iso(d)}';
|
||||
if (was != null && was != d) {
|
||||
if (store.row('health.measure', u) != null) return 'That day already has measurements — edit it instead.';
|
||||
store.delete('health.measure', 'measure:${iso(was)}');
|
||||
}
|
||||
if (vals.values.every((v) => v == null) && note.trim().isEmpty) {
|
||||
if (store.row('health.measure', u) != null) store.delete('health.measure', u);
|
||||
return null;
|
||||
}
|
||||
final old = store.row('health.measure', u) ?? {};
|
||||
final now = DateTime.now();
|
||||
store.put('health.measure', u, {
|
||||
...old, // columns this app doesn't show (old skinfolds) stay
|
||||
'day': iso(d), 'note': note.trim(), 'updated': '${iso(now)} ${now.toIso8601String().substring(11, 19)}',
|
||||
for (final k in fields.keys) k: vals[k],
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- vitals ------------------------------------------------------------------------------
|
||||
|
||||
const vitalSources = {'mi_fitness': 'Mi Fitness', 'health_connect': 'Health Connect', 'gadgetbridge': 'Gadgetbridge'};
|
||||
|
||||
class Vital {
|
||||
Vital(this.row) : t = DateTime.parse('${(row['t'] as String).replaceFirst(' ', 'T')}:00Z');
|
||||
final Map<String, dynamic> row;
|
||||
final DateTime t; // local wall time (stored as UTC so nothing shifts)
|
||||
String get u => row['_u'] as String;
|
||||
int? get sys => (row['sys'] as num?)?.toInt();
|
||||
int? get dia => (row['dia'] as num?)?.toInt();
|
||||
double? get spo2 => (row['spo2'] as num?)?.toDouble();
|
||||
String get note => (row['note'] as String?) ?? '';
|
||||
String? get source => row['source'] as String?;
|
||||
bool get isBp => sys != null && dia != null;
|
||||
}
|
||||
|
||||
List<Vital> vitals(SyncStore store) =>
|
||||
[for (final r in store.rows('health.vital')) Vital(r)]..sort((a, b) => b.t.compareTo(a.t)); // newest first
|
||||
|
||||
/// (name, colour key) — ESC 2024 office categories; the higher of the two numbers decides.
|
||||
(String, String)? bpClass(int? sys, int? dia) {
|
||||
if (sys == null || dia == null) return null;
|
||||
const classes = [('non-elevated', 0, 0, 'ok'), ('elevated', 120, 70, 'mid'), ('hypertension', 140, 90, 'high'),
|
||||
('severe hypertension', 180, 110, 'vhigh')];
|
||||
var pick = classes.first;
|
||||
for (final c in classes) {
|
||||
if (sys >= c.$2 || dia >= c.$3) pick = c;
|
||||
}
|
||||
return (pick.$1, pick.$4);
|
||||
}
|
||||
|
||||
(String, String)? spo2Class(double? p) => p == null ? null : p >= 95 ? ('normal', 'ok') : p > 90 ? ('low', 'mid') : ('very low', 'vhigh');
|
||||
|
||||
/// db.save_vital: one kind per reading (bp: sys + dia, ox: spo2). Returns an error or null.
|
||||
String? saveVital(SyncStore store, {String? u, required String kind, required DateTime t, int? sys, int? dia, double? spo2,
|
||||
String note = ''}) {
|
||||
if (t.isAfter(DateTime.now().toUtc().add(const Duration(hours: 14)))) return "That time hasn't come yet.";
|
||||
if (kind == 'bp') {
|
||||
if (sys == null || dia == null) return 'Blood pressure needs both numbers (e.g. 120 / 80).';
|
||||
if (sys < 60 || sys > 260) return 'Systolic: between 60 and 260 mmHg.';
|
||||
if (dia < 30 || dia > 160) return 'Diastolic: between 30 and 160 mmHg.';
|
||||
if (sys <= dia) return 'The upper number (systolic) is the bigger one.';
|
||||
} else {
|
||||
if (spo2 == null) return 'Enter the oxygen %.';
|
||||
if (spo2 < 50 || spo2 > 100) return 'Blood oxygen: between 50 and 100 %.';
|
||||
}
|
||||
final old = u == null ? null : store.row('health.vital', u);
|
||||
final ts = '${iso(t)} ${t.toIso8601String().substring(11, 16)}';
|
||||
store.put('health.vital', u ?? SyncStore.randomId(), {
|
||||
...?old,
|
||||
't': ts, 'sys': kind == 'bp' ? sys : null, 'dia': kind == 'bp' ? dia : null,
|
||||
'spo2': kind == 'ox' ? (spo2! * 10).round() / 10 : null, 'pulse': null, 'note': note.trim(),
|
||||
'source': old?['source'],
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Readings of one kind as chart points (oldest first).
|
||||
List<(DateTime, double)> vitalSeries(List<Vital> vs, double? Function(Vital) pick) =>
|
||||
[for (final v in vs.reversed) if (pick(v) != null) (v.t, pick(v)!)];
|
||||
419
app/lib/health/body_page.dart
Normal file
419
app/lib/health/body_page.dart
Normal file
|
|
@ -0,0 +1,419 @@
|
|||
// Health ▸ Body: tiles (weight + change, BMI, waist, body fat), the chart (weight / waist / BMI /
|
||||
// body fat over 3 months · 1 year · all), body fat by every formula, ratios + resting energy, the
|
||||
// measurements (tap = edit, + = add). The numbers are the web page's (body_model.dart).
|
||||
// Categories: tap a tile (the web page shows them on hover).
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import '../widgets/line_chart.dart';
|
||||
import 'body_model.dart';
|
||||
import 'cycle_model.dart' show plus, today;
|
||||
import 'range.dart';
|
||||
|
||||
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
String dm(DateTime d) => '${d.day} ${_mon[d.month - 1]}';
|
||||
String dmy(DateTime d) => '${d.day} ${_mon[d.month - 1]} ${d.year}';
|
||||
String n1(double? v) => v == null ? '—' : v.toStringAsFixed(1);
|
||||
/// 115 not 115.0; 124.6 stays.
|
||||
String trim1(double? v) => v == null ? '—' : n1(v).replaceFirst(RegExp(r'\.0$'), '');
|
||||
const _short = {'weight': 'weight', 'waist': 'waist', 'hip': 'hips', 'neck': 'neck', 'chest': 'chest', 'arm': 'arm',
|
||||
'thigh': 'thigh', 'fat_scale': 'scale fat'};
|
||||
|
||||
/// A category word → its colour (healthy green, raised amber, high red, low blue).
|
||||
Color classColor(String? c) {
|
||||
if (c == null) return muted;
|
||||
if (RegExp(r'very high|obese|severe|vhigh|very low').hasMatch(c)) return bad;
|
||||
if (RegExp(r'^(healthy|normal|non-elevated|ok)').hasMatch(c)) return good;
|
||||
if (RegExp(r'^(low|underweight)').hasMatch(c)) return const Color(0xFF5CC8FF);
|
||||
return accent;
|
||||
}
|
||||
|
||||
class BodyPage extends StatefulWidget {
|
||||
const BodyPage({super.key, required this.sync, required this.range});
|
||||
final SyncService sync;
|
||||
final HealthRange range;
|
||||
@override
|
||||
State<BodyPage> createState() => _BodyPageState();
|
||||
}
|
||||
|
||||
class _BodyPageState extends State<BodyPage> {
|
||||
String chart = 'weight';
|
||||
int shown = 5;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Scaffold(
|
||||
floatingActionButton: FloatingActionButton(
|
||||
backgroundColor: accent,
|
||||
foregroundColor: bg,
|
||||
tooltip: 'Add measurements',
|
||||
onPressed: () => _edit(BodyView(widget.sync.store, profileOf(widget.sync.store)), null),
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
body: ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.sync, widget.range]),
|
||||
builder: (context, _) {
|
||||
final v = BodyView(widget.sync.store, profileOf(widget.sync.store));
|
||||
if (v.rows.isEmpty) {
|
||||
return const Center(child: Text('No measurements yet — + to add the first.', style: TextStyle(color: muted)));
|
||||
}
|
||||
return LayoutBuilder(builder: (context, box) {
|
||||
final wide = box.maxWidth >= 700;
|
||||
final left = [_tiles(v, wide), const SizedBox(height: 12), _chart(v)];
|
||||
final right = [_fat(v), const SizedBox(height: 12), _ratios(v), const SizedBox(height: 12), _list(v)];
|
||||
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 88), children: [
|
||||
if (wide)
|
||||
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Expanded(child: Column(children: left)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Column(children: right)),
|
||||
])
|
||||
else ...[...left, const SizedBox(height: 12), ...right],
|
||||
]);
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// ---- tiles
|
||||
Widget _tiles(BodyView v, bool wide) {
|
||||
final wc = v.change('weight');
|
||||
final b = v.bmiNow;
|
||||
String from(String k) {
|
||||
final c = v.cur[k];
|
||||
if (c == null) return '';
|
||||
return c.day == v.now ? 'today' : c.stale ? 'old: ${dmy(c.day)}' : dm(c.day);
|
||||
}
|
||||
final tiles = [
|
||||
_Tile('Weight', v.weight == null ? '—' : '${trim1(v.weight)} kg',
|
||||
wc == null ? from('weight') : '${wc.$1 >= 0 ? '+' : '−'}${wc.$1.abs().toStringAsFixed(1)} kg in ${wc.$3} days',
|
||||
null, () => _info('Weight', _weightInfo(v))),
|
||||
_Tile('BMI', b == null ? '—' : n1(b), bmiClass(b) ?? 'needs height + weight', bmiClass(b), () => _info('BMI', _bmiInfo(v))),
|
||||
_Tile('Waist', v.waist == null ? '—' : '${trim1(v.waist)} cm', waistClass(v.waist, v.p.sex) ?? from('waist'),
|
||||
waistClass(v.waist, v.p.sex), () => _info('Waist', _waistInfo(v))),
|
||||
_Tile('Body fat', v.fatMid == null ? '—' : '${n1(v.fatMid)} %',
|
||||
fatClass(v.fatMid, v.p.sex, v.age) ?? 'needs measurements', fatClass(v.fatMid, v.p.sex, v.age),
|
||||
() => _info('Body fat', _fatInfo(v))),
|
||||
];
|
||||
return GridView.count(
|
||||
crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
|
||||
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.9,
|
||||
children: tiles,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _weightInfo(BodyView v) {
|
||||
final hw = healthyWeight(v.p.height);
|
||||
return Text(hw == null ? 'Set your height on the dashboard.' :
|
||||
'Healthy weight for ${v.p.height} cm (BMI 18.5–24.9): ${hw.$1.toStringAsFixed(1)}–${hw.$2.toStringAsFixed(1)} kg.');
|
||||
}
|
||||
|
||||
Widget _bmiInfo(BodyView v) {
|
||||
final band = bmiAgeBand(v.age);
|
||||
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
const Text('WHO classes (all adults): under 18.5 underweight · 18.5–25 normal · 25–30 overweight · 30+ obese (I 30–35, II 35–40, III 40+).'),
|
||||
const SizedBox(height: 10),
|
||||
const Text('Desirable BMI by age (NRC 1989):', style: TextStyle(color: muted)),
|
||||
for (final r in bmiAge)
|
||||
Text('${r.$1}–${r.$2 > 100 ? '+' : r.$2}: ${r.$3}–${r.$4}',
|
||||
style: TextStyle(color: band == r ? accent : null, fontWeight: band == r ? FontWeight.bold : null)),
|
||||
const SizedBox(height: 8),
|
||||
const Text('BMI reads muscle as fat; the waist and body fat say more.', style: TextStyle(color: muted)),
|
||||
]);
|
||||
}
|
||||
|
||||
Widget _waistInfo(BodyView v) => Text(v.p.sex == female
|
||||
? 'WHO (European women): under 80 cm healthy · 80–88 raised · 88+ high.'
|
||||
: 'WHO (European men): under 94 cm healthy · 94–102 raised · 102+ high.');
|
||||
|
||||
Widget _fatInfo(BodyView v) {
|
||||
final rows = fatRanges[v.p.sex == female ? female : 'male']!;
|
||||
final band = fatBand(v.p.sex, v.age);
|
||||
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Healthy body fat by age (${v.p.sex}, Gallagher et al. 2000):', style: const TextStyle(color: muted)),
|
||||
for (final r in rows)
|
||||
Text('${r.$1}–${r.$2}: healthy ${r.$3.round()}–${r.$4.round()} % · high from ${r.$4.round()} · very high from ${r.$5.round()}',
|
||||
style: TextStyle(color: band == r ? accent : null, fontWeight: band == r ? FontWeight.bold : null)),
|
||||
const SizedBox(height: 8),
|
||||
const Text('The middle (median) of every formula that has its measurements; they disagree by a few points.',
|
||||
style: TextStyle(color: muted)),
|
||||
]);
|
||||
}
|
||||
|
||||
void _info(String title, Widget body) => showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: card,
|
||||
builder: (_) => Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 28),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||||
const SizedBox(height: 10),
|
||||
body,
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
// ---- chart
|
||||
Widget _chart(BodyView v) {
|
||||
final sr = v.series();
|
||||
final from = widget.range.from(v.rows.first.day, v.now);
|
||||
final hw = healthyWeight(v.p.height);
|
||||
const fatColors = [Color(0xFFFFB33A), Color(0xFF5CC8FF), Color(0xFFC792EA), Color(0xFF7FD6A3)];
|
||||
final (List<Series> s, String unit, (double, double)? band) = switch (chart) {
|
||||
'waist' => ([Series('Waist', sr['waist']!, accent)], 'cm', null),
|
||||
'bmi' => ([Series('BMI', sr['bmi']!, accent)], '', (18.5, 25.0)),
|
||||
'fat' => ([for (var i = 0; i < fatFormulas.length; i++) Series(fatFormulas[i].$2, sr[fatFormulas[i].$1]!, fatColors[i])], '%', null),
|
||||
_ => ([Series('Weight', sr['weight']!, accent)], 'kg', hw),
|
||||
};
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 10, 12, 6),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(children: [
|
||||
for (final (k, l) in [('weight', 'Weight'), ('waist', 'Waist'), ('bmi', 'BMI'), ('fat', 'Body fat')])
|
||||
Padding(padding: const EdgeInsets.only(right: 6),
|
||||
child: ChoiceChip(label: Text(l), selected: chart == k, onSelected: (_) => setState(() => chart = k))),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
LineChart(series: s, from: from, to: plus(v.now, 1), unit: unit, band: band, range: widget.range),
|
||||
if (chart == 'fat')
|
||||
Wrap(spacing: 10, children: [
|
||||
for (var i = 0; i < fatFormulas.length; i++)
|
||||
Text('● ${fatFormulas[i].$2}', style: TextStyle(color: fatColors[i], fontSize: 12)),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- body fat by formula
|
||||
Widget _fat(BodyView v) => _Card('Body fat', [
|
||||
for (final f in v.fat)
|
||||
Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
message: f.note,
|
||||
child: _Row(f.name, f.value != null ? '${n1(f.value)} %' : 'needs ${f.missing.map(_need).join(', ')}',
|
||||
f.value == null ? muted : classColor(fatClass(f.value, v.p.sex, v.age))),
|
||||
),
|
||||
const Divider(color: card2),
|
||||
_Row('Middle of ${v.fat.where((f) => f.value != null).length}', v.fatMid == null ? '—' :
|
||||
'${n1(v.fatMid)} %${v.fatRange == null ? '' : ' (${n1(v.fatRange!.$1)}–${n1(v.fatRange!.$2)})'}',
|
||||
classColor(fatClass(v.fatMid, v.p.sex, v.age))),
|
||||
if (v.weight != null && v.fatMid != null)
|
||||
_Row('Fat · lean', '${(v.weight! * v.fatMid! / 100).toStringAsFixed(1)} kg · ${(v.weight! * (1 - v.fatMid! / 100)).toStringAsFixed(1)} kg', null),
|
||||
]);
|
||||
|
||||
static String _need(String k) => k == 'height' ? 'height' : k == 'fat_scale' ? 'a scale reading' : fields[k]!.$1.toLowerCase();
|
||||
|
||||
// ---- ratios + energy
|
||||
Widget _ratios(BodyView v) {
|
||||
final r1 = whtr(v.waist, v.p.height), r2 = whr(v.waist, v.hip);
|
||||
final m = bmrMifflin(v.weight, v.p.height, v.p.sex, v.age), k = bmrKatch(v.weight, v.fatMid);
|
||||
return _Card('Ratios & energy', [
|
||||
_Row('Waist ÷ height', r1 == null ? '—' : '${r1.toStringAsFixed(2)} · ${whtrClass(r1)}', classColor(whtrClass(r1))),
|
||||
_Row('Waist ÷ hips', r2 == null ? '—' : '${r2.toStringAsFixed(2)} · ${whrClass(r2, v.p.sex)}', classColor(whrClass(r2, v.p.sex))),
|
||||
_Row('Resting energy', m == null ? '—' : '${m.round()} kcal/day${k == null ? '' : ' · ${k.round()} from lean mass'}', null),
|
||||
]);
|
||||
}
|
||||
|
||||
// ---- the measurements
|
||||
Widget _list(BodyView v) {
|
||||
final from = widget.range.from(v.rows.first.day, v.now); // the charts' period
|
||||
final rows = v.rows.reversed.where((r) => !r.day.isBefore(from)).toList();
|
||||
return _Card('Measurements', [
|
||||
if (rows.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
|
||||
child: Text('Nothing measured in this period', style: TextStyle(color: muted))),
|
||||
for (final r in rows.take(shown))
|
||||
InkWell(
|
||||
onTap: () => _edit(v, r),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 7),
|
||||
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
SizedBox(width: 92, child: Text(r.day.year == v.now.year ? dm(r.day) : dmy(r.day), style: const TextStyle(color: muted))),
|
||||
Expanded(child: Text([
|
||||
for (final k in fields.keys) if (r[k] != null) '${_short[k]} ${trim1(r[k])}',
|
||||
if (r.note.isNotEmpty) '“${r.note}”',
|
||||
].join(' · '))),
|
||||
]),
|
||||
),
|
||||
),
|
||||
if (rows.length > shown)
|
||||
TextButton(onPressed: () => setState(() => shown += 5), child: Text('Show more (${rows.length - shown})')),
|
||||
]);
|
||||
}
|
||||
|
||||
Future<void> _edit(BodyView v, Measure? m) => showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => MeasureSheet(v: v, m: m, onSave: (d, vals, note, was) {
|
||||
final err = saveMeasure(widget.sync.store, d, vals, note, was: was);
|
||||
if (err == null) widget.sync.changed();
|
||||
return err;
|
||||
}, onDelete: m == null ? null : () {
|
||||
saveMeasure(widget.sync.store, m.day, {}, '');
|
||||
widget.sync.changed();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
class _Tile extends StatelessWidget {
|
||||
const _Tile(this.label, this.value, this.sub, this.cls, this.onTap);
|
||||
final String label, value, sub;
|
||||
final String? cls;
|
||||
final VoidCallback onTap;
|
||||
@override
|
||||
Widget build(BuildContext context) => Card(
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||||
Text(value, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
|
||||
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: cls == null ? muted : classColor(cls), fontSize: 12.5)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _Card extends StatelessWidget {
|
||||
const _Card(this.title, this.children);
|
||||
final String title;
|
||||
final List<Widget> children;
|
||||
@override
|
||||
Widget build(BuildContext context) => Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 6),
|
||||
...children,
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _Row extends StatelessWidget {
|
||||
const _Row(this.k, this.v, this.color);
|
||||
final String k, v;
|
||||
final Color? color;
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(children: [
|
||||
Expanded(child: Text(k, style: const TextStyle(color: muted))),
|
||||
Flexible(child: Text(v, textAlign: TextAlign.right, style: TextStyle(color: color))),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/// Add / edit a day's measurements: date, every field (placeholders = your last values), note.
|
||||
class MeasureSheet extends StatefulWidget {
|
||||
const MeasureSheet({super.key, required this.v, required this.m, required this.onSave, this.onDelete});
|
||||
final BodyView v;
|
||||
final Measure? m;
|
||||
final String? Function(DateTime d, Map<String, double?> vals, String note, DateTime? was) onSave;
|
||||
final VoidCallback? onDelete;
|
||||
@override
|
||||
State<MeasureSheet> createState() => _MeasureSheetState();
|
||||
}
|
||||
|
||||
class _MeasureSheetState extends State<MeasureSheet> {
|
||||
late DateTime d = widget.m?.day ?? today();
|
||||
late final ctl = {
|
||||
for (final k in fields.keys) k: TextEditingController(text: widget.m?[k] == null ? '' : trim1(widget.m![k]))
|
||||
};
|
||||
late final note = TextEditingController(text: widget.m?.note ?? '');
|
||||
String? error;
|
||||
bool armed = false;
|
||||
|
||||
void _loadDay(DateTime nd) {
|
||||
// picking a day that already has measurements (when adding) loads them, like the web dialog
|
||||
final other = widget.v.rows.where((r) => r.day == nd).firstOrNull;
|
||||
setState(() {
|
||||
d = nd;
|
||||
if (widget.m == null && other != null) {
|
||||
for (final k in fields.keys) {
|
||||
ctl[k]!.text = other[k] == null ? '' : trim1(other[k]);
|
||||
}
|
||||
note.text = other.note;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
Expanded(child: Text(widget.m == null ? 'Add measurements' : 'Edit measurements',
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent))),
|
||||
TextButton.icon(
|
||||
icon: const Icon(Icons.event, size: 18),
|
||||
label: Text(dmy(d)),
|
||||
onPressed: () async {
|
||||
final p = await showDatePicker(context: context, initialDate: d, firstDate: DateTime.utc(2000), lastDate: today());
|
||||
if (p != null) _loadDay(DateTime.utc(p.year, p.month, p.day));
|
||||
},
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 4),
|
||||
GridView.count(
|
||||
crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
|
||||
crossAxisSpacing: 12, childAspectRatio: 3.2,
|
||||
children: [
|
||||
for (final e in fields.entries)
|
||||
TextField(
|
||||
controller: ctl[e.key],
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
textInputAction: TextInputAction.next,
|
||||
decoration: InputDecoration(
|
||||
labelText: e.key == 'fat_scale' ? 'Scale body fat' : e.value.$1, suffixText: e.value.$2,
|
||||
hintText: widget.v.cur[e.key] == null ? null : n1(widget.v.cur[e.key]!.v),
|
||||
),
|
||||
),
|
||||
]),
|
||||
TextField(controller: note, maxLength: 2000, decoration: const InputDecoration(labelText: 'Note')),
|
||||
if (error != null) Padding(padding: const EdgeInsets.only(bottom: 8), child: Text(error!, style: const TextStyle(color: bad))),
|
||||
Row(children: [
|
||||
if (widget.onDelete != null)
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (!armed) return setState(() => armed = true);
|
||||
widget.onDelete!();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Text(armed ? 'Tap again to delete' : 'Delete', style: const TextStyle(color: bad)),
|
||||
),
|
||||
const Spacer(),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final vals = <String, double?>{};
|
||||
for (final k in fields.keys) {
|
||||
final t = ctl[k]!.text.trim().replaceAll(',', '.');
|
||||
if (t.isEmpty) {
|
||||
vals[k] = null;
|
||||
} else if (double.tryParse(t) == null) {
|
||||
return setState(() => error = '${fields[k]!.$1}: not a number.');
|
||||
} else {
|
||||
vals[k] = double.parse(t);
|
||||
}
|
||||
}
|
||||
final err = widget.onSave(d, vals, note.text, widget.m?.day);
|
||||
if (err != null) return setState(() => error = err);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Save'),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
74
app/lib/health/cycle_doctor.dart
Normal file
74
app/lib/health/cycle_doctor.dart
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// Cycle ▸ For your doctor: the last 12 months as on the web page's History (cycle.views.history's
|
||||
// doctor part): last period, cycle / period length (average + range), periods logged, pain,
|
||||
// most common symptoms + moods, and what's worth mentioning by the common guidelines.
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'cycle_model.dart';
|
||||
|
||||
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
String dmy(DateTime d) => '${d.day} ${_mon[d.month - 1]} ${d.year}';
|
||||
String _range((int, int)? r) => r == null ? '—' : r.$1 == r.$2 ? '${r.$1} days' : '${r.$1}–${r.$2} days';
|
||||
|
||||
class DoctorPage extends StatelessWidget {
|
||||
const DoctorPage({super.key, required this.sync, required this.settings});
|
||||
final SyncService sync;
|
||||
final CycleSettings settings;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Scaffold(
|
||||
appBar: AppBar(title: const Text('For your doctor')),
|
||||
body: ListenableBuilder(
|
||||
listenable: sync,
|
||||
builder: (context, _) {
|
||||
final v = CycleView(sync.store, settings);
|
||||
if (v.periods.isEmpty) {
|
||||
return const Center(child: Text('Nothing logged yet.', style: TextStyle(color: muted)));
|
||||
}
|
||||
final d = doctor(v);
|
||||
final rows = <(String, String)>[
|
||||
('First day of last period', d.last == null ? '—' : dmy(d.last!)),
|
||||
('Cycle length', d.cycle == null ? 'not enough data yet' : '${d.cycle} days on average · ${_range(d.cycleRange)}'),
|
||||
('Period length', d.period == null ? 'not enough data yet' : '${d.period} days on average · ${_range(d.periodRange)}'),
|
||||
('Periods logged', '${d.periods}'),
|
||||
('Pain', d.painDays == 0 ? 'none logged' : 'on ${d.painDays} day${d.painDays != 1 ? 's' : ''}, ${d.painAvg} / 5 on average'),
|
||||
('Most common', d.symptoms.isEmpty ? 'no symptoms logged' : d.symptoms.map((s) => '${s.$1} (${s.$2}×)').join(', ')),
|
||||
];
|
||||
return ListView(padding: const EdgeInsets.all(12), children: [
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Row(children: [
|
||||
Expanded(child: Text('${dmy(d.since)} – ${dmy(d.now)}', style: const TextStyle(color: muted))),
|
||||
const Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
message: 'From self-logged data; general guidance, not a diagnosis.',
|
||||
child: Icon(Icons.info_outline, size: 18, color: muted),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 12),
|
||||
for (final (k, val) in rows) ...[
|
||||
Text(k, style: const TextStyle(color: muted, fontSize: 13)),
|
||||
Padding(padding: const EdgeInsets.only(top: 2, bottom: 12), child: Text(val, style: const TextStyle(fontSize: 16))),
|
||||
],
|
||||
const Divider(color: card2),
|
||||
const SizedBox(height: 6),
|
||||
if (d.flags.isEmpty)
|
||||
const Text('Nothing unusual by the common guidelines (cycles 21–35 days, periods up to 7 days, '
|
||||
'no spotting between periods, …).', style: TextStyle(color: good))
|
||||
else ...[
|
||||
const Text('Worth mentioning', style: TextStyle(fontWeight: FontWeight.bold, color: accent)),
|
||||
const SizedBox(height: 6),
|
||||
for (final f in d.flags)
|
||||
Padding(padding: const EdgeInsets.only(bottom: 4), child: Text('• $f')),
|
||||
],
|
||||
]),
|
||||
),
|
||||
),
|
||||
]);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
334
app/lib/health/cycle_model.dart
Normal file
334
app/lib/health/cycle_model.dart
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
// The cycle tracker's numbers — a port of the dashboard's plugins/cycle/views.py (keep them in
|
||||
// step: same rules, same results as the web page) + db.save_day's rules for writing a day.
|
||||
//
|
||||
// Data: synced rows "cycle.day", id "day:YYYY-MM-DD": {day, period 0/1, flow 1–5, pain 1–5,
|
||||
// pain_len, tags "a,b", note, source, updated}. Days are UTC dates here (no DST surprises).
|
||||
import 'dart:math';
|
||||
|
||||
import '../sync/store.dart';
|
||||
|
||||
const history = 12; // cycles averaged (at most)
|
||||
const halfLife = 180; // days: a cycle this much older counts half as much
|
||||
const maxCycle = 60; // longer "cycles" are gaps in logging
|
||||
const luteal = 14; // ovulation -> next period, days
|
||||
const gap = 2; // unmarked days that don't split a period
|
||||
|
||||
const painLen = {'0-1': 'under 1 h', '1-3': '1–3 h', '3-6': '3–6 h', '6-24': '6–24 h'};
|
||||
const tagGroups = {
|
||||
'Symptoms': {
|
||||
'spotting': 'Spotting', 'headache': 'Headache', 'backache': 'Backache', 'tiredness': 'Tiredness',
|
||||
'bloating': 'Bloating', 'breasts': 'Tender breasts', 'acne': 'Acne', 'nausea': 'Nausea',
|
||||
'cravings': 'Cravings', 'stomach': 'Upset stomach', 'sleep': 'Poor sleep', 'dizzy': 'Dizziness'},
|
||||
'Mood': {
|
||||
'happy': 'Happy', 'calm': 'Calm', 'energetic': 'Energetic', 'sensitive': 'Sensitive',
|
||||
'irritable': 'Irritable', 'anxious': 'Anxious', 'sad': 'Sad', 'swings': 'Mood swings',
|
||||
'stressed': 'Stressed', 'unmotivated': 'Unmotivated'},
|
||||
'Sex': {
|
||||
'sex_prot': 'Sex, protected', 'sex_unprot': 'Sex, unprotected', 'drive': 'Sex drive',
|
||||
'drive_low': 'Low sex drive', 'solo': 'Masturbation', 'sex_pain': 'Pain during sex'},
|
||||
};
|
||||
const flowNames = ['very light', 'light', 'medium', 'heavy', 'very heavy'];
|
||||
const sources = {
|
||||
'xiaomi': ('⌚', 'Imported from Xiaomi (Mi Fitness)'),
|
||||
'mymonthlycycles': ('📱', 'Imported from My Monthly Cycles'),
|
||||
'calculated': ('≈', 'Calculated: not logged, placed between the periods around it'),
|
||||
};
|
||||
/// Calendar symbols for some tags: (tags, glyph, label); "spot" = a small droplet.
|
||||
const symbols = [
|
||||
({'sex_prot', 'sex_unprot'}, '♥', 'had sex'),
|
||||
({'happy', 'calm', 'energetic'}, '☺', 'good mood'),
|
||||
({'sensitive', 'irritable', 'anxious', 'sad', 'swings', 'stressed', 'unmotivated'}, '☹', 'low mood'),
|
||||
({'spotting'}, 'spot', 'spotting'),
|
||||
({'tiredness'}, '💤', 'tired'),
|
||||
({'headache'}, '⚡', 'headache'),
|
||||
];
|
||||
|
||||
DateTime day(DateTime d) => DateTime.utc(d.year, d.month, d.day);
|
||||
|
||||
/// Python's round(): halves go to the even number (round(28.5) == 28), so averages match the web page.
|
||||
int pyRound(double x) {
|
||||
final f = x.floorToDouble(), diff = x - f;
|
||||
if (diff > 0.5) return f.toInt() + 1;
|
||||
if (diff < 0.5) return f.toInt();
|
||||
return f.toInt().isEven ? f.toInt() : f.toInt() + 1;
|
||||
}
|
||||
DateTime today() => day(DateTime.now());
|
||||
DateTime parseDay(String s) => DateTime.parse('${s}T00:00:00Z');
|
||||
String iso(DateTime d) => d.toIso8601String().substring(0, 10);
|
||||
int daysBetween(DateTime a, DateTime b) => b.difference(a).inDays; // b - a
|
||||
DateTime plus(DateTime d, int n) => d.add(Duration(days: n));
|
||||
|
||||
class CycleSettings {
|
||||
const CycleSettings({this.cycleLength = 28, this.periodLength = 5, this.showFertile = true});
|
||||
final int cycleLength, periodLength;
|
||||
final bool showFertile;
|
||||
}
|
||||
|
||||
class DayLog {
|
||||
DayLog(this.row);
|
||||
final Map<String, dynamic> row;
|
||||
bool get period => (row['period'] ?? 0) == 1;
|
||||
int? get flow => row['flow'] as int?;
|
||||
int? get pain => row['pain'] as int?;
|
||||
String? get painLength => row['pain_len'] as String?;
|
||||
List<String> get tags => ((row['tags'] as String?) ?? '').split(',').where((t) => t.isNotEmpty).toList();
|
||||
String get note => (row['note'] as String?) ?? '';
|
||||
String? get source => row['source'] as String?;
|
||||
bool get hasLog => pain != null || tags.isNotEmpty || note.isNotEmpty;
|
||||
|
||||
String summary() {
|
||||
final names = {for (final g in tagGroups.values) ...g};
|
||||
return [
|
||||
if (pain != null) 'pain $pain/5${painLen[painLength] != null ? ' (${painLen[painLength]})' : ''}',
|
||||
...tags.where(names.containsKey).map((t) => names[t]!),
|
||||
if (note.isNotEmpty) note,
|
||||
if (sources[source] != null) sources[source]!.$2,
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
List<(String, String)> get symbolList =>
|
||||
[for (final (ts, g, label) in symbols) if (ts.intersection(tags.toSet()).isNotEmpty) (g, label)];
|
||||
}
|
||||
|
||||
class Period {
|
||||
Period(this.start, this.end, this.calc);
|
||||
DateTime start, end;
|
||||
bool calc;
|
||||
int get length => daysBetween(start, end) + 1;
|
||||
}
|
||||
|
||||
class CycleStats {
|
||||
CycleStats(this.cycle, this.period, this.cycles, this.fromData);
|
||||
final int cycle, period;
|
||||
final List<int> cycles;
|
||||
final bool fromData;
|
||||
}
|
||||
|
||||
int _avg(List<(int, DateTime)> xs, int fallback, DateTime now) {
|
||||
final last = xs.length > history ? xs.sublist(xs.length - history) : xs;
|
||||
if (last.isEmpty) return fallback;
|
||||
final w = [for (final (_, d) in last) pow(0.5, max(0, daysBetween(d, now)) / halfLife).toDouble()];
|
||||
var s = 0.0;
|
||||
for (var i = 0; i < last.length; i++) {
|
||||
s += last[i].$1 * w[i];
|
||||
}
|
||||
return pyRound(s / w.reduce((a, b) => a + b));
|
||||
}
|
||||
|
||||
/// Sorted period days -> runs; up to [gap] unmarked days inside one don't split it.
|
||||
List<Period> periodsOf(List<DateTime> days, Set<DateTime> calc) {
|
||||
final out = <Period>[];
|
||||
for (final d in days) {
|
||||
if (out.isNotEmpty && daysBetween(out.last.end, d) <= gap + 1) {
|
||||
out.last.end = d;
|
||||
out.last.calc = out.last.calc && calc.contains(d);
|
||||
} else {
|
||||
out.add(Period(d, d, calc.contains(d)));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool going(Period p, DateTime now) => !p.end.isBefore(plus(now, -1));
|
||||
|
||||
/// (length, start of the next period) between consecutive logged periods.
|
||||
List<(int, DateTime)> realCycles(List<Period> ps) => [
|
||||
for (var i = 0; i + 1 < ps.length; i++)
|
||||
if (!ps[i].calc && !ps[i + 1].calc) (daysBetween(ps[i].start, ps[i + 1].start), ps[i + 1].start)
|
||||
];
|
||||
|
||||
CycleStats stats(List<Period> ps, CycleSettings s, DateTime now) {
|
||||
final cyc = realCycles(ps);
|
||||
final ok = [for (final c in cyc) if (c.$1 >= 15 && c.$1 <= maxCycle) c];
|
||||
final lens = [for (final p in ps) if (!going(p, now) && !p.calc) (p.length, p.start)];
|
||||
return CycleStats(_avg(ok, s.cycleLength, now), _avg(lens, s.periodLength, now), [for (final c in cyc) c.$1],
|
||||
ok.isNotEmpty);
|
||||
}
|
||||
|
||||
/// The next n predicted periods (start, end) + days late (0 = not late).
|
||||
(List<(DateTime, DateTime)>, int) predict(List<Period> ps, CycleStats st, DateTime now, {int n = 4}) {
|
||||
if (ps.isEmpty) return (const [], 0);
|
||||
var next = plus(ps.last.start, st.cycle);
|
||||
final late = next.isBefore(now) ? daysBetween(next, now) : 0;
|
||||
if (late > 0) next = plus(now, st.cycle); // overdue: "any day now"; the one after counts from today
|
||||
return ([for (var k = 0; k < n; k++) (plus(next, k * st.cycle), plus(next, k * st.cycle + st.period - 1))], late);
|
||||
}
|
||||
|
||||
/// {day: "ovul" | "fertile"} before each given period start.
|
||||
Map<DateTime, String> fertile(List<DateTime> starts) {
|
||||
final out = <DateTime, String>{};
|
||||
for (final a in starts) {
|
||||
final ov = plus(a, -luteal);
|
||||
for (var k = -5; k <= 1; k++) {
|
||||
out[plus(ov, k)] = 'fertile';
|
||||
}
|
||||
out[ov] = 'ovul';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
enum Status { empty, period, late, wait }
|
||||
|
||||
/// Everything the Cycle page shows, from the synced rows.
|
||||
class CycleView {
|
||||
CycleView(SyncStore store, this.s, {DateTime? now}) : now = now ?? today() {
|
||||
for (final r in store.rows('cycle.day')) {
|
||||
final d = parseDay(r['day'] as String);
|
||||
logs[d] = DayLog(r);
|
||||
}
|
||||
final days = [for (final e in logs.entries) if (e.value.period) e.key]..sort();
|
||||
marked = days.toSet();
|
||||
final calc = {for (final e in logs.entries) if (e.value.source == 'calculated') e.key};
|
||||
periods = periodsOf(days, calc);
|
||||
st = stats(periods, s, this.now);
|
||||
final (p, l) = predict(periods, st, this.now);
|
||||
preds = p;
|
||||
late = l;
|
||||
final last = periods.isEmpty ? null : periods.last;
|
||||
if (last != null) {
|
||||
cycleDay = daysBetween(last.start, this.now) + 1;
|
||||
status = going(last, this.now) ? Status.period : late > 0 ? Status.late : Status.wait;
|
||||
}
|
||||
predDays = {for (final (a, z) in preds) for (var k = 0; k <= daysBetween(a, z); k++) plus(a, k)};
|
||||
if (status == Status.period) {
|
||||
for (var k = 0; k < st.period; k++) {
|
||||
if (plus(last!.start, k).isAfter(last.end)) predDays.add(plus(last.start, k));
|
||||
}
|
||||
}
|
||||
final starts = [for (final (a, _) in preds) a];
|
||||
if (last != null) starts.add(plus(last.start, st.cycle));
|
||||
fert = s.showFertile ? fertile(starts) : {};
|
||||
}
|
||||
|
||||
final CycleSettings s;
|
||||
final DateTime now;
|
||||
final logs = <DateTime, DayLog>{};
|
||||
late final Set<DateTime> marked;
|
||||
late final List<Period> periods;
|
||||
late final CycleStats st;
|
||||
late final List<(DateTime, DateTime)> preds;
|
||||
late final int late;
|
||||
late final Set<DateTime> predDays;
|
||||
late final Map<DateTime, String> fert;
|
||||
Status status = Status.empty;
|
||||
int? cycleDay;
|
||||
|
||||
Period? get last => periods.isEmpty ? null : periods.last;
|
||||
bool get todayOn => marked.contains(now);
|
||||
DateTime? get expected => last == null ? null : plus(last!.start, st.cycle);
|
||||
int? get daysToNext => preds.isEmpty ? null : daysBetween(now, preds.first.$1);
|
||||
|
||||
/// The fertile window that matters now (this cycle's if not over, else the next one's).
|
||||
(DateTime, DateTime, DateTime)? fertileWindow() {
|
||||
if (last == null || !s.showFertile) return null;
|
||||
for (final a in [plus(last!.start, st.cycle), ...preds.map((p) => p.$1)]) {
|
||||
final ov = plus(a, -luteal);
|
||||
if (!plus(ov, 1).isBefore(now)) return (plus(ov, -5), plus(ov, 1), ov);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- for a doctor (views.history's doctor part + views.flags) --------------------------------
|
||||
|
||||
const doctorMonths = 12;
|
||||
|
||||
class Doctor {
|
||||
Doctor({required this.since, required this.now, required this.last, required this.periods, required this.cycle,
|
||||
required this.cycleRange, required this.period, required this.periodRange, required this.symptoms,
|
||||
required this.painDays, required this.painAvg, required this.flags});
|
||||
final DateTime since, now;
|
||||
final DateTime? last;
|
||||
final int periods, painDays;
|
||||
final int? cycle, period;
|
||||
final (int, int)? cycleRange, periodRange;
|
||||
final List<(String, int)> symptoms;
|
||||
final double? painAvg;
|
||||
final List<String> flags;
|
||||
}
|
||||
|
||||
(int, int)? _spread(List<int> xs) => xs.isEmpty ? null : (xs.reduce(min), xs.reduce(max));
|
||||
|
||||
/// Things worth mentioning to a doctor (common guidance, not a diagnosis).
|
||||
List<String> flags(List<Period> ps, List<int> cycles, Map<DateTime, DayLog> logs, DateTime now) {
|
||||
final out = <String>[];
|
||||
final within = cycles.where((c) => c <= maxCycle).toList(); // longer = a gap in logging
|
||||
final recent = within.length > 6 ? within.sublist(within.length - 6) : within;
|
||||
final short = recent.where((c) => c < 21).length, long = recent.where((c) => c > 35).length;
|
||||
if (short >= 2) out.add('$short of the last ${recent.length} cycles were shorter than 21 days.');
|
||||
if (long >= 2) out.add('$long of the last ${recent.length} cycles were longer than 35 days.');
|
||||
if (recent.length >= 3 && recent.reduce(max) - recent.reduce(min) > 7) {
|
||||
out.add('Cycle length varies a lot: ${recent.reduce(min)}–${recent.reduce(max)} days.');
|
||||
}
|
||||
final finished = ps.where((p) => !going(p, now)).toList();
|
||||
final done = finished.length > 6 ? finished.sublist(finished.length - 6) : finished;
|
||||
final longp = done.where((p) => p.length > 7).length;
|
||||
if (longp > 0) out.add('$longp of the last ${done.length} periods lasted more than 7 days.');
|
||||
bool inside(Period p, DateTime d) => !d.isBefore(p.start) && !d.isAfter(p.end);
|
||||
final heavy = done.where((p) => logs.entries.where((e) => inside(p, e.key) && (e.value.flow ?? 0) >= 4).length >= 3).length;
|
||||
if (heavy > 0) out.add('$heavy of the last ${done.length} periods had 3 or more heavy days.');
|
||||
final since = plus(now, -90);
|
||||
final spot = logs.entries.where((e) => !e.key.isBefore(since) && e.value.tags.contains('spotting') && !e.value.period).length;
|
||||
if (spot > 0) out.add('Spotting between periods on $spot day${spot != 1 ? 's' : ''} in the last 3 months.');
|
||||
final strong = logs.entries.where((e) => !e.key.isBefore(since) && (e.value.pain ?? 0) >= 4).length;
|
||||
if (strong >= 3) out.add('Strong pain (4–5 of 5) on $strong days in the last 3 months.');
|
||||
if (ps.isNotEmpty && daysBetween(ps.last.start, now) > 90) out.add('No period for ${daysBetween(ps.last.start, now)} days.');
|
||||
return out;
|
||||
}
|
||||
|
||||
Doctor doctor(CycleView v) {
|
||||
final now = v.now, since = plus(now, -doctorMonths * 30);
|
||||
final real = v.periods.where((p) => !p.calc).toList();
|
||||
final dp = real.where((p) => !p.start.isBefore(since)).toList();
|
||||
final dcycles = [
|
||||
for (final (c, d) in realCycles(v.periods))
|
||||
if (!d.isBefore(since) && c <= maxCycle && !plus(d, -c).isBefore(since)) c
|
||||
];
|
||||
final dlens = [for (final p in dp) if (!going(p, now)) p.length];
|
||||
final names = {for (final g in tagGroups.values) ...g};
|
||||
final counts = <String, int>{};
|
||||
final pains = <int>[];
|
||||
for (final e in v.logs.entries.where((e) => !e.key.isBefore(since))) {
|
||||
for (final t in e.value.tags) {
|
||||
if (tagGroups['Symptoms']!.containsKey(t) || tagGroups['Mood']!.containsKey(t)) counts[t] = (counts[t] ?? 0) + 1;
|
||||
}
|
||||
if (e.value.pain != null) pains.add(e.value.pain!);
|
||||
}
|
||||
final sym = [for (final e in counts.entries) (names[e.key]!, e.value)]..sort((a, b) => b.$2.compareTo(a.$2));
|
||||
return Doctor(
|
||||
since: dp.isNotEmpty && dp.first.start.isAfter(since) ? dp.first.start : since,
|
||||
now: now,
|
||||
last: real.isEmpty ? null : real.last.start,
|
||||
periods: dp.length,
|
||||
cycle: dcycles.isEmpty ? null : pyRound(dcycles.reduce((a, b) => a + b) / dcycles.length),
|
||||
cycleRange: _spread(dcycles),
|
||||
period: dlens.isEmpty ? null : pyRound(dlens.reduce((a, b) => a + b) / dlens.length),
|
||||
periodRange: _spread(dlens),
|
||||
symptoms: sym.take(10).toList(),
|
||||
painDays: pains.length,
|
||||
painAvg: pains.isEmpty ? null : pyRound(pains.reduce((a, b) => a + b) / pains.length * 10) / 10,
|
||||
flags: flags(real, v.st.cycles, v.logs, now),
|
||||
);
|
||||
}
|
||||
|
||||
/// db.save_day: set the given fields of a day (the rest stay); a day with nothing left is deleted.
|
||||
void saveDay(SyncStore store, DateTime d, Map<String, dynamic> fields) {
|
||||
if (d.isAfter(today())) throw ArgumentError("That day hasn't happened yet.");
|
||||
final u = 'day:${iso(d)}';
|
||||
final row = store.row('cycle.day', u) ??
|
||||
{'day': iso(d), 'period': 0, 'note': '', 'flow': null, 'pain': null, 'pain_len': null, 'tags': '', 'source': null};
|
||||
row.addAll(fields);
|
||||
if (fields.containsKey('tags')) {
|
||||
final picked = (fields['tags'] as List).cast<String>().toSet();
|
||||
row['tags'] = [for (final g in tagGroups.values) ...g.keys.where(picked.contains)].join(','); // stable order
|
||||
}
|
||||
final now = DateTime.now();
|
||||
row['updated'] = '${iso(now)} ${now.toIso8601String().substring(11, 19)}';
|
||||
final empty = row['period'] != 1 && (row['note'] ?? '') == '' && row['flow'] == null && row['pain'] == null &&
|
||||
row['pain_len'] == null && (row['tags'] ?? '') == '';
|
||||
if (empty) {
|
||||
if (store.row('cycle.day', u) != null) store.delete('cycle.day', u);
|
||||
} else {
|
||||
store.put('cycle.day', u, row);
|
||||
}
|
||||
}
|
||||
351
app/lib/health/cycle_page.dart
Normal file
351
app/lib/health/cycle_page.dart
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
// The Cycle page (Health ▸ Cycle): the status ring + one button for today (as on the web page),
|
||||
// the month calendar, and a day's log as a sheet. Phone difference: tapping a day opens its log; holding
|
||||
// it marks / unmarks it as a period day (the web's click — not on a tap, so no marks by a stray tap; Undo).
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'cycle_model.dart';
|
||||
|
||||
const periodRed = Color(0xFFE5576B), fertileTeal = Color(0xFF3FB5A0);
|
||||
const _months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
|
||||
'November', 'December'];
|
||||
const _dows = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||||
String niceDay(DateTime d) => '${_dows[d.weekday - 1]} ${d.day} ${_months[d.month - 1].substring(0, 3)}';
|
||||
|
||||
class CyclePage extends StatefulWidget {
|
||||
const CyclePage({super.key, required this.sync});
|
||||
final SyncService sync;
|
||||
@override
|
||||
State<CyclePage> createState() => _CyclePageState();
|
||||
}
|
||||
|
||||
class _CyclePageState extends State<CyclePage> {
|
||||
int offset = 0; // months from this one
|
||||
final settings = const CycleSettings(); // TODO: from synced settings once those sync (Pi: 28 / 5 / fertile on)
|
||||
|
||||
void _save(DateTime d, Map<String, dynamic> fields) {
|
||||
saveDay(widget.sync.store, d, fields);
|
||||
widget.sync.changed();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: widget.sync,
|
||||
builder: (context, _) {
|
||||
final v = CycleView(widget.sync.store, settings);
|
||||
final status = _StatusCard(v: v, onToday: (on) => _save(v.now, {'period': on ? 1 : 0}));
|
||||
final month = _Month(v: v, offset: offset, onMove: (d) => setState(() => offset += d), onDay: (d) => _openDay(v, d),
|
||||
onHold: (d) => _toggle(v, d));
|
||||
return LayoutBuilder(builder: (context, box) {
|
||||
if (box.maxWidth >= 700) { // landscape / tablet: side by side
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(12, 12, 12, 24),
|
||||
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Expanded(flex: 2, child: status),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(flex: 3, child: month),
|
||||
]),
|
||||
);
|
||||
}
|
||||
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
|
||||
status,
|
||||
const SizedBox(height: 12),
|
||||
month,
|
||||
]);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
/// Hold a day: period on that day on / off at once (the web calendar's click); Undo in the snackbar.
|
||||
void _toggle(CycleView v, DateTime d) {
|
||||
if (d.isAfter(v.now)) return;
|
||||
final was = v.marked.contains(d);
|
||||
HapticFeedback.mediumImpact();
|
||||
_save(d, {'period': was ? 0 : 1});
|
||||
final m = ScaffoldMessenger.of(context);
|
||||
m.hideCurrentSnackBar();
|
||||
m.showSnackBar(SnackBar(
|
||||
content: Text('${was ? 'Not a period day' : 'Period'}: ${niceDay(d)}'),
|
||||
duration: const Duration(seconds: 4),
|
||||
persist: false, // with an action Flutter keeps it up until tapped
|
||||
action: SnackBarAction(label: 'Undo', textColor: accent, onPressed: () => _save(d, {'period': was ? 1 : 0})),
|
||||
));
|
||||
}
|
||||
|
||||
Future<void> _openDay(CycleView v, DateTime d) async {
|
||||
if (d.isAfter(v.now)) return;
|
||||
await showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => DaySheet(day: d, log: v.logs[d], onSave: (f) => _save(d, f)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The status card's two lines (also Health ▸ Overview's period tile).
|
||||
(String, String) cycleStatus(CycleView v) => switch (v.status) {
|
||||
Status.empty => ('No periods logged yet', 'Mark the first day of your period.'),
|
||||
Status.period => ('Period · day ${v.cycleDay}', 'since ${niceDay(v.last!.start)}'),
|
||||
Status.late => ('${v.late} ${v.late == 1 ? 'day' : 'days'} late', 'expected ${niceDay(v.expected!)}'),
|
||||
Status.wait => (
|
||||
v.daysToNext == 0 ? 'Period expected today' : 'Next period in ${v.daysToNext} ${v.daysToNext == 1 ? 'day' : 'days'}',
|
||||
'${niceDay(v.preds.first.$1)} · cycle day ${v.cycleDay}'),
|
||||
};
|
||||
|
||||
class _StatusCard extends StatelessWidget {
|
||||
const _StatusCard({required this.v, required this.onToday});
|
||||
final CycleView v;
|
||||
final void Function(bool on) onToday;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final t = Theme.of(context).textTheme;
|
||||
final (head, sub) = cycleStatus(v);
|
||||
final button = v.todayOn ? 'Not today — undo' : v.status == Status.period ? 'Period today too' : 'Period started today';
|
||||
final fw = v.fertileWindow();
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
SizedBox(width: 96, height: 96, child: CustomPaint(painter: _Ring(v), child: Center(
|
||||
child: Text(v.cycleDay == null || v.status == Status.late ? '' : '${v.cycleDay}',
|
||||
style: t.headlineMedium?.copyWith(fontWeight: FontWeight.bold))))),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(head, style: t.titleLarge?.copyWith(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 2),
|
||||
Text(sub, style: const TextStyle(color: muted)),
|
||||
if (fw != null) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(fw.$1.isAfter(v.now) ? 'Fertile ${niceDay(fw.$1)} – ${niceDay(fw.$2)}' : 'Fertile window now, until ${niceDay(fw.$2)}',
|
||||
style: const TextStyle(color: fertileTeal)),
|
||||
],
|
||||
])),
|
||||
]),
|
||||
const SizedBox(height: 14),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: v.todayOn ? card2 : periodRed, foregroundColor: Colors.white),
|
||||
onPressed: () => onToday(!v.todayOn),
|
||||
child: Text(button),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Tooltip(
|
||||
message: v.st.fromData ? 'Recent cycles count more (half as much every 180 days of age)' : 'From the settings until there are logged cycles',
|
||||
child: Text('Usual cycle ${v.st.cycle} days · period ${v.st.period} days',
|
||||
textAlign: TextAlign.center, style: const TextStyle(color: muted, fontSize: 13)),
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cycle as a circle: the period arc, the fertile arc, today's dot (cycle.views.ring).
|
||||
class _Ring extends CustomPainter {
|
||||
_Ring(this.v);
|
||||
final CycleView v;
|
||||
|
||||
@override
|
||||
void paint(Canvas c, Size size) {
|
||||
final r = size.width / 2 - 6, o = Offset(size.width / 2, size.height / 2);
|
||||
final n = max(v.st.cycle, max(v.cycleDay ?? 0, 1));
|
||||
Paint p(Color col, double w) => Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = w..strokeCap = StrokeCap.round;
|
||||
c.drawCircle(o, r, p(card2, 8));
|
||||
if (v.last == null) return;
|
||||
void arc(int d0, int d1, Color col) {
|
||||
final a0 = (d0 - 1) / n * 2 * pi - pi / 2, sweep = (d1 - d0 + 1) / n * 2 * pi;
|
||||
c.drawArc(Rect.fromCircle(center: o, radius: r), a0, sweep, false, p(col, 8));
|
||||
}
|
||||
arc(1, min(v.st.period, n), periodRed);
|
||||
final ov = v.st.cycle - luteal;
|
||||
if (v.s.showFertile && ov - 5 > v.st.period) arc(ov - 5, ov + 1, fertileTeal);
|
||||
if (v.cycleDay != null && v.status != Status.late) {
|
||||
final a = (v.cycleDay! - .5) / n * 2 * pi - pi / 2;
|
||||
final at = o + Offset(cos(a), sin(a)) * r;
|
||||
c.drawCircle(at, 8.5, Paint()..color = card); // the web's dot outline (stroke: var(--card))
|
||||
c.drawCircle(at, 7, Paint()..color = Colors.white);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _Ring old) => true;
|
||||
}
|
||||
|
||||
class _Month extends StatelessWidget {
|
||||
const _Month({required this.v, required this.offset, required this.onMove, required this.onDay, required this.onHold});
|
||||
final CycleView v;
|
||||
final int offset;
|
||||
final void Function(int) onMove;
|
||||
final void Function(DateTime) onDay, onHold;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final m0 = DateTime.utc(v.now.year, v.now.month + offset, 1);
|
||||
final g0 = plus(m0, -(m0.weekday - 1));
|
||||
final mEnd = DateTime.utc(m0.year, m0.month + 1, 0);
|
||||
final g1 = plus(mEnd, 7 - mEnd.weekday);
|
||||
final weeks = <List<DateTime>>[];
|
||||
for (var d = g0; !d.isAfter(g1); d = plus(d, 7)) {
|
||||
weeks.add([for (var k = 0; k < 7; k++) plus(d, k)]);
|
||||
}
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 4, 8, 12),
|
||||
child: Column(children: [
|
||||
Row(children: [
|
||||
IconButton(onPressed: () => onMove(-1), icon: const Icon(Icons.chevron_left)),
|
||||
Expanded(child: Text('${_months[m0.month - 1]} ${m0.year}', textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold))),
|
||||
IconButton(onPressed: offset < 12 ? () => onMove(1) : null, icon: const Icon(Icons.chevron_right)),
|
||||
]),
|
||||
Row(children: [for (final d in _dows) Expanded(child: Text(d, textAlign: TextAlign.center, style: const TextStyle(color: muted, fontSize: 12)))]),
|
||||
const SizedBox(height: 4),
|
||||
for (final w in weeks)
|
||||
Row(children: [for (final d in w) Expanded(child: _Cell(v: v, d: d, out: d.month != m0.month, onTap: () => onDay(d), onHold: () => onHold(d)))]),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Cell extends StatelessWidget {
|
||||
const _Cell({required this.v, required this.d, required this.out, required this.onTap, required this.onHold});
|
||||
final CycleView v;
|
||||
final DateTime d;
|
||||
final bool out;
|
||||
final VoidCallback onTap, onHold; // tap = the day's log, hold = period on / off
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final on = v.marked.contains(d), pred = !on && v.predDays.contains(d), fert = on ? null : v.fert[d];
|
||||
final log = v.logs[d];
|
||||
final isToday = d == v.now, future = d.isAfter(v.now);
|
||||
final syms = log?.symbolList ?? const [];
|
||||
return GestureDetector(
|
||||
onTap: future ? null : onTap,
|
||||
onLongPress: future ? null : onHold,
|
||||
child: Opacity(
|
||||
opacity: out ? 0.35 : 1,
|
||||
child: Container(
|
||||
height: MediaQuery.of(context).orientation == Orientation.landscape ? 44 : 52,
|
||||
margin: const EdgeInsets.all(1.5),
|
||||
decoration: BoxDecoration(
|
||||
color: fert != null ? fertileTeal.withValues(alpha: 0.14) : null,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: isToday ? Border.all(color: accent, width: 1.5) : null,
|
||||
),
|
||||
child: Stack(children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: 32, height: 32,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: on ? periodRed.withValues(alpha: 0.35 + 0.13 * ((log?.flow ?? 3) - 1)) : null,
|
||||
border: pred ? Border.all(color: periodRed, width: 1.5) : fert == 'ovul' ? Border.all(color: fertileTeal, width: 2) : null,
|
||||
),
|
||||
child: Text('${d.day}', style: TextStyle(color: future ? muted : Colors.white, fontWeight: isToday ? FontWeight.bold : null)),
|
||||
),
|
||||
),
|
||||
if (syms.isNotEmpty)
|
||||
Positioned(left: 3, top: 1, child: Text(syms.map((s) => s.$1 == 'spot' ? '•' : s.$1).join(), style: const TextStyle(fontSize: 9))),
|
||||
if (log?.hasLog ?? false) const Positioned(right: 4, top: 3, child: Icon(Icons.edit, size: 9, color: accent)),
|
||||
if (sources[log?.source] != null)
|
||||
Positioned(left: 3, bottom: 1, child: Text(sources[log!.source]!.$1, style: const TextStyle(fontSize: 8, color: muted))),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A day's log: period on / off + flow, pain + how long, tags, note — saved together.
|
||||
class DaySheet extends StatefulWidget {
|
||||
const DaySheet({super.key, required this.day, required this.log, required this.onSave});
|
||||
final DateTime day;
|
||||
final DayLog? log;
|
||||
final void Function(Map<String, dynamic>) onSave;
|
||||
@override
|
||||
State<DaySheet> createState() => _DaySheetState();
|
||||
}
|
||||
|
||||
class _DaySheetState extends State<DaySheet> {
|
||||
late bool period = widget.log?.period ?? false;
|
||||
late int? flow = widget.log?.flow, pain = widget.log?.pain;
|
||||
late String? len = widget.log?.painLength;
|
||||
late final Set<String> tags = {...?widget.log?.tags};
|
||||
late final note = TextEditingController(text: widget.log?.note ?? '');
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
|
||||
child: DraggableScrollableSheet(
|
||||
expand: false,
|
||||
initialChildSize: 0.75,
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scroll) => ListView(controller: scroll, padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), children: [
|
||||
Center(child: Container(width: 36, height: 4, decoration: BoxDecoration(color: muted, borderRadius: BorderRadius.circular(2)))),
|
||||
const SizedBox(height: 12),
|
||||
Text(niceDay(widget.day), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: accent)),
|
||||
SwitchListTile(contentPadding: EdgeInsets.zero, title: const Text('Period day'), value: period,
|
||||
activeThumbColor: periodRed, onChanged: (x) => setState(() => period = x)),
|
||||
if (period) ...[
|
||||
const Text('Flow', style: TextStyle(color: muted)),
|
||||
Row(children: [
|
||||
for (var i = 1; i <= 5; i++)
|
||||
IconButton(
|
||||
tooltip: flowNames[i - 1],
|
||||
onPressed: () => setState(() => flow = flow == i ? null : i),
|
||||
icon: Icon(Icons.water_drop, size: 16.0 + i * 3, color: (flow ?? 0) >= i ? periodRed : card2),
|
||||
),
|
||||
]),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
const Text('Pain', style: TextStyle(color: muted)),
|
||||
Wrap(spacing: 6, children: [
|
||||
for (var i = 1; i <= 5; i++)
|
||||
ChoiceChip(label: Text('$i'), selected: pain == i, onSelected: (x) => setState(() => pain = x ? i : null)),
|
||||
]),
|
||||
if (pain != null)
|
||||
Wrap(spacing: 6, children: [
|
||||
for (final e in painLen.entries)
|
||||
ChoiceChip(label: Text(e.value), selected: len == e.key, onSelected: (x) => setState(() => len = x ? e.key : null)),
|
||||
]),
|
||||
for (final g in tagGroups.entries) ...[
|
||||
const SizedBox(height: 10),
|
||||
Text(g.key, style: const TextStyle(color: muted)),
|
||||
Wrap(spacing: 6, runSpacing: 2, children: [
|
||||
for (final t in g.value.entries)
|
||||
FilterChip(
|
||||
label: Text(t.value),
|
||||
selected: tags.contains(t.key),
|
||||
onSelected: (x) => setState(() {
|
||||
x ? tags.add(t.key) : tags.remove(t.key);
|
||||
if (x && t.key == 'drive') tags.remove('drive_low'); // exclusive, like the web page
|
||||
if (x && t.key == 'drive_low') tags.remove('drive');
|
||||
}),
|
||||
),
|
||||
]),
|
||||
],
|
||||
const SizedBox(height: 10),
|
||||
TextField(controller: note, maxLines: 3, maxLength: 2000, decoration: const InputDecoration(labelText: 'Note')),
|
||||
const SizedBox(height: 8),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
widget.onSave({'period': period ? 1 : 0, 'flow': flow, 'pain': pain, 'pain_len': pain == null ? null : len,
|
||||
'tags': tags.toList(), 'note': note.text.trim()});
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Save'),
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
226
app/lib/health/food_archive.dart
Normal file
226
app/lib/health/food_archive.dart
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
// Every Open Food Facts product (2 million+, every country), searched on the sync server's archive
|
||||
// (GET /v1/food/search — sync-server/src/food.php), with filters: country, brand, Nutri-Score; a
|
||||
// barcode finds that product. A pick is kept ("food.product", food_model.dart keepProduct) and synced,
|
||||
// so entries made from it work on every device. Also the camera barcode scanner (ZXing, no Google services).
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:flutter_zxing/flutter_zxing.dart' show Format;
|
||||
|
||||
import '../app/scanner.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'food_model.dart';
|
||||
|
||||
const _countries = [('', 'Any country'), ('ro', 'Romania'), ('sk', 'Slovakia'), ('cz', 'Czechia'), ('hu', 'Hungary'), ('at', 'Austria'),
|
||||
('de', 'Germany'), ('pl', 'Poland'), ('it', 'Italy'), ('fr', 'France'), ('es', 'Spain'), ('uk', 'UK'), ('us', 'USA')];
|
||||
const _scores = [('', 'Any Nutri-Score'), ('a', 'A'), ('ab', 'A–B'), ('abc', 'A–C')];
|
||||
|
||||
/// The archive's search: [q] (or a barcode), filters → its products (as it sends them), or throws a message.
|
||||
Future<List<Map<String, dynamic>>> archiveSearch(SyncService sync, Map<String, String> p) async {
|
||||
final s = sync.settings;
|
||||
final query = {for (final e in p.entries) if (e.value.isNotEmpty) e.key: e.value, 'limit': '25'};
|
||||
final uri = Uri.parse('${s.server.replaceAll(RegExp(r'/+$'), '')}/v1/food/search').replace(queryParameters: query);
|
||||
final http.Response r;
|
||||
try {
|
||||
r = await http.get(uri, headers: {'Authorization': 'Bearer ${s.token}', 'Accept': 'application/json'})
|
||||
.timeout(const Duration(seconds: 20));
|
||||
} catch (_) {
|
||||
throw 'The sync server can\'t be reached — no connection?';
|
||||
}
|
||||
final j = jsonDecode(r.body);
|
||||
if (r.statusCode != 200) throw (j is Map ? j['error'] : null) ?? 'Error ${r.statusCode}';
|
||||
return ((j as Map)['items'] as List).cast<Map<String, dynamic>>();
|
||||
}
|
||||
|
||||
/// The archive's search sheet → the product picked (kept already), or null.
|
||||
Future<Food?> openArchive(BuildContext context, SyncService sync, FoodDb? fdb, String q) => showModalBottomSheet<Food>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => ArchiveSheet(sync: sync, fdb: fdb, q: q),
|
||||
);
|
||||
|
||||
class ArchiveSheet extends StatefulWidget {
|
||||
const ArchiveSheet({super.key, required this.sync, required this.fdb, required this.q});
|
||||
final SyncService sync;
|
||||
final FoodDb? fdb;
|
||||
final String q;
|
||||
@override
|
||||
State<ArchiveSheet> createState() => _ArchiveSheetState();
|
||||
}
|
||||
|
||||
class _ArchiveSheetState extends State<ArchiveSheet> {
|
||||
late final q = TextEditingController(text: widget.q);
|
||||
final brand = TextEditingController();
|
||||
String country = '', score = '';
|
||||
List<Map<String, dynamic>> items = [];
|
||||
String? status;
|
||||
Timer? timer;
|
||||
int seq = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_run();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _soon() {
|
||||
timer?.cancel();
|
||||
timer = Timer(const Duration(milliseconds: 350), _run);
|
||||
}
|
||||
|
||||
Future<void> _run() async {
|
||||
final text = q.text.trim(), n = ++seq;
|
||||
final code = RegExp(r'^\d{8,14}$').hasMatch(text);
|
||||
if (!code && text.length < 3 && brand.text.trim().isEmpty && country.isEmpty) {
|
||||
setState(() {
|
||||
items = [];
|
||||
status = 'Type at least 3 letters, or pick a filter.';
|
||||
});
|
||||
return;
|
||||
}
|
||||
setState(() => status = 'Searching…');
|
||||
try {
|
||||
final got = await archiveSearch(widget.sync, {
|
||||
if (code) 'barcode': text else 'q': text,
|
||||
'country': country, 'brand': brand.text.trim(), 'nutriscore': score,
|
||||
});
|
||||
if (!mounted || n != seq) return;
|
||||
setState(() {
|
||||
items = got;
|
||||
status = got.isEmpty ? 'Nothing found.' : null;
|
||||
});
|
||||
} catch (e) {
|
||||
if (mounted && n == seq) {
|
||||
setState(() {
|
||||
items = [];
|
||||
status = '$e';
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String _home(String c) {
|
||||
final cs = c.split(' ').where((x) => x.isNotEmpty).toList();
|
||||
return cs.take(3).map((x) => x[0].toUpperCase() + x.substring(1).replaceAll('-', ' ')).join(', ') + (cs.length > 3 ? ' …' : '');
|
||||
}
|
||||
|
||||
void _pick(Map<String, dynamic> it) {
|
||||
final id = (it['id'] as num).toInt();
|
||||
final f = widget.fdb?.food(id) ?? keepProduct(widget.sync.store, it); // one you have already: that one
|
||||
if (f == null) {
|
||||
setState(() => status = 'That product came back garbled.');
|
||||
return;
|
||||
}
|
||||
widget.sync.changed();
|
||||
Navigator.of(context).pop(f);
|
||||
}
|
||||
|
||||
Widget _drop(List<(String, String)> opts, String value, void Function(String) set) => DropdownButton<String>(
|
||||
value: value,
|
||||
isDense: true,
|
||||
underline: const SizedBox(),
|
||||
dropdownColor: card2,
|
||||
items: [for (final (k, l) in opts) DropdownMenuItem(value: k, child: Text(l, style: const TextStyle(fontSize: 13.5)))],
|
||||
onChanged: (v) {
|
||||
set(v ?? '');
|
||||
_run();
|
||||
},
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final h = MediaQuery.of(context).size.height;
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: h * 0.85),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
const Text('All products', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||||
const Text('Open Food Facts — every country, through the sync server', style: TextStyle(color: muted, fontSize: 12.5)),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: q,
|
||||
autofocus: widget.q.isEmpty,
|
||||
decoration: InputDecoration(
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
hintText: 'Name, brand or barcode…',
|
||||
suffixIcon: IconButton(
|
||||
tooltip: 'Scan a barcode',
|
||||
icon: const Icon(Icons.qr_code_scanner),
|
||||
onPressed: () async {
|
||||
final code = await scanBarcode(context);
|
||||
if (code != null) {
|
||||
q.text = code;
|
||||
_run();
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
onChanged: (_) => _soon(),
|
||||
onSubmitted: (_) => _run(),
|
||||
),
|
||||
Wrap(spacing: 12, crossAxisAlignment: WrapCrossAlignment.center, children: [
|
||||
_drop(_countries, country, (v) => country = v),
|
||||
_drop(_scores, score, (v) => score = v),
|
||||
SizedBox(
|
||||
width: 120,
|
||||
child: TextField(
|
||||
controller: brand,
|
||||
style: const TextStyle(fontSize: 13.5),
|
||||
decoration: const InputDecoration(isDense: true, hintText: 'Brand'),
|
||||
onChanged: (_) => _soon(),
|
||||
),
|
||||
),
|
||||
]),
|
||||
if (status != null) Padding(padding: const EdgeInsets.only(top: 10), child: Text(status!, style: const TextStyle(color: muted))),
|
||||
Flexible(
|
||||
child: ListView(shrinkWrap: true, children: [
|
||||
for (final it in items)
|
||||
ListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('${it['name']}', maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
subtitle: Text(
|
||||
[
|
||||
if ('${it['brand'] ?? ''}'.isNotEmpty) '${it['brand']}',
|
||||
_home('${it['countries'] ?? ''}'),
|
||||
if (widget.fdb?.food((it['id'] as num).toInt()) != null) '✓ you have it',
|
||||
].where((x) => x.isNotEmpty).join(' · '),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(color: muted),
|
||||
),
|
||||
trailing: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [
|
||||
Text('${((it['per100'] as Map?)?['kcal'] as num? ?? 0).round()} kcal', style: const TextStyle(fontSize: 13.5)),
|
||||
if (it['nutriscore'] != null)
|
||||
Text('Nutri-Score ${'${it['nutriscore']}'.toUpperCase()}', style: const TextStyle(color: muted, fontSize: 11.5)),
|
||||
]),
|
||||
onTap: () => _pick(it),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera, until a product barcode (EAN / UPC) is read → its digits, or null (closed) — app/scanner.dart.
|
||||
Future<String?> scanBarcode(BuildContext context) => scanCode(context,
|
||||
title: 'Scan a barcode',
|
||||
format: Format.ean13 | Format.ean8 | Format.upca | Format.upce,
|
||||
accept: (v) => RegExp(r'^\d{8,14}$').hasMatch(v));
|
||||
208
app/lib/health/food_history.dart
Normal file
208
app/lib/health/food_history.dart
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
// Food ▸ History (views.history): over the shared Health period — tiles (the average *logged* day:
|
||||
// empty days don't count as zero; days logged + within 10 % of the target; protein, fibre; where the
|
||||
// energy came from), energy per day (per week from 120 days: the average logged day) stacked by macro
|
||||
// with the target as a dashed line (tap a bar = its numbers), and the foods eaten most.
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'cycle_model.dart' show daysBetween, parseDay, plus, today;
|
||||
import 'food_model.dart';
|
||||
import 'food_page.dart' show macroColors;
|
||||
import '../widgets/line_chart.dart' show RangeChip;
|
||||
import 'range.dart';
|
||||
|
||||
const weeklyFrom = 120;
|
||||
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
|
||||
class FoodHistoryPage extends StatefulWidget {
|
||||
const FoodHistoryPage({super.key, required this.sync, required this.range});
|
||||
final SyncService sync;
|
||||
final HealthRange range;
|
||||
@override
|
||||
State<FoodHistoryPage> createState() => _FoodHistoryPageState();
|
||||
}
|
||||
|
||||
class _FoodHistoryPageState extends State<FoodHistoryPage> {
|
||||
String? tip;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Scaffold(
|
||||
appBar: AppBar(title: const Text('Food history')),
|
||||
body: ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.sync, widget.range]),
|
||||
builder: (context, _) {
|
||||
final store = widget.sync.store;
|
||||
final now = today();
|
||||
final first = store.db.select("SELECT min(json_extract(data, '\$.day')) AS d FROM rec WHERE t = 'food.entry'").first['d'] as String?;
|
||||
final a = widget.range.from(first == null ? now : parseDay(first), now);
|
||||
final days = dayTotals(store, dayIso(a), dayIso(now));
|
||||
final logged = days.values.where((v) => (v['kcal'] ?? 0) > 0).toList();
|
||||
double? avg(String k) => logged.isEmpty ? null : logged.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / logged.length;
|
||||
final target = targets(store, FoodSettings.of(store))['kcal']!.$1;
|
||||
final onTarget = logged.where((v) => ((v['kcal'] ?? 0) - target).abs() <= target * 0.1).length;
|
||||
final e = {for (final m in macros) m: (avg(m) ?? 0) * kcalPerG[m]!};
|
||||
final tot = e.values.fold<double>(0, (x, y) => x + y);
|
||||
final top = topFoods(store, dayIso(a), dayIso(now));
|
||||
String r(double? v) => v == null ? '—' : v.round().toString();
|
||||
return ListView(padding: const EdgeInsets.all(12), children: [
|
||||
GridView.count(
|
||||
crossAxisCount: MediaQuery.of(context).size.width >= 700 ? 4 : 2,
|
||||
shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
|
||||
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.9,
|
||||
children: [
|
||||
_tile('Average day', '${r(avg('kcal'))} kcal', 'target ${target.round()}'),
|
||||
_tile('Days logged', '${logged.length} of ${daysBetween(a, now) + 1}', '$onTarget within 10 % of target'),
|
||||
_tile('Protein', '${r(avg('protein'))} g', 'a logged day on average'),
|
||||
_tile('Fibre', '${r(avg('fiber'))} g', 'at least 25 g'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
if (tot > 0)
|
||||
Card(child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
const Text('Where the energy came from', style: TextStyle(color: muted, fontSize: 13)),
|
||||
const SizedBox(height: 6),
|
||||
ClipRRect(borderRadius: BorderRadius.circular(5), child: Row(children: [
|
||||
for (final m in macros) Expanded(flex: max(1, (100 * e[m]! / tot).round()),
|
||||
child: Container(height: 12, color: macroColors[m])),
|
||||
])),
|
||||
const SizedBox(height: 4),
|
||||
Text(macros.map((m) => '${m[0].toUpperCase()}${m.substring(1)} ${(100 * e[m]! / tot).round()} %').join(' · '),
|
||||
style: const TextStyle(fontSize: 13)),
|
||||
]),
|
||||
)),
|
||||
const SizedBox(height: 10),
|
||||
Card(child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(10, 10, 10, 6),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
const Expanded(child: Text('Energy per day', style: TextStyle(fontWeight: FontWeight.bold))),
|
||||
RangeChip(widget.range),
|
||||
]),
|
||||
const SizedBox(height: 8),
|
||||
_Bars(days: days, a: a, z: now, target: target, onTip: (t) => setState(() => tip = t)),
|
||||
SizedBox(height: 20, child: Text(tip ?? 'Tap a bar for its numbers', textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: muted, fontSize: 12.5))),
|
||||
]),
|
||||
)),
|
||||
const SizedBox(height: 10),
|
||||
if (top.isNotEmpty)
|
||||
Card(child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
const Text('Eaten most', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
for (final (name, n, kcal) in top)
|
||||
Padding(padding: const EdgeInsets.symmetric(vertical: 4), child: Row(children: [
|
||||
Expanded(child: Text(name)),
|
||||
Text('$n× · ${kcal.round()} kcal', style: const TextStyle(color: muted)),
|
||||
])),
|
||||
]),
|
||||
)),
|
||||
]);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
Widget _tile(String label, String value, String sub) => Card(child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||||
Text(value, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
|
||||
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)),
|
||||
]),
|
||||
));
|
||||
}
|
||||
|
||||
/// Bars per day (or per week, the average logged day), stacked protein / carbs / fat by energy, the rest grey.
|
||||
class _Bars extends StatelessWidget {
|
||||
const _Bars({required this.days, required this.a, required this.z, required this.target, required this.onTip});
|
||||
final Map<String, Map<String, double>> days;
|
||||
final DateTime a, z;
|
||||
final double target;
|
||||
final void Function(String) onTip;
|
||||
|
||||
List<(DateTime, List<Map<String, double>>, String)> _buckets() {
|
||||
final n = daysBetween(a, z) + 1;
|
||||
final out = <(DateTime, List<Map<String, double>>, String)>[];
|
||||
if (n >= weeklyFrom) {
|
||||
for (var s = plus(a, -(a.weekday - 1)); !s.isAfter(z); s = plus(s, 7)) {
|
||||
final vs = [for (var i = 0; i < 7; i++) days[dayIso(plus(s, i))]].whereType<Map<String, double>>()
|
||||
.where((v) => (v['kcal'] ?? 0) > 0).toList();
|
||||
out.add((s, vs, 'Week of ${s.day} ${_mon[s.month - 1]} ${s.year}'));
|
||||
}
|
||||
} else {
|
||||
for (var i = 0; i < n; i++) {
|
||||
final x = plus(a, i), v = days[dayIso(x)];
|
||||
out.add((x, v != null && (v['kcal'] ?? 0) > 0 ? [v] : [], '${x.day} ${_mon[x.month - 1]} ${x.year}'));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final b = _buckets();
|
||||
return LayoutBuilder(builder: (context, box) => GestureDetector(
|
||||
onTapDown: (d) {
|
||||
final i = (d.localPosition.dx / box.maxWidth * b.length).floor().clamp(0, b.length - 1);
|
||||
final (_, vs, label) = b[i];
|
||||
if (vs.isEmpty) return onTip('$label · nothing logged');
|
||||
double av(String k) => vs.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / vs.length;
|
||||
onTip('$label · ${av('kcal').round()} kcal${vs.length > 1 ? ' (${vs.length} days)' : ''} · '
|
||||
'P ${av('protein').round()} g, C ${av('carbs').round()} g, F ${av('fat').round()} g');
|
||||
},
|
||||
child: CustomPaint(size: Size(box.maxWidth, 170), painter: _BarsPainter(b, target)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
class _BarsPainter extends CustomPainter {
|
||||
_BarsPainter(this.b, this.target);
|
||||
final List<(DateTime, List<Map<String, double>>, String)> b;
|
||||
final double target;
|
||||
|
||||
@override
|
||||
void paint(Canvas c, Size size) {
|
||||
const mb = 16.0;
|
||||
final h = size.height - mb;
|
||||
double avg(List<Map<String, double>> vs, String k) => vs.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / vs.length;
|
||||
final peak = [target * 1.25, for (final (_, vs, _) in b) if (vs.isNotEmpty) avg(vs, 'kcal')].reduce(max);
|
||||
double y(double k) => h - h * k / peak;
|
||||
final bw = size.width / max(1, b.length), pad = bw > 4 ? bw * 0.18 : 0.0;
|
||||
for (var i = 0; i < b.length; i++) {
|
||||
final (x, vs, _) = b[i];
|
||||
if (vs.isNotEmpty) {
|
||||
final k = avg(vs, 'kcal');
|
||||
final e = {for (final m in macros) m: avg(vs, m) * kcalPerG[m]!};
|
||||
final sum = e.values.reduce((p, q) => p + q);
|
||||
final scale = sum > k ? k / sum : 1.0; // labels' macros can add up past the kcal
|
||||
var base = 0.0;
|
||||
for (final m in macros) {
|
||||
final hh = e[m]! * scale;
|
||||
if (hh > 0) c.drawRect(Rect.fromLTRB(i * bw + pad, y(base + hh), (i + 1) * bw - pad, y(base)), Paint()..color = macroColors[m]!);
|
||||
base += hh;
|
||||
}
|
||||
if (k - base > 1) c.drawRect(Rect.fromLTRB(i * bw + pad, y(k), (i + 1) * bw - pad, y(base)), Paint()..color = muted);
|
||||
}
|
||||
final weekly = b.length > 1 && b[1].$1.difference(b[0].$1).inDays == 7;
|
||||
final label = weekly ? (x.day <= 7 && (b.length <= 30 || x.month % 3 == 1) ? _mon[x.month - 1] : null)
|
||||
: b.length > 35 ? (x.day == 1 ? _mon[x.month - 1] : null) : (x.weekday == 1 || b.length <= 8 ? '${x.day} ${_mon[x.month - 1]}' : null);
|
||||
if (label != null) {
|
||||
final tp = TextPainter(text: TextSpan(text: label, style: const TextStyle(color: muted, fontSize: 10.5)),
|
||||
textDirection: TextDirection.ltr)..layout();
|
||||
tp.paint(c, Offset(i * bw + bw / 2 - tp.width / 2, h + 3));
|
||||
}
|
||||
}
|
||||
final ty = y(target);
|
||||
for (var x = 0.0; x < size.width; x += 8) {
|
||||
c.drawLine(Offset(x, ty), Offset(min(x + 4, size.width), ty), Paint()..color = accent..strokeWidth = 1.2);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _BarsPainter old) => true;
|
||||
}
|
||||
720
app/lib/health/food_model.dart
Normal file
720
app/lib/health/food_model.dart
Normal file
|
|
@ -0,0 +1,720 @@
|
|||
// The food diary — a port of the dashboard's plugins/food: db.py (what an entry is, recent foods),
|
||||
// fooddb.py (the food database: search, portions → grams → nutrients), views.py (totals, targets,
|
||||
// the ring, the bars). Keep them in step with the web pages.
|
||||
//
|
||||
// Synced rows: "food.entry" {day, time, meal, name, kcal, protein, carbs, sugar, fiber, fat, sat_fat,
|
||||
// mono_fat, poly_fat, trans_fat, sodium_mg, cholesterol_mg, potassium_mg, micros, source, src_id,
|
||||
// amount, unit, note, food_id (foods.db id), grams, my_food_id (a "food.food" id)}; "food.food" =
|
||||
// My foods + meals (per 100 g, portions JSON, recipe JSON, gone).
|
||||
// foods.db (USDA + Open Food Facts, read-only) ships with the app — the same file as on the Pi, so
|
||||
// food_id means the same food on both. "food.product" = shop products picked from the archive on the
|
||||
// sync server (every Open Food Facts product; uid "p:<food_id>", {food_id, name, brand, barcode, data
|
||||
// JSON = the product, added}) — FoodDb.food finds them too, so entries made from them work everywhere.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:sqlite3/sqlite3.dart';
|
||||
|
||||
import '../sync/store.dart';
|
||||
import 'body_model.dart' show BodyView, bmrMifflin, female, profileOf;
|
||||
import 'cycle_model.dart' show iso;
|
||||
import 'summaries.dart';
|
||||
|
||||
const mealKeys = ['breakfast', 'lunch', 'dinner', 'snack'];
|
||||
const mealLabels = {'breakfast': 'Breakfast', 'lunch': 'Lunch', 'dinner': 'Dinner', 'snack': 'Snacks', '': 'Other'};
|
||||
const kcalPerG = {'protein': 4, 'carbs': 4, 'fat': 9};
|
||||
const macros = ['protein', 'carbs', 'fat'];
|
||||
const foodCols = ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'mono_fat', 'poly_fat', 'trans_fat',
|
||||
'sodium_mg', 'cholesterol_mg', 'potassium_mg'];
|
||||
const reuseSources = {'manual', 'parsed'}; // entries worth offering again (imports are too rough)
|
||||
const generic = {'tbsp (15 ml)': 15.0, 'tsp (5 ml)': 5.0}; // spoons every food can be measured in (ml as g)
|
||||
|
||||
/// The dashboard's Settings ▸ Food, as its Health summary brings it (meta:food); its defaults until then.
|
||||
class FoodSettings {
|
||||
const FoodSettings({this.goalRate = 0, this.split = (20, 50, 30), this.kcalTarget = 0, this.fiberMin = 25,
|
||||
this.sugarMax = 50, this.sodiumMax = 2000});
|
||||
final double goalRate; // % of the weight a week (0 = keep it)
|
||||
final (int, int, int) split; // protein / carbs / fat % of the energy
|
||||
final int kcalTarget, fiberMin, sugarMax, sodiumMax;
|
||||
|
||||
static FoodSettings of(SyncStore store) {
|
||||
final m = Summaries(store).meta('food');
|
||||
if (m == null) return const FoodSettings();
|
||||
final sp = (m['split'] as List?)?.map((v) => (v as num).toInt()).toList();
|
||||
int n(String k, int d) => (m[k] as num?)?.toInt() ?? d;
|
||||
return FoodSettings(
|
||||
goalRate: (m['goal_rate'] as num?)?.toDouble() ?? 0,
|
||||
split: sp != null && sp.length == 3 ? (sp[0], sp[1], sp[2]) : (20, 50, 30),
|
||||
kcalTarget: n('kcal_target', 0), fiberMin: n('fiber_min', 25), sugarMax: n('sugar_max', 50),
|
||||
sodiumMax: n('sodium_max', 2000));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- a food (the database's or one of My foods) ---------------------------------------------
|
||||
|
||||
class Portion {
|
||||
const Portion(this.label, this.grams);
|
||||
final String label;
|
||||
final double grams;
|
||||
}
|
||||
|
||||
class Food {
|
||||
Food({required this.ref, required this.kind, required this.name, this.category = '', this.brand, this.barcode, required this.per100,
|
||||
required this.portions, this.nutriscore, this.nova, this.foodId, this.myUid, this.isMeal = false, this.source = '',
|
||||
this.labels = '', this.sugarsIn, this.dairy, this.addedSugar});
|
||||
final String ref, kind, name, category; // ref "usda:ID" / "my:UID"; kind usda / off / my
|
||||
final String source, labels; // foods.db: foundation / sr_legacy / survey / off; OFF labels ("no added sugar" …)
|
||||
final String? brand, barcode, nutriscore;
|
||||
final int? nova, foodId;
|
||||
// off.py's facts for the added-sugar estimate (sugar.dart): the sweet ingredients ("" = none; null = not known),
|
||||
// filed as dairy (1 / 0), the label's added sugars g / 100 g
|
||||
final String? sugarsIn;
|
||||
final int? dairy;
|
||||
final double? addedSugar;
|
||||
final String? myUid;
|
||||
final Map<String, double?> per100;
|
||||
final List<Portion> portions;
|
||||
final bool isMeal;
|
||||
|
||||
/// g, ml, its portions, and the generic spoons unless it has its own (food.js unitsOf).
|
||||
List<String> get units {
|
||||
final own = portions.map((p) => p.label).toList();
|
||||
final hasSpoon = own.any((l) => RegExp(r'^(tablespoon|tbsp|teaspoon|tsp)', caseSensitive: false).hasMatch(l));
|
||||
return ['g', 'ml', ...own, if (!hasSpoon) ...generic.keys];
|
||||
}
|
||||
|
||||
/// Grams of [amount] [unit] (fooddb.portion for the units the form offers), or null.
|
||||
double? grams(double amount, String unit) {
|
||||
if (unit == 'g' || unit == 'ml') return amount;
|
||||
if (generic.containsKey(unit)) return amount * generic[unit]!;
|
||||
for (final p in portions) {
|
||||
if (p.label == unit) return amount * p.grams;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The food's columns for that many grams (fooddb.nutrients).
|
||||
Map<String, double?> nutrients(double grams) =>
|
||||
{for (final c in foodCols) c: per100[c] == null ? null : (per100[c]! * grams / 100 * 100).round() / 100};
|
||||
}
|
||||
|
||||
// ---- foods.db (the database) ---------------------------------------------------------------
|
||||
|
||||
class FoodDb {
|
||||
FoodDb._(this.db);
|
||||
final Database db;
|
||||
|
||||
static FoodDb? _one;
|
||||
static SyncStore? store; // the synced data: products kept from the archive ("food.product") — set in main.dart
|
||||
|
||||
/// Copies the shipped foods.db out of the app (once per version of the file) and opens it read-only.
|
||||
static Future<FoodDb> open() async {
|
||||
if (_one != null) return _one!;
|
||||
final data = await rootBundle.load('assets/foods.db');
|
||||
final path = '${(await getApplicationSupportDirectory()).path}/foods.db';
|
||||
final f = File(path);
|
||||
if (!f.existsSync() || f.lengthSync() != data.lengthInBytes) {
|
||||
await f.writeAsBytes(data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), flush: true);
|
||||
}
|
||||
return _one = FoodDb._(sqlite3.open(path, mode: OpenMode.readOnly));
|
||||
}
|
||||
|
||||
static const _stop = {'with', 'and', 'of', 'a', 'an', 'the', 'in', 'on', 'some', 'my'};
|
||||
static const _plain = {'nfs', 'raw', 'whole', 'plain', 'regular', 'fresh', 'cooked', 'boiled'};
|
||||
static const _rank = {'foundation': 0, 'sr_legacy': 1, 'survey': 2, 'off': 3};
|
||||
|
||||
static List<String> words(String q) => RegExp(r'\w+', unicode: true)
|
||||
.allMatches(q.toLowerCase())
|
||||
.map((m) => m.group(0)!)
|
||||
.where((w) => (w.length > 1 || int.tryParse(w) != null) && !_stop.contains(w))
|
||||
.toList();
|
||||
|
||||
Food _food(Row r) {
|
||||
final off = r['source'] == 'off';
|
||||
return Food(
|
||||
ref: 'usda:${r['id']}', kind: off ? 'off' : 'usda', name: r['name'] as String, category: r['category'] as String? ?? '',
|
||||
brand: r['brand'] as String?, barcode: r.containsKey('barcode') ? r['barcode'] as String? : null,
|
||||
nutriscore: r['nutriscore'] as String?, nova: (r['nova'] as num?)?.toInt(),
|
||||
foodId: r['id'] as int, source: r['source'] as String? ?? '', labels: r['labels'] as String? ?? '',
|
||||
// a foods.db older than these columns: none of them (the old rule)
|
||||
sugarsIn: r.containsKey('sugars_in') ? r['sugars_in'] as String? : null,
|
||||
dairy: r.containsKey('dairy') ? (r['dairy'] as num?)?.toInt() : null,
|
||||
addedSugar: r.containsKey('added_sugar') ? (r['added_sugar'] as num?)?.toDouble() : null,
|
||||
per100: {for (final c in foodCols) c: (r[c] as num?)?.toDouble()},
|
||||
portions: [
|
||||
for (final p in db.select('SELECT label, grams FROM portion WHERE food_id = ? ORDER BY seq, grams', [r['id']]))
|
||||
Portion(p['label'] as String, (p['grams'] as num).toDouble())
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// A food of the database by id: foods.db's, else a product kept from the archive.
|
||||
Food? food(int id) {
|
||||
final r = db.select('SELECT * FROM food WHERE id = ?', [id]).firstOrNull;
|
||||
return r != null ? _food(r) : store == null ? null : keptProduct(store!, id);
|
||||
}
|
||||
|
||||
/// The products with that barcode (foods.db keeps it as on the pack), else kept ones.
|
||||
List<Food> byBarcode(String code) {
|
||||
final rs = db.select("SELECT * FROM food WHERE barcode = ? OR barcode = ?", [code, code.replaceFirst(RegExp(r'^0+'), '')]);
|
||||
return rs.isNotEmpty ? [for (final r in rs) _food(r)] : store == null ? [] : keptByBarcode(store!, code);
|
||||
}
|
||||
|
||||
/// fooddb.search: every word a prefix in name / brand / category; all in the name first, the name starting
|
||||
/// with the first word, plain versions (raw, NFS …), fewer words, relevance, shorter names; one per name.
|
||||
List<Food> search(String q, {int limit = 10}) {
|
||||
final ws = words(q);
|
||||
if (ws.isEmpty) return [];
|
||||
final terms = ws.map((w) => '"$w"*').join(' ');
|
||||
final rs = db.select(
|
||||
'SELECT f.*, bm25(food_fts, 10, 1) AS rank FROM food_fts JOIN food f ON f.id = food_fts.rowid '
|
||||
'WHERE food_fts MATCH ? ORDER BY rank LIMIT 200', [terms]);
|
||||
final first = ws.first;
|
||||
List<num> key(Row r) {
|
||||
final name = (r['name'] as String).toLowerCase();
|
||||
final nameWords = RegExp(r'\w+', unicode: true).allMatches(name).map((m) => m.group(0)!).toList();
|
||||
final lead = nameWords.isEmpty ? '' : nameWords.first;
|
||||
final exact = (lead == first || lead == '${first}s' || lead == '${first}es' || first == '${lead}s' || first == '${lead}es')
|
||||
? 0 : lead.startsWith(first) ? 1 : 2;
|
||||
final inName = ws.every((w) => nameWords.any((x) => x.startsWith(w))) ? 0 : 1;
|
||||
final plain = nameWords.any(_plain.contains) ? 0 : 1;
|
||||
return [inName, exact, plain, nameWords.length, ((r['rank'] as num) * 10).round() / 10, name.length,
|
||||
_rank[r['source']] ?? 3];
|
||||
}
|
||||
final sorted = rs.toList()
|
||||
..sort((a, b) {
|
||||
final ka = key(a), kb = key(b);
|
||||
for (var i = 0; i < ka.length; i++) {
|
||||
final c = ka[i].compareTo(kb[i]);
|
||||
if (c != 0) return c;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
final seen = <String>{}, out = <Food>[];
|
||||
for (final r in sorted) {
|
||||
if (seen.add((r['name'] as String).toLowerCase())) out.add(_food(r));
|
||||
if (out.length >= limit) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- My foods ------------------------------------------------------------------------------
|
||||
|
||||
Food myFood(Map<String, dynamic> r) {
|
||||
final ps = (jsonDecode((r['portions'] as String?) ?? '[]') as List).cast<Map<String, dynamic>>();
|
||||
return Food(
|
||||
ref: 'my:${r['_u']}', kind: 'my', name: r['name'] as String, category: 'My foods', myUid: r['_u'] as String,
|
||||
per100: {for (final c in foodCols) c: (r[c] as num?)?.toDouble()},
|
||||
portions: [for (final p in ps) Portion(p['label'] as String, (p['grams'] as num).toDouble())],
|
||||
isMeal: r['recipe'] != null,
|
||||
);
|
||||
}
|
||||
|
||||
/// My foods (not deleted) with every word of q in the name; exact / starting first, then the most used.
|
||||
List<Food> myFoods(SyncStore store, String q, {int limit = 8}) {
|
||||
final ws = q.toLowerCase().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
|
||||
final uses = <String, int>{};
|
||||
for (final e in store.rows('food.entry')) {
|
||||
final m = e['my_food_id'];
|
||||
if (m is String) uses[m] = (uses[m] ?? 0) + 1;
|
||||
}
|
||||
final all = [
|
||||
for (final r in store.rows('food.food'))
|
||||
if ((r['gone'] ?? 0) == 0 && ws.every((w) => (r['name'] as String).toLowerCase().contains(w))) r
|
||||
];
|
||||
final ql = q.trim().toLowerCase();
|
||||
all.sort((a, b) {
|
||||
int k(Map<String, dynamic> r) {
|
||||
final n = (r['name'] as String).toLowerCase();
|
||||
return n == ql ? 0 : n.startsWith(ql) ? 1 : 2;
|
||||
}
|
||||
final c = k(a).compareTo(k(b));
|
||||
return c != 0 ? c : (uses[b['_u']] ?? 0).compareTo(uses[a['_u']] ?? 0);
|
||||
});
|
||||
return all.take(limit).map(myFood).toList();
|
||||
}
|
||||
|
||||
Food? myFoodByUid(SyncStore store, String uid) {
|
||||
final r = store.row('food.food', uid);
|
||||
return r == null ? null : myFood(r);
|
||||
}
|
||||
|
||||
// ---- entries ------------------------------------------------------------------------------
|
||||
|
||||
class Entry {
|
||||
Entry(this.row);
|
||||
final Map<String, dynamic> row;
|
||||
String get u => row['_u'] as String;
|
||||
String get day => row['day'] as String;
|
||||
String get meal => mealKeys.contains(row['meal']) ? row['meal'] as String : '';
|
||||
String get name => (row['name'] as String?) ?? '';
|
||||
double? n(String k) => (row[k] as num?)?.toDouble();
|
||||
double get kcal => n('kcal') ?? 0;
|
||||
double? get amount => n('amount');
|
||||
String? get unit => row['unit'] as String?;
|
||||
int? get foodId => (row['food_id'] as num?)?.toInt();
|
||||
String? get myFoodId => row['my_food_id'] is String ? row['my_food_id'] as String : null;
|
||||
String get source => (row['source'] as String?) ?? '';
|
||||
String get portion => amount == null ? '' : '${_num(amount!)} ${unit ?? ''}'.trim();
|
||||
int get stamp => (row['_h'] as num?)?.toInt() ?? 0;
|
||||
}
|
||||
|
||||
String _num(double v) => v == v.roundToDouble() ? v.round().toString() : v.toStringAsFixed(v < 10 ? 2 : 1).replaceFirst(RegExp(r'0+$'), '');
|
||||
|
||||
List<Entry> entriesOn(SyncStore store, String day) {
|
||||
final es = [for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') = ?", args: [day])) Entry(r)];
|
||||
es.sort((a, b) {
|
||||
final c = a.stamp.compareTo(b.stamp);
|
||||
if (c != 0) return c;
|
||||
return ((a.row['time'] as String?) ?? '').compareTo((b.row['time'] as String?) ?? '');
|
||||
});
|
||||
return es;
|
||||
}
|
||||
|
||||
/// {day: kcal} for the days in [a, z] (the week strip).
|
||||
Map<String, double> kcalByDay(SyncStore store, String a, String z) {
|
||||
final out = <String, double>{};
|
||||
for (final r in store.db.select(
|
||||
"SELECT json_extract(data, '\$.day') AS dday, sum(json_extract(data, '\$.kcal')) AS k FROM rec "
|
||||
"WHERE t = 'food.entry' AND json_extract(data, '\$.day') BETWEEN ? AND ? GROUP BY dday", [a, z])) { // not 'd': rec.d is the device
|
||||
out[r['dday'] as String] = (r['k'] as num?)?.toDouble() ?? 0;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Foods eaten before (db.foods): one per name — its latest entry — most eaten first; q anywhere in the name.
|
||||
List<(Entry, int)> recentFoods(SyncStore store, String q, {int limit = 8}) {
|
||||
final groups = <String, (Entry, int)>{};
|
||||
for (final r in store.rows('food.entry')) {
|
||||
final e = Entry(r);
|
||||
if (!reuseSources.contains(e.source) || e.name.trim().isEmpty) continue;
|
||||
final k = e.name.trim().toLowerCase();
|
||||
final g = groups[k];
|
||||
final newer = g == null || e.day.compareTo(g.$1.day) > 0 || (e.day == g.$1.day && e.stamp > g.$1.stamp);
|
||||
groups[k] = (newer ? e : g.$1, (g?.$2 ?? 0) + 1);
|
||||
}
|
||||
final ql = q.trim().toLowerCase();
|
||||
final hits = groups.entries.where((e) => e.key.contains(ql)).map((e) => e.value).toList()
|
||||
..sort((a, b) {
|
||||
final sa = a.$1.name.toLowerCase().startsWith(ql) ? 0 : 1, sb = b.$1.name.toLowerCase().startsWith(ql) ? 0 : 1;
|
||||
if (sa != sb) return sa.compareTo(sb);
|
||||
if (a.$2 != b.$2) return b.$2.compareTo(a.$2);
|
||||
return b.$1.day.compareTo(a.$1.day);
|
||||
});
|
||||
return hits.take(limit).toList();
|
||||
}
|
||||
|
||||
// ---- products kept from the archive ("food.product", the dashboard's db.product) ---------------
|
||||
|
||||
const tProduct = 'food.product';
|
||||
const offId = 20000000000000; // off.OFF_ID: + the barcode
|
||||
|
||||
/// A product from the archive (or as kept: the same keys) → a Food (kind "off").
|
||||
Food productFood(Map<String, dynamic> d) {
|
||||
final per = (d['per100'] as Map?)?.cast<String, dynamic>() ?? {};
|
||||
return Food(
|
||||
ref: 'usda:${d['id']}', kind: 'off', name: d['name'] as String? ?? '?', category: d['category'] as String? ?? '',
|
||||
brand: d['brand'] as String?, barcode: d['barcode'] as String?, nutriscore: d['nutriscore'] as String?,
|
||||
nova: (d['nova'] as num?)?.toInt(), foodId: (d['id'] as num).toInt(), source: 'off', labels: d['labels'] as String? ?? '',
|
||||
sugarsIn: d['sugars_in'] as String?, dairy: (d['dairy'] as num?)?.toInt(), addedSugar: (d['added_sugar'] as num?)?.toDouble(),
|
||||
per100: {for (final c in foodCols) c: (per[c] as num?)?.toDouble()},
|
||||
portions: [
|
||||
for (final p in ((d['portions'] as List?) ?? []).cast<Map>())
|
||||
if ((p['grams'] as num?) != null) Portion('${p['label']}', (p['grams'] as num).toDouble())
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Food? _kept(Map<String, dynamic>? row) {
|
||||
try {
|
||||
return row == null ? null : productFood(jsonDecode(row['data'] as String) as Map<String, dynamic>);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Food? keptProduct(SyncStore store, int id) => _kept(store.row(tProduct, 'p:$id'));
|
||||
|
||||
List<Food> keptByBarcode(SyncStore store, String code) =>
|
||||
[for (final r in store.rows(tProduct, where: "json_extract(data, '\$.barcode') = ?", args: [code])) ?_kept(r)];
|
||||
|
||||
/// Kept products whose name / brand has every word of [q] (folded: no diacritics).
|
||||
List<Food> keptProducts(SyncStore store, String q, {required String Function(String) fold, int limit = 4}) {
|
||||
final ws = fold(q).split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
|
||||
if (ws.isEmpty) return [];
|
||||
return [
|
||||
for (final r in store.rows(tProduct))
|
||||
if (ws.every(fold('${r['name']} ${r['brand'] ?? ''}').contains)) ?_kept(r),
|
||||
].take(limit).toList();
|
||||
}
|
||||
|
||||
/// Keep a product picked from the archive (the dashboard's db.save_product: checked, then stored and synced).
|
||||
Food? keepProduct(SyncStore store, Map<String, dynamic> d) {
|
||||
final id = (d['id'] as num?)?.toInt();
|
||||
final per = d['per100'];
|
||||
if (id == null || id < offId || id >= offId * 1.5 || per is! Map || '${d['name'] ?? ''}'.trim().isEmpty) return null;
|
||||
String? t(String k, int n) => d[k] == null ? null : '${d[k]}'.substring(0, min(n, '${d[k]}'.length));
|
||||
final v = <String, dynamic>{
|
||||
for (final (k, n) in [('name', 120), ('category', 120), ('brand', 60), ('barcode', 14), ('countries', 200), ('nutriscore', 1),
|
||||
('allergens', 400), ('labels', 400), ('ingredients', 1600), ('sugars_in', 200)]) k: t(k, n),
|
||||
'id': id,
|
||||
'per100': {for (final c in foodCols) c: (per[c] as num?)?.toDouble()},
|
||||
'portions': [
|
||||
for (final p in ((d['portions'] as List?) ?? []).cast<Map>().take(6))
|
||||
if ((p['grams'] as num? ?? 0) > 0 && (p['grams'] as num) <= 10000) {'label': '${p['label']}', 'grams': (p['grams'] as num).toDouble()}
|
||||
],
|
||||
'nova': [1, 2, 3, 4].contains(d['nova']) ? d['nova'] : null,
|
||||
'dairy': [0, 1].contains(d['dairy']) ? d['dairy'] : null,
|
||||
'added_sugar': (d['added_sugar'] as num?)?.toDouble(),
|
||||
};
|
||||
final old = store.row(tProduct, 'p:$id');
|
||||
final data = jsonEncode(v);
|
||||
if (old?['data'] != data) {
|
||||
store.put(tProduct, 'p:$id', {'food_id': id, 'name': v['name'], 'brand': v['brand'] ?? '', 'barcode': v['barcode'], 'data': data,
|
||||
'added': old?['added'] ?? DateTime.now().toUtc().toIso8601String().substring(0, 19).replaceFirst('T', ' ')});
|
||||
}
|
||||
return productFood(v);
|
||||
}
|
||||
|
||||
/// The food an entry was made from, if it still exists (database or My foods).
|
||||
Food? foodOf(SyncStore store, FoodDb? fdb, Entry e) {
|
||||
if (e.myFoodId != null) return myFoodByUid(store, e.myFoodId!);
|
||||
if (e.foodId != null) return fdb?.food(e.foodId!);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Save an entry made from [food] (amount × unit → grams → its nutrients) — new (u null) or changed.
|
||||
/// The numbers are the entry's own, worked out now (later changes to the food don't touch it).
|
||||
String? saveFromFood(SyncStore store, {String? u, required String day, required String meal, required Food food,
|
||||
required double amount, required String unit, String note = ''}) {
|
||||
final g = food.grams(amount, unit);
|
||||
if (g == null) return "Can't tell the grams of that portion.";
|
||||
final old = u == null ? null : store.row('food.entry', u);
|
||||
store.put('food.entry', u ?? SyncStore.randomId(), {
|
||||
'micros': '{}', 'src_id': null, 'time': null,
|
||||
...?old,
|
||||
'day': day, 'meal': meal, 'name': food.name, ...food.nutrients(g),
|
||||
'amount': amount, 'unit': unit, 'grams': g, 'note': note,
|
||||
'food_id': food.foodId, 'my_food_id': food.myUid, 'source': old?['source'] ?? 'manual',
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Save an entry without a food (its numbers typed, or copied from an older one and scaled by amount).
|
||||
String? saveTotals(SyncStore store, {String? u, required String day, required String meal, required String name,
|
||||
required Map<String, double?> values, double? amount, String? unit, Map<String, dynamic>? copyFrom, String note = ''}) {
|
||||
if (name.trim().isEmpty) return 'What was it?';
|
||||
if (values['kcal'] == null) return 'How much energy? A guess is fine.';
|
||||
final old = u == null ? null : store.row('food.entry', u);
|
||||
final extra = <String, dynamic>{};
|
||||
if (old == null && copyFrom != null && (copyFrom['kcal'] as num?) != null && (copyFrom['kcal'] as num) > 0) {
|
||||
final f = values['kcal']! / (copyFrom['kcal'] as num); // db.save `from`: the other nutrients, scaled
|
||||
for (final k in foodCols) {
|
||||
if (!values.containsKey(k) && copyFrom[k] != null) extra[k] = ((copyFrom[k] as num) * f * 1000).round() / 1000;
|
||||
}
|
||||
}
|
||||
store.put('food.entry', u ?? SyncStore.randomId(), {
|
||||
'micros': '{}', 'src_id': null, 'time': null, 'food_id': null, 'grams': null, 'my_food_id': null,
|
||||
...?old, ...extra,
|
||||
'day': day, 'meal': meal, 'name': name.trim(), ...values, 'amount': amount, 'unit': unit, 'note': note,
|
||||
'source': old?['source'] ?? 'manual',
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Add an older entry again as it was (yesterday's +): a food entry is worked out again, else copied.
|
||||
void addAgain(SyncStore store, FoodDb? fdb, Entry e, String day, String meal) {
|
||||
final f = foodOf(store, fdb, e);
|
||||
if (f != null && e.amount != null && e.unit != null && f.grams(e.amount!, e.unit!) != null) {
|
||||
saveFromFood(store, day: day, meal: meal, food: f, amount: e.amount!, unit: e.unit!);
|
||||
return;
|
||||
}
|
||||
saveTotals(store, day: day, meal: meal, name: e.name, amount: e.amount, unit: e.unit,
|
||||
values: {for (final k in ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'sodium_mg']) k: e.n(k)},
|
||||
copyFrom: e.row);
|
||||
}
|
||||
|
||||
// ---- totals, targets, ring (views.py) ----------------------------------------------------------
|
||||
|
||||
Map<String, double?> totals(Iterable<Entry> es) {
|
||||
final out = <String, double?>{};
|
||||
for (final k in ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'sodium_mg']) {
|
||||
final vs = es.map((e) => e.n(k)).whereType<double>().toList();
|
||||
out[k] = vs.isEmpty ? null : vs.reduce((a, b) => a + b);
|
||||
}
|
||||
out['kcal'] ??= 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
class Plan {
|
||||
Plan(this.kcal, this.maint, this.basis, this.deficit, this.capped);
|
||||
final int kcal;
|
||||
final int? maint;
|
||||
final String basis;
|
||||
final int deficit;
|
||||
final bool capped;
|
||||
}
|
||||
|
||||
/// views.plan: your usual day from Health (the Pi's energy summary: resting + walking + workouts,
|
||||
/// averaged over 28 days with step data — at least 7) minus the weight goal; resting × 1.4 until then.
|
||||
Plan plan(SyncStore store, FoodSettings s) {
|
||||
final e = Summaries(store).meta('energy') ?? {};
|
||||
final b = BodyView(store, profileOf(store));
|
||||
final w = (e['weight'] as num?)?.toDouble() ?? b.weight;
|
||||
final bmr = (e['bmr'] as num?)?.toDouble() ?? bmrMifflin(w, b.p.height, b.p.sex, b.age);
|
||||
if (s.kcalTarget > 0) return Plan(s.kcalTarget, null, 'set by hand', 0, false);
|
||||
final tdee = (e['tdee'] as num?)?.toInt(), days = (e['days'] as num?)?.toInt() ?? 0;
|
||||
final int? maint;
|
||||
final String basis;
|
||||
if (tdee != null && days >= 7) {
|
||||
maint = tdee;
|
||||
basis = 'your average day in Health (resting + walking + workouts, $days days)';
|
||||
} else if (bmr != null) {
|
||||
maint = (bmr * 1.4).round();
|
||||
basis = 'resting energy × 1.4 (not enough step data in Health yet)';
|
||||
} else {
|
||||
return Plan(2000, null, 'no weight yet — 2000 kcal', 0, false);
|
||||
}
|
||||
if (w == null) return Plan(2000, maint, basis, 0, false);
|
||||
var deficit = w * s.goalRate / 100 * 7700 / 7;
|
||||
var capped = deficit > 1000;
|
||||
deficit = min(deficit, 1000);
|
||||
var kcal = maint - deficit;
|
||||
final floor = b.p.sex == female ? 1200 : 1500;
|
||||
if (kcal < floor) {
|
||||
kcal = floor.toDouble();
|
||||
capped = true;
|
||||
}
|
||||
return Plan((kcal / 10).round() * 10, maint, basis, deficit.round(), capped);
|
||||
}
|
||||
|
||||
/// {key: (target, kind)} — kind goal / min / max (views.targets).
|
||||
Map<String, (double, String)> targets(SyncStore store, FoodSettings s) {
|
||||
final kcal = plan(store, s).kcal.toDouble();
|
||||
final pct = [s.split.$1, s.split.$2, s.split.$3];
|
||||
return {
|
||||
'kcal': (kcal, 'goal'),
|
||||
for (var i = 0; i < 3; i++) macros[i]: ((kcal * pct[i] / 100 / kcalPerG[macros[i]]!).roundToDouble(), 'goal'),
|
||||
'fiber': (s.fiberMin.toDouble(), 'min'),
|
||||
'sugar': (0, 'info'), // total sugar: shown, no limit (natural sugar counts too)
|
||||
'added_sugar': ((kcal * 0.10 / 4).roundToDouble(), 'max'), // WHO: added ("free") sugars under 10 % of the energy (sugar.dart)
|
||||
'sat_fat': ((kcal * 0.10 / 9).roundToDouble(), 'max'),
|
||||
'sodium_mg': (s.sodiumMax.toDouble(), 'max'),
|
||||
};
|
||||
}
|
||||
|
||||
String dayIso(DateTime d) => iso(d);
|
||||
String num1(double v) => _num(v);
|
||||
|
||||
// ---- My foods: save / delete (db.clean_food, save_food, delete_food) ---------------------------
|
||||
|
||||
/// What the food editor edits per 100 g (db.FIELDS): key → (label, unit, max).
|
||||
const foodFields = {
|
||||
'kcal': ('Energy', 'kcal', 10000.0), 'protein': ('Protein', 'g', 1000.0), 'carbs': ('Carbs', 'g', 1000.0),
|
||||
'sugar': ('of which sugar', 'g', 1000.0), 'fat': ('Fat', 'g', 1000.0), 'sat_fat': ('of which saturated', 'g', 1000.0),
|
||||
'fiber': ('Fibre', 'g', 500.0), 'sodium_mg': ('Sodium', 'mg', 50000.0),
|
||||
};
|
||||
|
||||
/// New (uid null) or changed food: name unique among the live ones, energy required, portions need a
|
||||
/// name + grams. The nutrients the editor doesn't show stay as they were. → (uid, error).
|
||||
/// [sugarKind]: "Sugar counts as" (added / dairy / natural; '' = estimated; null = left as it is).
|
||||
(String?, String?) saveMyFood(SyncStore store, {String? uid, required String name, required Map<String, double?> per100,
|
||||
required List<Portion> portions, String note = '', String? sugarKind}) {
|
||||
final n = name.trim().split(RegExp(r'\s+')).join(' ');
|
||||
if (n.isEmpty) return (null, 'Name the food.');
|
||||
if (per100['kcal'] == null) return (null, 'Energy per 100 g — from the label.');
|
||||
for (final e in per100.entries) {
|
||||
final max = foodFields[e.key]?.$3;
|
||||
if (e.value != null && max != null && (e.value! < 0 || e.value! > max)) return (null, '${foodFields[e.key]!.$1}: 0–${max.round()}.');
|
||||
}
|
||||
for (final p in portions) {
|
||||
if (p.label.trim().isEmpty || p.grams <= 0) return (null, 'A portion needs a name and its grams.');
|
||||
if (['g', 'ml'].contains(p.label.trim().toLowerCase())) return (null, 'g and ml are there already.');
|
||||
}
|
||||
final clash = store.rows('food.food').any((r) =>
|
||||
(r['gone'] ?? 0) == 0 && r['_u'] != uid && (r['name'] as String).toLowerCase() == n.toLowerCase());
|
||||
if (clash) return (null, 'You already have a food with that name in My foods — pick it, or name this one differently.');
|
||||
final now = DateTime.now().toIso8601String().substring(0, 19);
|
||||
final old = uid == null ? null : store.row('food.food', uid);
|
||||
final u = uid ?? SyncStore.randomId();
|
||||
store.put('food.food', u, {
|
||||
'based_on': null, 'based_on_name': null, 'recipe': null, 'gone': 0, 'created': now,
|
||||
for (final c in foodCols) c: null,
|
||||
...?old,
|
||||
'name': n, ...per100, 'note': note.trim(), 'updated': now,
|
||||
if (sugarKind != null) 'sugar_kind': const ['added', 'dairy', 'natural'].contains(sugarKind) ? sugarKind : null,
|
||||
'portions': jsonEncode([for (final p in portions) {'label': p.label.trim().split(RegExp(r'\s+')).join(' '), 'grams': p.grams}]),
|
||||
});
|
||||
return (u, null);
|
||||
}
|
||||
|
||||
/// Deleted foods are only hidden (gone): entries made from them keep pointing at them.
|
||||
void deleteMyFood(SyncStore store, String uid) {
|
||||
final r = store.row('food.food', uid);
|
||||
if (r == null) return;
|
||||
store.put('food.food', uid, {...r, 'gone': 1, 'updated': DateTime.now().toIso8601String().substring(0, 19)});
|
||||
}
|
||||
|
||||
/// All My foods (not deleted), by name, with how often each was used.
|
||||
List<(Map<String, dynamic>, int)> allMyFoods(SyncStore store) {
|
||||
final uses = <String, int>{};
|
||||
for (final e in store.rows('food.entry')) {
|
||||
if (e['my_food_id'] is String) uses[e['my_food_id'] as String] = (uses[e['my_food_id'] as String] ?? 0) + 1;
|
||||
}
|
||||
final rs = store.rows('food.food').where((r) => (r['gone'] ?? 0) == 0).toList()
|
||||
..sort((a, b) => (a['name'] as String).toLowerCase().compareTo((b['name'] as String).toLowerCase()));
|
||||
return [for (final r in rs) (r, uses[r['_u']] ?? 0)];
|
||||
}
|
||||
|
||||
// ---- history (views.history) -------------------------------------------------------------------
|
||||
|
||||
/// {day: totals} for [a, z] (ISO days) — one pass over the entries.
|
||||
Map<String, Map<String, double>> dayTotals(SyncStore store, String a, String z) {
|
||||
final out = <String, Map<String, double>>{};
|
||||
for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [a, z])) {
|
||||
final t = out.putIfAbsent(r['day'] as String, () => {});
|
||||
for (final k in ['kcal', 'protein', 'carbs', 'fat', 'fiber', 'sugar', 'sodium_mg', 'sat_fat']) {
|
||||
t[k] = (t[k] ?? 0) + ((r[k] as num?)?.toDouble() ?? 0);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// The foods eaten most in [a, z]: (name, times, average kcal).
|
||||
List<(String, int, double)> topFoods(SyncStore store, String a, String z, {int limit = 12}) {
|
||||
final g = <String, (String, int, double)>{};
|
||||
for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [a, z])) {
|
||||
final name = (r['name'] as String?)?.trim() ?? '';
|
||||
if (name.isEmpty) continue;
|
||||
final k = name.toLowerCase(), cur = g[k];
|
||||
final kcal = (r['kcal'] as num?)?.toDouble() ?? 0;
|
||||
g[k] = cur == null ? (name, 1, kcal) : (cur.$1, cur.$2 + 1, cur.$3 + kcal);
|
||||
}
|
||||
final out = [for (final v in g.values) (v.$1, v.$2, v.$3 / v.$2)]
|
||||
..sort((x, y) => x.$2 != y.$2 ? y.$2.compareTo(x.$2) : (y.$3 * y.$2).compareTo(x.$3 * x.$2));
|
||||
return out.take(limit).toList();
|
||||
}
|
||||
|
||||
// ---- meals (db.save_meal) ------------------------------------------------------------------------
|
||||
|
||||
const mealMax = 40; // ingredients
|
||||
|
||||
/// One ingredient of a meal: a food + amount + unit, or (an entry logged without a food) its own numbers.
|
||||
class Ingredient {
|
||||
Ingredient.food(Food this.food, this.amount, this.unit) : fixed = null, name = food.name, grams = null;
|
||||
Ingredient.fixed(Map<String, double?> this.fixed, this.name, this.amount, this.unit, this.grams) : food = null;
|
||||
final Food? food;
|
||||
final Map<String, double?>? fixed;
|
||||
final String name;
|
||||
double? amount, grams;
|
||||
String? unit;
|
||||
|
||||
double? get g => food != null ? (amount == null ? null : food!.grams(amount!, unit ?? 'g')) : grams;
|
||||
Map<String, double?> get values => food != null ? (g == null ? {} : food!.nutrients(g!)) : fixed!;
|
||||
}
|
||||
|
||||
/// The meal's ingredients from its synced recipe (refs "usda:ID" / "my:~ID").
|
||||
List<Ingredient> recipeOf(SyncStore store, FoodDb? fdb, Map<String, dynamic> row) {
|
||||
final r = row['recipe'] is String ? jsonDecode(row['recipe'] as String) as Map<String, dynamic> : null;
|
||||
final out = <Ingredient>[];
|
||||
for (final i in ((r?['ingredients'] as List?) ?? []).cast<Map<String, dynamic>>()) {
|
||||
final amount = (i['amount'] as num?)?.toDouble(), unit = i['unit'] as String?;
|
||||
if (i['fixed'] is Map) {
|
||||
out.add(Ingredient.fixed({for (final e in (i['fixed'] as Map).entries) e.key as String: (e.value as num?)?.toDouble()},
|
||||
(i['name'] as String?) ?? '', amount, unit, (i['grams'] as num?)?.toDouble()));
|
||||
continue;
|
||||
}
|
||||
final ref = (i['food'] as String?) ?? '';
|
||||
final f = ref.startsWith('usda:') ? fdb?.food(int.parse(ref.substring(5)))
|
||||
: ref.startsWith('my:') ? myFoodByUid(store, ref.substring(3).replaceFirst('~', '')) : null;
|
||||
if (f != null) {
|
||||
out.add(Ingredient.food(f, amount, unit));
|
||||
} else {
|
||||
// gone: keep it as its own numbers so the meal still adds up (the web says "remove it and pick it again")
|
||||
out.add(Ingredient.fixed({}, '${(i['name'] as String?) ?? '?'} (gone)', amount, unit, (i['grams'] as num?)?.toDouble()));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
double? doneGramsOf(Map<String, dynamic> row) {
|
||||
final r = row['recipe'] is String ? jsonDecode(row['recipe'] as String) as Map<String, dynamic> : null;
|
||||
return (r?['done_grams'] as num?)?.toDouble();
|
||||
}
|
||||
|
||||
/// The meals inside a meal (by id) — a meal may hold another meal, not itself.
|
||||
Set<String> mealIds(SyncStore store, String uid, [int depth = 0]) {
|
||||
final row = store.row('food.food', uid);
|
||||
final r = row?['recipe'] is String ? jsonDecode(row!['recipe'] as String) as Map<String, dynamic> : null;
|
||||
final out = <String>{};
|
||||
for (final i in ((r?['ingredients'] as List?) ?? []).cast<Map<String, dynamic>>()) {
|
||||
final ref = (i['food'] as String?) ?? '';
|
||||
if (ref.startsWith('my:')) {
|
||||
final id = ref.substring(3).replaceFirst('~', '');
|
||||
out.add(id);
|
||||
if (depth < 4) out.addAll(mealIds(store, id, depth + 1));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Save a meal (new: uid null): its values per 100 g worked out from the ingredients as they are now;
|
||||
/// portions get "whole meal" (its whole weight). → (uid, error).
|
||||
(String?, String?) saveMeal(SyncStore store, {String? uid, required String name, required List<Ingredient> ings,
|
||||
double? doneGrams, required List<Portion> portions, String note = ''}) {
|
||||
if (name.trim().isEmpty) return (null, 'Name the meal.');
|
||||
if (ings.isEmpty) return (null, 'Add what goes into it.');
|
||||
if (ings.length > mealMax) return (null, 'At most $mealMax ingredients.');
|
||||
final tot = <String, double?>{for (final c in foodCols) c: null};
|
||||
var grams = 0.0;
|
||||
final unweighed = <String>[], recipe = <Map<String, dynamic>>[];
|
||||
for (final i in ings) {
|
||||
if (i.food != null) {
|
||||
if (uid != null && i.food!.myUid != null && (i.food!.myUid == uid || mealIds(store, i.food!.myUid!).contains(uid))) {
|
||||
return (null, '${i.name}: a meal can’t contain itself.');
|
||||
}
|
||||
final g = i.g;
|
||||
if (g == null || g <= 0) return (null, '${i.name}: how much of it — amount and unit?');
|
||||
i.food!.nutrients(g).forEach((c, v) {
|
||||
if (v != null) tot[c] = (tot[c] ?? 0) + v;
|
||||
});
|
||||
grams += g;
|
||||
recipe.add({'food': i.food!.myUid != null ? 'my:~${i.food!.myUid}' : 'usda:${i.food!.foodId}', 'name': i.food!.name,
|
||||
'amount': i.amount, 'unit': i.unit ?? 'g', 'grams': (g * 100).round() / 100});
|
||||
} else {
|
||||
if (i.fixed!['kcal'] == null) return (null, '${i.name}: no energy on that one.');
|
||||
i.fixed!.forEach((c, v) {
|
||||
if (v != null && tot.containsKey(c)) tot[c] = (tot[c] ?? 0) + v;
|
||||
});
|
||||
if (i.grams != null && i.grams! > 0) {
|
||||
grams += i.grams!;
|
||||
} else {
|
||||
unweighed.add(i.name);
|
||||
}
|
||||
recipe.add({'fixed': i.fixed, 'name': i.name, 'amount': i.amount, 'unit': i.unit, 'grams': i.grams});
|
||||
}
|
||||
}
|
||||
final weight = doneGrams ?? grams;
|
||||
if (unweighed.isNotEmpty && doneGrams == null) {
|
||||
return (null, 'No weight for ${unweighed.take(3).join(', ')}${unweighed.length > 3 ? ' …' : ''} — weigh the meal (or guess) and enter it as the weight when done.');
|
||||
}
|
||||
if (weight <= 0) return (null, 'How much does it weigh?');
|
||||
final per100 = {for (final e in tot.entries) e.key: e.value == null ? null : (e.value! * 100 / weight * 1000).round() / 1000};
|
||||
final (u, err) = saveMyFood(store, uid: uid, name: name, per100: per100,
|
||||
portions: [...portions.where((p) => p.label.trim().toLowerCase() != 'whole meal'), Portion('whole meal', (weight * 10).round() / 10)],
|
||||
note: note);
|
||||
if (err != null) return (null, err);
|
||||
final row = store.row('food.food', u!)!;
|
||||
store.put('food.food', u, {...row, 'recipe': jsonEncode({'ingredients': recipe, 'done_grams': doneGrams})});
|
||||
return (u, null);
|
||||
}
|
||||
|
||||
/// An entry dragged into another meal (db.move: only the meal changes).
|
||||
void moveEntry(SyncStore store, String u, String meal) {
|
||||
final r = store.row('food.entry', u);
|
||||
if (r != null && r['meal'] != meal) store.put('food.entry', u, {...r, 'meal': meal});
|
||||
}
|
||||
397
app/lib/health/food_page.dart
Normal file
397
app/lib/health/food_page.dart
Normal file
|
|
@ -0,0 +1,397 @@
|
|||
// 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<String, double?> 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<FoodPage> createState() => _FoodPageState();
|
||||
}
|
||||
|
||||
class _FoodPageState extends State<FoodPage> {
|
||||
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<void> _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<void> _makeMeal(List<Entry> es) async {
|
||||
final picked = es.isEmpty ? <Entry>[] : 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)'),
|
||||
),
|
||||
];
|
||||
return 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(onPressed: () => setState(() => d = plus(d, -1)), 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(
|
||||
onPressed: daysBetween(today(), d) < ahead ? () => setState(() => d = plus(d, 1)) : 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)));
|
||||
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,
|
||||
decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(3)),
|
||||
child: FractionallySizedBox(heightFactor: h / 1.15,
|
||||
child: Container(decoration: BoxDecoration(color: over ? bad : good, borderRadius: BorderRadius.circular(3)))),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(kc == null ? '' : '${kc.round()}', style: const TextStyle(fontSize: 10.5, color: muted)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}(),
|
||||
]);
|
||||
}
|
||||
|
||||
Widget _meal(String m, List<Entry> 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<Entry>(
|
||||
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<Entry>(
|
||||
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<double>(0, (a, e) => a + fs.entry(e));
|
||||
}
|
||||
return _ringCard(t, targets(store, s), plan(store, s), es.isNotEmpty);
|
||||
}
|
||||
|
||||
Widget _ringCard(Map<String, double?> t, Map<String, (double, String)> 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<Widget> _burned(double kcal, bool any) {
|
||||
if (day.isAfter(today())) return [];
|
||||
final e = (Summaries(sync.store).day(dayIso(day))?['energy'] as Map?)?.cast<String, dynamic>();
|
||||
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<String, double?> 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;
|
||||
}
|
||||
|
||||
420
app/lib/health/food_sheet.dart
Normal file
420
app/lib/health/food_sheet.dart
Normal file
|
|
@ -0,0 +1,420 @@
|
|||
// Adding / editing a food entry (the web page's inline editor as a bottom sheet, lifted by the
|
||||
// keyboard). Modes:
|
||||
// search — the box: empty = yesterday's foods (this meal first; + adds one as it was, a tap picks
|
||||
// it to change the portion); typed = My foods · Eaten before · Food database · Products
|
||||
// (+ ones kept from the archive); a barcode (typed or scanned — the camera button) = that
|
||||
// product; "Search all products…" = the archive on the sync server (food_archive.dart)
|
||||
// food — the picked food: amount + unit (g, ml, its portions, tbsp / tsp), the numbers live, meal
|
||||
// totals — an entry without a food (Lifesum imports, estimates): name, kcal / P / C / F
|
||||
// Editing an entry opens it in food or totals mode; Delete = tap twice.
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'cycle_model.dart' show parseDay, plus;
|
||||
import 'food_archive.dart';
|
||||
import 'food_model.dart';
|
||||
import 'food_page.dart' show macroDots;
|
||||
import 'my_foods.dart';
|
||||
import 'sugar.dart' show fold;
|
||||
|
||||
class FoodSheet extends StatefulWidget {
|
||||
const FoodSheet({super.key, required this.sync, required this.fdb, required this.day, required this.meal, this.entry});
|
||||
final SyncService sync;
|
||||
final FoodDb? fdb;
|
||||
final String day, meal;
|
||||
final Entry? entry;
|
||||
@override
|
||||
State<FoodSheet> createState() => _FoodSheetState();
|
||||
}
|
||||
|
||||
class _FoodSheetState extends State<FoodSheet> {
|
||||
late String meal = widget.meal.isEmpty ? 'snack' : widget.meal;
|
||||
String mode = 'search';
|
||||
final q = TextEditingController();
|
||||
Food? food;
|
||||
final amount = TextEditingController(), name = TextEditingController(), unitCtl = TextEditingController();
|
||||
String unit = 'g';
|
||||
final totalsCtl = {for (final k in ['kcal', 'protein', 'carbs', 'fat']) k: TextEditingController()};
|
||||
Map<String, dynamic>? copyFrom; // totals mode from an older entry: its other nutrients come along, scaled
|
||||
String? error;
|
||||
bool armed = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final e = widget.entry;
|
||||
if (e != null) {
|
||||
final f = foodOf(widget.sync.store, widget.fdb, e);
|
||||
if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) {
|
||||
_pick(f, e.amount!, e.unit!);
|
||||
} else {
|
||||
_totals(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _pick(Food f, [double? a, String? u]) => setState(() {
|
||||
food = f;
|
||||
mode = 'food';
|
||||
unit = u ?? (f.portions.isNotEmpty ? f.portions.first.label : 'g');
|
||||
amount.text = num1(a ?? (unit == 'g' ? 100 : 1));
|
||||
error = null;
|
||||
});
|
||||
|
||||
void _totals(Entry e, {bool copy = false}) => setState(() {
|
||||
mode = 'totals';
|
||||
name.text = e.name;
|
||||
amount.text = e.amount == null ? '' : num1(e.amount!);
|
||||
unit = e.unit ?? '';
|
||||
unitCtl.text = unit;
|
||||
for (final k in totalsCtl.keys) {
|
||||
totalsCtl[k]!.text = e.n(k) == null ? '' : num1(e.n(k)!);
|
||||
}
|
||||
copyFrom = copy ? e.row : null;
|
||||
error = null;
|
||||
});
|
||||
|
||||
void _done() {
|
||||
widget.sync.changed();
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
void _save() {
|
||||
final store = widget.sync.store;
|
||||
final u = widget.entry?.u;
|
||||
String? err;
|
||||
if (mode == 'food') {
|
||||
final a = double.tryParse(amount.text.trim().replaceAll(',', '.'));
|
||||
if (a == null || a <= 0) return setState(() => error = 'How much?');
|
||||
err = saveFromFood(store, u: u, day: widget.entry?.day ?? widget.day, meal: meal, food: food!, amount: a, unit: unit,
|
||||
note: (widget.entry?.row['note'] as String?) ?? '');
|
||||
} else {
|
||||
double? v(String k) => double.tryParse(totalsCtl[k]!.text.trim().replaceAll(',', '.'));
|
||||
err = saveTotals(store, u: u, day: widget.entry?.day ?? widget.day, meal: meal, name: name.text,
|
||||
values: {for (final k in totalsCtl.keys) k: v(k)},
|
||||
amount: double.tryParse(amount.text.trim().replaceAll(',', '.')), unit: unit.isEmpty ? null : unit,
|
||||
copyFrom: copyFrom, note: (widget.entry?.row['note'] as String?) ?? '');
|
||||
}
|
||||
if (err != null) return setState(() => error = err);
|
||||
_done();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final h = MediaQuery.of(context).size.height;
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: h * 0.8),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
Expanded(child: Text(widget.entry == null ? 'Add to ${mealLabels[meal]!.toLowerCase()}' : 'Edit',
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent))),
|
||||
DropdownButton<String>(
|
||||
value: meal,
|
||||
underline: const SizedBox(),
|
||||
dropdownColor: card2,
|
||||
items: [for (final m in mealKeys) DropdownMenuItem(value: m, child: Text(mealLabels[m]!))],
|
||||
onChanged: (m) => setState(() => meal = m!),
|
||||
),
|
||||
]),
|
||||
if (mode == 'search') Flexible(child: _search()) else if (mode == 'food') _foodForm() else _totalsForm(),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- search
|
||||
Widget _search() {
|
||||
final store = widget.sync.store;
|
||||
final text = q.text.trim();
|
||||
final sections = <(String, List<Widget>)>[];
|
||||
if (text.isEmpty) {
|
||||
final yday = parseDay(widget.day);
|
||||
final ys = entriesOn(store, dayIso(plus(yday, -1))).where((e) => e.meal.isNotEmpty).toList();
|
||||
final here = entriesOn(store, widget.day);
|
||||
bool already(Entry y) => here.any((e) => e.meal == meal && e.name == y.name && e.amount == y.amount && e.unit == y.unit);
|
||||
final mine = ys.where((e) => e.meal == meal).toList(), rest = ys.where((e) => e.meal != meal).toList();
|
||||
if (mine.isNotEmpty) sections.add(('Yesterday · ${mealLabels[meal]!.toLowerCase()}', [for (final e in mine) _yday(e, already(e))]));
|
||||
if (rest.isNotEmpty) sections.add(('Yesterday · other meals', [for (final e in rest) _yday(e, already(e))]));
|
||||
final recent = recentFoods(store, '', limit: 8);
|
||||
if (recent.isNotEmpty) sections.add(('Eaten often', [for (final (e, n) in recent) _recent(e, n)]));
|
||||
} else if (RegExp(r'^\d{8,14}$').hasMatch(text)) { // a barcode: that product, here or kept
|
||||
final found = widget.fdb?.byBarcode(text) ?? keptByBarcode(store, text);
|
||||
sections.add(('Barcode $text', [
|
||||
for (final f in found) _foodTile(f),
|
||||
if (found.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
|
||||
child: Text('Not in the food database here — look it up in all products:', style: TextStyle(color: muted))),
|
||||
]));
|
||||
} else {
|
||||
final my = myFoods(store, text);
|
||||
final recent = recentFoods(store, text, limit: 5);
|
||||
final db = widget.fdb?.search(text, limit: 14) ?? [];
|
||||
if (my.isNotEmpty) sections.add(('My foods', [for (final f in my) _foodTile(f)]));
|
||||
if (recent.isNotEmpty) sections.add(('Eaten before', [for (final (e, n) in recent) _recent(e, n)]));
|
||||
final kept = keptProducts(store, text, fold: fold);
|
||||
final usda = db.where((f) => f.kind == 'usda').take(8).toList(),
|
||||
off = [...kept, ...db.where((f) => f.kind == 'off' && !kept.any((k) => k.foodId == f.foodId))].take(6).toList();
|
||||
if (usda.isNotEmpty) sections.add(('Food database', [for (final f in usda) _foodTile(f)]));
|
||||
if (off.isNotEmpty) sections.add(('Products', [for (final f in off) _foodTile(f)]));
|
||||
if (widget.fdb == null) sections.add(('', [const Text('Loading the food database…', style: TextStyle(color: muted))]));
|
||||
}
|
||||
return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
TextField(
|
||||
controller: q,
|
||||
autofocus: true,
|
||||
decoration: InputDecoration(
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
hintText: 'Search foods…',
|
||||
suffixIcon: IconButton(tooltip: 'Scan a barcode', icon: const Icon(Icons.qr_code_scanner), onPressed: _scan),
|
||||
),
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Flexible(
|
||||
child: ListView(shrinkWrap: true, children: [
|
||||
for (final (title, items) in sections) ...[
|
||||
if (title.isNotEmpty)
|
||||
Padding(padding: const EdgeInsets.only(top: 10, bottom: 2),
|
||||
child: Text(title, style: const TextStyle(color: muted, fontSize: 12.5, fontWeight: FontWeight.bold))),
|
||||
...items,
|
||||
],
|
||||
if (sections.isEmpty && text.isNotEmpty) const Padding(padding: EdgeInsets.all(12),
|
||||
child: Text('Nothing found', style: TextStyle(color: muted))),
|
||||
if (text.length >= 3)
|
||||
TextButton.icon(
|
||||
onPressed: () => _archive(text),
|
||||
icon: const Icon(Icons.travel_explore),
|
||||
label: Text(RegExp(r'^\d{8,14}$').hasMatch(text) ? 'Look up barcode $text in all products' : 'Search all products for “$text”'),
|
||||
),
|
||||
if (text.isNotEmpty)
|
||||
TextButton.icon(
|
||||
onPressed: () async {
|
||||
final uid = await openFoodEditor(context, widget.sync, name: text);
|
||||
final f = uid == null ? null : myFoodByUid(widget.sync.store, uid);
|
||||
if (f != null && mounted) _pick(f);
|
||||
},
|
||||
icon: const Icon(Icons.add),
|
||||
label: Text('New food “$text” (from its label)'),
|
||||
),
|
||||
if (text.isNotEmpty)
|
||||
TextButton.icon(
|
||||
onPressed: () => setState(() {
|
||||
mode = 'totals';
|
||||
name.text = text;
|
||||
amount.text = '';
|
||||
unit = '';
|
||||
unitCtl.text = '';
|
||||
copyFrom = null;
|
||||
}),
|
||||
icon: const Icon(Icons.edit_note),
|
||||
label: Text('“$text” with my own numbers'),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/// The archive (every Open Food Facts product) → the one picked, kept, then as any food.
|
||||
Future<void> _archive(String text) async {
|
||||
final f = await openArchive(context, widget.sync, widget.fdb, text);
|
||||
if (f != null && mounted) _pick(f);
|
||||
}
|
||||
|
||||
/// The camera → a barcode: its product here, else straight to the archive.
|
||||
Future<void> _scan() async {
|
||||
final code = await scanBarcode(context);
|
||||
if (code == null || !mounted) return;
|
||||
final here = widget.fdb?.byBarcode(code) ?? keptByBarcode(widget.sync.store, code);
|
||||
if (here.length == 1) return _pick(here.first);
|
||||
setState(() => q.text = code);
|
||||
if (here.isEmpty) await _archive(code);
|
||||
}
|
||||
|
||||
Widget _yday(Entry e, bool done) => ListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(e.name),
|
||||
subtitle: Text('${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal', style: const TextStyle(color: muted)),
|
||||
onTap: () => _fromEntry(e),
|
||||
trailing: done
|
||||
? const Icon(Icons.check, color: good)
|
||||
: IconButton(
|
||||
tooltip: 'Add as it was',
|
||||
icon: const Icon(Icons.add_circle, color: accent),
|
||||
onPressed: () {
|
||||
addAgain(widget.sync.store, widget.fdb, e, widget.day, meal);
|
||||
widget.sync.changed();
|
||||
setState(() {});
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
Widget _recent(Entry e, int n) => ListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(e.name),
|
||||
subtitle: Text('${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal · $n×', style: const TextStyle(color: muted)),
|
||||
onTap: () => _fromEntry(e),
|
||||
);
|
||||
|
||||
/// An older entry picked: its food with its portion, else its numbers (scaled with the amount).
|
||||
void _fromEntry(Entry e) {
|
||||
final f = foodOf(widget.sync.store, widget.fdb, e);
|
||||
if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) {
|
||||
_pick(f, e.amount!, e.unit!);
|
||||
} else {
|
||||
_totals(e, copy: true);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _foodTile(Food f) {
|
||||
final k = f.per100['kcal'];
|
||||
final sub = [
|
||||
if (f.kind == 'off') f.brand ?? '' else if (f.kind != 'my') f.category,
|
||||
if (k != null) '${k.round()} kcal / 100 g',
|
||||
if (f.isMeal) 'meal',
|
||||
].where((x) => x.isNotEmpty).join(' · ');
|
||||
return ListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(f.name),
|
||||
subtitle: Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted)),
|
||||
trailing: f.nutriscore == null ? null : _score(f.nutriscore!),
|
||||
onTap: () => _pick(f),
|
||||
);
|
||||
}
|
||||
|
||||
static Widget _score(String s) {
|
||||
const colors = {'a': Color(0xFF1E8F4E), 'b': Color(0xFF7AC547), 'c': Color(0xFFF2C40F), 'd': Color(0xFFEE8100), 'e': Color(0xFFE63E11)};
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
|
||||
decoration: BoxDecoration(color: colors[s] ?? card2, borderRadius: BorderRadius.circular(5)),
|
||||
child: Text(s.toUpperCase(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- food: amount + unit
|
||||
Widget _foodForm() {
|
||||
final f = food!;
|
||||
final a = double.tryParse(amount.text.trim().replaceAll(',', '.'));
|
||||
final g = a == null ? null : f.grams(a, unit);
|
||||
final nut = g == null ? null : f.nutrients(g);
|
||||
final source = switch (f.kind) {
|
||||
'my' => f.isMeal ? 'My meal' : 'My food',
|
||||
'off' => 'Product (Open Food Facts)${f.brand != null ? ' · ${f.brand}' : ''}',
|
||||
_ => 'Food database (USDA)',
|
||||
};
|
||||
return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
InkWell(
|
||||
onTap: () => setState(() => mode = 'search'),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(children: [
|
||||
Expanded(child: Text(f.name, style: const TextStyle(fontSize: 16.5, fontWeight: FontWeight.bold))),
|
||||
const Icon(Icons.search, color: muted, size: 18),
|
||||
]),
|
||||
),
|
||||
),
|
||||
Text(source, style: const TextStyle(color: muted, fontSize: 12.5)),
|
||||
const SizedBox(height: 10),
|
||||
Row(children: [
|
||||
SizedBox(
|
||||
width: 100,
|
||||
child: TextField(
|
||||
controller: amount,
|
||||
autofocus: widget.entry == null,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
decoration: const InputDecoration(labelText: 'Amount'),
|
||||
onChanged: (_) => setState(() {}),
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<String>(
|
||||
initialValue: f.units.contains(unit) ? unit : 'g',
|
||||
isExpanded: true,
|
||||
dropdownColor: card2,
|
||||
decoration: const InputDecoration(labelText: 'Unit'),
|
||||
items: [
|
||||
for (final u in f.units)
|
||||
DropdownMenuItem(value: u, child: Text(f.portions.any((p) => p.label == u)
|
||||
? '$u (${num1(f.portions.firstWhere((p) => p.label == u).grams)} g)' : u, overflow: TextOverflow.ellipsis)),
|
||||
],
|
||||
onChanged: (u) => setState(() => unit = u!),
|
||||
),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 10),
|
||||
if (nut != null)
|
||||
Row(children: [
|
||||
Text('${(nut['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
|
||||
Text(' · ${num1(g!)} g · ', style: const TextStyle(color: muted)),
|
||||
macroDots(nut),
|
||||
]),
|
||||
if (nut != null && (nut['fiber'] != null || nut['sugar'] != null))
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 3),
|
||||
child: Text([
|
||||
if (nut['fiber'] != null) 'fibre ${num1(nut['fiber']!)} g',
|
||||
if (nut['sugar'] != null) 'sugar ${num1(nut['sugar']!)} g',
|
||||
if (nut['sat_fat'] != null) 'sat. fat ${num1(nut['sat_fat']!)} g',
|
||||
if (nut['sodium_mg'] != null) 'sodium ${nut['sodium_mg']!.round()} mg',
|
||||
].join(' · '), style: const TextStyle(color: muted, fontSize: 12.5)),
|
||||
),
|
||||
_actions(),
|
||||
]);
|
||||
}
|
||||
|
||||
// ---- totals: an entry without a food
|
||||
Widget _totalsForm() => Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
TextField(controller: name, decoration: const InputDecoration(labelText: 'What was it?')),
|
||||
Row(children: [
|
||||
SizedBox(width: 100, child: TextField(controller: amount, keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
decoration: const InputDecoration(labelText: 'Amount'))),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: TextField(controller: unitCtl, onChanged: (v) => unit = v.trim(),
|
||||
decoration: const InputDecoration(labelText: 'Unit (g, pcs, bowl…)'))),
|
||||
]),
|
||||
Row(children: [
|
||||
for (final (k, l) in [('kcal', 'kcal'), ('protein', 'Protein g'), ('carbs', 'Carbs g'), ('fat', 'Fat g')])
|
||||
Expanded(child: Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: TextField(controller: totalsCtl[k], keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
textInputAction: TextInputAction.next, decoration: InputDecoration(labelText: l)),
|
||||
)),
|
||||
]),
|
||||
if (widget.entry != null && widget.entry!.source != 'manual')
|
||||
Padding(padding: const EdgeInsets.only(top: 6),
|
||||
child: Text('Imported from ${widget.entry!.source} — its other nutrients stay as they are.',
|
||||
style: const TextStyle(color: muted, fontSize: 12.5))),
|
||||
_actions(),
|
||||
]);
|
||||
|
||||
Widget _actions() => Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
if (error != null) Padding(padding: const EdgeInsets.only(bottom: 6), child: Text(error!, style: const TextStyle(color: bad))),
|
||||
Row(children: [
|
||||
if (widget.entry != null)
|
||||
TextButton.icon(
|
||||
icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad),
|
||||
style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null),
|
||||
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)),
|
||||
onPressed: () {
|
||||
if (!armed) return setState(() => armed = true);
|
||||
widget.sync.store.delete('food.entry', widget.entry!.u);
|
||||
_done();
|
||||
},
|
||||
),
|
||||
const Spacer(),
|
||||
FilledButton(onPressed: _save, child: Text(widget.entry == null ? 'Add' : 'Save')),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
}
|
||||
309
app/lib/health/heart_page.dart
Normal file
309
app/lib/health/heart_page.dart
Normal file
|
|
@ -0,0 +1,309 @@
|
|||
// Health ▸ Heart (as on the web page's Heart tab): heart rate from the band (the Pi's summaries:
|
||||
// the latest day, resting, lowest / highest / resting per day), then the vitals — Blood pressure and
|
||||
// Blood oxygen, each its own card: latest + category (ESC 2024 / SpO₂ bands), 30-day average, chart,
|
||||
// the readings (tap = edit) and + Add.
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import '../widgets/line_chart.dart';
|
||||
import 'body_model.dart';
|
||||
import 'body_page.dart' show classColor, dm, dmy;
|
||||
import 'cycle_model.dart' show day, parseDay, plus, today;
|
||||
import 'range.dart';
|
||||
import 'summaries.dart';
|
||||
|
||||
String _hm(DateTime t) => t.toIso8601String().substring(11, 16);
|
||||
|
||||
class HeartPage extends StatefulWidget {
|
||||
const HeartPage({super.key, required this.sync, required this.range});
|
||||
final SyncService sync;
|
||||
final HealthRange range;
|
||||
@override
|
||||
State<HeartPage> createState() => _HeartPageState();
|
||||
}
|
||||
|
||||
class _HeartPageState extends State<HeartPage> {
|
||||
final shown = {'bp': 5, 'ox': 5};
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.sync, widget.range]),
|
||||
builder: (context, _) {
|
||||
final all = vitals(widget.sync.store);
|
||||
final bp = all.where((v) => v.isBp).toList(), ox = all.where((v) => v.spo2 != null).toList();
|
||||
return LayoutBuilder(builder: (context, box) {
|
||||
final cards = [_bp(bp), _ox(ox)];
|
||||
final hrCard = _hr();
|
||||
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
|
||||
if (hrCard != null) ...[hrCard, const SizedBox(height: 12)],
|
||||
if (box.maxWidth >= 700)
|
||||
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Expanded(child: cards[0]), const SizedBox(width: 12), Expanded(child: cards[1])])
|
||||
else ...[cards[0], const SizedBox(height: 12), cards[1]],
|
||||
]);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
/// Heart rate from the band (the Pi's day summaries): the latest day's low – high, the resting rate
|
||||
/// used for zones / calories, and lowest / highest / resting per day over the period.
|
||||
Widget? _hr() {
|
||||
final sm = Summaries(widget.sync.store);
|
||||
final days = sm.all('day').where((x) => x['hr'] != null).toList();
|
||||
if (days.isEmpty) return null;
|
||||
final person = sm.meta('person') ?? {};
|
||||
final last = days.last, h = (last['hr'] as Map).cast<String, dynamic>();
|
||||
final from = widget.range.from(parseDay(days.first['_day'] as String), today());
|
||||
List<(DateTime, double)> pts(String k) => [
|
||||
for (final x in days)
|
||||
if ((x['hr'] as Map)[k] != null) (parseDay(x['_day'] as String), ((x['hr'] as Map)[k] as num).toDouble())
|
||||
];
|
||||
final lastDay = parseDay(last['_day'] as String);
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
const Expanded(child: Text('Heart rate', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||||
Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
showDuration: const Duration(seconds: 8),
|
||||
message: 'From your band (Gadgetbridge → the dashboard). Resting = the median of the last 90 days '
|
||||
'${person['rest_set'] == true ? '(your setting)' : '(worked out)'}; max ${person['hrmax'] ?? '—'} bpm. '
|
||||
'Zones and workout calories use both.',
|
||||
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
|
||||
),
|
||||
]),
|
||||
Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
|
||||
Text('${h['low'] ?? '—'}–${h['high'] ?? '—'}', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
|
||||
const Text(' bpm', style: TextStyle(color: muted)),
|
||||
const Spacer(),
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
|
||||
Text('resting ${person['rest'] ?? '—'} bpm', style: const TextStyle(color: good)),
|
||||
Text(lastDay == today() ? 'today so far' : dm(lastDay), style: const TextStyle(color: muted, fontSize: 12.5)),
|
||||
]),
|
||||
const SizedBox(width: 6),
|
||||
]),
|
||||
const SizedBox(height: 10),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 6),
|
||||
child: LineChart(from: from, to: plus(today(), 1), unit: 'bpm', decimals: 0, range: widget.range, series: [
|
||||
Series('Highest', pts('high'), bad),
|
||||
Series('Lowest', pts('low'), const Color(0xFF5CC8FF)),
|
||||
Series('Resting', pts('rest'), good),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// The readings inside the charts' period (the latest is shown on top regardless).
|
||||
List<Vital> _inPeriod(List<Vital> vs) => vs.where((v) => !day(v.t).isBefore(_from(vs))).toList();
|
||||
|
||||
DateTime _from(List<Vital> vs) => widget.range.from(vs.isEmpty ? today() : day(vs.last.t), today());
|
||||
|
||||
Widget _bp(List<Vital> vs) {
|
||||
final last = vs.firstOrNull;
|
||||
final listed = _inPeriod(vs);
|
||||
final since = plus(today(), -30);
|
||||
final month = vs.where((v) => !v.t.isBefore(since)).toList();
|
||||
final avg = month.isEmpty ? null : (
|
||||
(month.map((v) => v.sys!).reduce((a, b) => a + b) / month.length).round(),
|
||||
(month.map((v) => v.dia!).reduce((a, b) => a + b) / month.length).round());
|
||||
final c = bpClass(last?.sys, last?.dia);
|
||||
return _VitalCard(
|
||||
title: 'Blood pressure',
|
||||
head: last == null ? 'No readings yet' : '${last.sys} / ${last.dia} mmHg',
|
||||
sub: last == null ? '' : '${c!.$1} · ${dm(last.t)} ${_hm(last.t)}',
|
||||
subColor: classColor(c?.$2),
|
||||
extra: avg == null ? null : '30-day average ${avg.$1} / ${avg.$2} (${month.length} reading${month.length != 1 ? 's' : ''})',
|
||||
info: 'ESC 2024 (office readings): under 120 / 70 non-elevated · 120–139 / 70–89 elevated · 140 / 90+ hypertension · '
|
||||
'180 / 110+ severe. The higher of the two numbers decides; the average of several readings on different days is what counts.',
|
||||
chart: vs.isEmpty ? null : LineChart(from: _from(vs), to: plus(today(), 1), unit: 'mmHg', decimals: 0, range: widget.range, series: [
|
||||
Series('Systolic', vitalSeries(vs, (v) => v.sys?.toDouble()), accent),
|
||||
Series('Diastolic', vitalSeries(vs, (v) => v.dia?.toDouble()), const Color(0xFF5CC8FF)),
|
||||
]),
|
||||
rows: [
|
||||
if (listed.isEmpty && vs.isNotEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
|
||||
child: Text('No readings in this period', style: TextStyle(color: muted))),
|
||||
for (final v in listed.take(shown['bp']!))
|
||||
_ReadingRow(v, '${v.sys} / ${v.dia}', classColor(bpClass(v.sys, v.dia)?.$2), () => _edit('bp', v)),
|
||||
],
|
||||
more: listed.length - shown['bp']!,
|
||||
onMore: () => setState(() => shown['bp'] = shown['bp']! + 10),
|
||||
onAdd: () => _edit('bp', null),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _ox(List<Vital> vs) {
|
||||
final last = vs.firstOrNull;
|
||||
final listed = _inPeriod(vs);
|
||||
final c = spo2Class(last?.spo2);
|
||||
return _VitalCard(
|
||||
title: 'Blood oxygen',
|
||||
head: last == null ? 'No readings yet' : '${last.spo2!.round()} %',
|
||||
sub: last == null ? '' : '${c!.$1} · ${dm(last.t)} ${_hm(last.t)}${last.source != null ? ' · ${vitalSources[last.source] ?? last.source}' : ''}',
|
||||
subColor: classColor(c?.$2),
|
||||
info: 'At rest: 95–100 % normal · 91–94 % low · 90 % or less very low (see a doctor). Wrist sensors read a couple of % low '
|
||||
'now and then — a single low spot check isn\'t a verdict.',
|
||||
chart: vs.isEmpty ? null : LineChart(from: _from(vs), to: plus(today(), 1), unit: '%', decimals: 0, band: (95, 100), limits: (85, 100), range: widget.range,
|
||||
series: [Series('SpO₂', vitalSeries(vs, (v) => v.spo2), accent)]),
|
||||
rows: [
|
||||
if (listed.isEmpty && vs.isNotEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
|
||||
child: Text('No readings in this period', style: TextStyle(color: muted))),
|
||||
for (final v in listed.take(shown['ox']!))
|
||||
_ReadingRow(v, '${v.spo2!.round()} %', classColor(spo2Class(v.spo2)?.$2), () => _edit('ox', v)),
|
||||
],
|
||||
more: listed.length - shown['ox']!,
|
||||
onMore: () => setState(() => shown['ox'] = shown['ox']! + 10),
|
||||
onAdd: () => _edit('ox', null),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _edit(String kind, Vital? v) => showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => VitalSheet(kind: kind, v: v, sync: widget.sync),
|
||||
);
|
||||
}
|
||||
|
||||
class _VitalCard extends StatelessWidget {
|
||||
const _VitalCard({required this.title, required this.head, required this.sub, required this.subColor, this.extra,
|
||||
required this.info, required this.chart, required this.rows, required this.more, required this.onMore, required this.onAdd});
|
||||
final String title, head, sub, info;
|
||||
final String? extra;
|
||||
final Color subColor;
|
||||
final Widget? chart;
|
||||
final List<Widget> rows;
|
||||
final int more;
|
||||
final VoidCallback onMore, onAdd;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||||
Tooltip(triggerMode: TooltipTriggerMode.tap, message: info, showDuration: const Duration(seconds: 8),
|
||||
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted))),
|
||||
TextButton.icon(onPressed: onAdd, icon: const Icon(Icons.add, size: 18), label: const Text('Add')),
|
||||
]),
|
||||
Text(head, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
|
||||
if (sub.isNotEmpty) Text(sub, style: TextStyle(color: subColor)),
|
||||
if (extra != null) Text(extra!, style: const TextStyle(color: muted, fontSize: 13)),
|
||||
if (chart != null) ...[const SizedBox(height: 10), Padding(padding: const EdgeInsets.only(right: 6), child: chart!)],
|
||||
...rows,
|
||||
if (more > 0) TextButton(onPressed: onMore, child: Text('Show more ($more)')),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _ReadingRow extends StatelessWidget {
|
||||
const _ReadingRow(this.v, this.value, this.color, this.onTap);
|
||||
final Vital v;
|
||||
final String value;
|
||||
final Color color;
|
||||
final VoidCallback onTap;
|
||||
@override
|
||||
Widget build(BuildContext context) => InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(children: [
|
||||
SizedBox(width: 160, child: Text('${v.t.year == today().year ? dm(v.t) : dmy(v.t)} ${_hm(v.t)}', maxLines: 1,
|
||||
style: const TextStyle(color: muted))),
|
||||
SizedBox(width: 72, child: Text(value, style: TextStyle(color: color))),
|
||||
Expanded(child: Text(v.note.isNotEmpty ? v.note : vitalSources[v.source] ?? '', overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(color: muted, fontSize: 13))),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Add / edit one reading: date + time, the numbers of its kind, note; Delete = tap twice.
|
||||
class VitalSheet extends StatefulWidget {
|
||||
const VitalSheet({super.key, required this.kind, required this.v, required this.sync});
|
||||
final String kind;
|
||||
final Vital? v;
|
||||
final SyncService sync;
|
||||
@override
|
||||
State<VitalSheet> createState() => _VitalSheetState();
|
||||
}
|
||||
|
||||
class _VitalSheetState extends State<VitalSheet> {
|
||||
late DateTime t = widget.v?.t ?? () {
|
||||
final n = DateTime.now();
|
||||
return DateTime.utc(n.year, n.month, n.day, n.hour, n.minute);
|
||||
}();
|
||||
late final sys = TextEditingController(text: widget.v?.sys?.toString() ?? '');
|
||||
late final dia = TextEditingController(text: widget.v?.dia?.toString() ?? '');
|
||||
late final ox = TextEditingController(text: widget.v?.spo2 == null ? '' : widget.v!.spo2!.round().toString());
|
||||
late final note = TextEditingController(text: widget.v?.note ?? '');
|
||||
String? error;
|
||||
bool armed = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bp = widget.kind == 'bp';
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Text('${widget.v == null ? 'Add' : 'Edit'} ${bp ? 'blood pressure' : 'blood oxygen'}',
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||||
Row(children: [
|
||||
TextButton.icon(icon: const Icon(Icons.event, size: 18), label: Text(dmy(t)), onPressed: () async {
|
||||
final p = await showDatePicker(context: context, initialDate: t, firstDate: DateTime.utc(2000), lastDate: today());
|
||||
if (p != null) setState(() => t = DateTime.utc(p.year, p.month, p.day, t.hour, t.minute));
|
||||
}),
|
||||
TextButton.icon(icon: const Icon(Icons.schedule, size: 18), label: Text(_hm(t)), onPressed: () async {
|
||||
final p = await showTimePicker(context: context, initialTime: TimeOfDay(hour: t.hour, minute: t.minute));
|
||||
if (p != null) setState(() => t = DateTime.utc(t.year, t.month, t.day, p.hour, p.minute));
|
||||
}),
|
||||
]),
|
||||
if (bp)
|
||||
Row(children: [
|
||||
Expanded(child: TextField(controller: sys, keyboardType: TextInputType.number, autofocus: widget.v == null,
|
||||
textInputAction: TextInputAction.next,
|
||||
decoration: const InputDecoration(labelText: 'Systolic (upper)', suffixText: 'mmHg'))),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: TextField(controller: dia, keyboardType: TextInputType.number,
|
||||
decoration: const InputDecoration(labelText: 'Diastolic (lower)', suffixText: 'mmHg'))),
|
||||
])
|
||||
else
|
||||
TextField(controller: ox, keyboardType: const TextInputType.numberWithOptions(decimal: true), autofocus: widget.v == null,
|
||||
decoration: const InputDecoration(labelText: 'Blood oxygen', suffixText: '%')),
|
||||
TextField(controller: note, maxLength: 500, decoration: const InputDecoration(labelText: 'Note')),
|
||||
if (error != null) Text(error!, style: const TextStyle(color: bad)),
|
||||
Row(children: [
|
||||
if (widget.v != null)
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (!armed) return setState(() => armed = true);
|
||||
widget.sync.store.delete('health.vital', widget.v!.u);
|
||||
widget.sync.changed();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Text(armed ? 'Tap again to delete' : 'Delete', style: const TextStyle(color: bad)),
|
||||
),
|
||||
const Spacer(),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final err = saveVital(widget.sync.store, u: widget.v?.u, kind: widget.kind, t: t,
|
||||
sys: int.tryParse(sys.text.trim()), dia: int.tryParse(dia.text.trim()),
|
||||
spo2: double.tryParse(ox.text.trim().replaceAll(',', '.')), note: note.text);
|
||||
if (err != null) return setState(() => error = err);
|
||||
widget.sync.changed();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Save'),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
314
app/lib/health/meal_builder.dart
Normal file
314
app/lib/health/meal_builder.dart
Normal file
|
|
@ -0,0 +1,314 @@
|
|||
// The meal builder (the web page's #fd-meal): a meal = one of My foods made of others. Name,
|
||||
// ingredients (a food + amount + unit, or an entry's own numbers), the total, "weight when done"
|
||||
// (soup boils down / takes on water; empty = the ingredients' sum), per 100 g, portions ("whole meal"
|
||||
// is added by itself), note. Saving works the values out from the ingredients as they are now.
|
||||
// Ways in: My foods (a meal, or + ▸ New meal) and Food ⋮ ▸ Make a meal (from the day's entries:
|
||||
// "put them together as one entry" replaces them by one entry of the meal — the day's total stays).
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'food_model.dart';
|
||||
import 'food_page.dart' show macroDots;
|
||||
import 'sugar.dart' show fold;
|
||||
|
||||
/// Search My foods + the database and pick one (for an ingredient).
|
||||
Future<Food?> pickFood(BuildContext context, SyncService sync, FoodDb? fdb) => showModalBottomSheet<Food>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => _Picker(sync: sync, fdb: fdb),
|
||||
);
|
||||
|
||||
class _Picker extends StatefulWidget {
|
||||
const _Picker({required this.sync, required this.fdb});
|
||||
final SyncService sync;
|
||||
final FoodDb? fdb;
|
||||
@override
|
||||
State<_Picker> createState() => _PickerState();
|
||||
}
|
||||
|
||||
class _PickerState extends State<_Picker> {
|
||||
final q = TextEditingController();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final t = q.text.trim();
|
||||
final my = t.isEmpty ? <Food>[] : myFoods(widget.sync.store, t);
|
||||
final kept = t.isEmpty ? <Food>[] : keptProducts(widget.sync.store, t, fold: fold); // picked from the archive before
|
||||
final db = t.isEmpty ? <Food>[] : [...kept, ...(widget.fdb?.search(t, limit: 12) ?? []).where((f) => !kept.any((k) => k.foodId == f.foodId))];
|
||||
Widget tile(Food f) => ListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(f.name),
|
||||
subtitle: Text([
|
||||
if (f.kind == 'my') f.isMeal ? 'My meal' : 'My food' else if (f.kind == 'off') f.brand ?? 'product' else f.category,
|
||||
'${(f.per100['kcal'] ?? 0).round()} kcal / 100 g',
|
||||
].join(' · '), style: const TextStyle(color: muted)),
|
||||
onTap: () => Navigator.pop(context, f),
|
||||
);
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 14, 16, 12 + MediaQuery.of(context).viewInsets.bottom),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
const Text('Add an ingredient', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||||
TextField(controller: q, autofocus: true, onChanged: (_) => setState(() {}),
|
||||
decoration: const InputDecoration(prefixIcon: Icon(Icons.search), hintText: 'Search foods…')),
|
||||
Flexible(child: ListView(shrinkWrap: true, children: [
|
||||
if (my.isNotEmpty) const Padding(padding: EdgeInsets.only(top: 8), child: Text('My foods', style: TextStyle(color: muted, fontSize: 12.5))),
|
||||
...my.map(tile),
|
||||
if (db.isNotEmpty) const Padding(padding: EdgeInsets.only(top: 8), child: Text('Food database · products', style: TextStyle(color: muted, fontSize: 12.5))),
|
||||
...db.map(tile),
|
||||
])),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The day's entries to tick for a meal → (picked entries) or null; "from scratch" = [].
|
||||
Future<List<Entry>?> pickEntries(BuildContext context, List<Entry> es) => showModalBottomSheet<List<Entry>>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => _EntryPicker(es),
|
||||
);
|
||||
|
||||
class _EntryPicker extends StatefulWidget {
|
||||
const _EntryPicker(this.es);
|
||||
final List<Entry> es;
|
||||
@override
|
||||
State<_EntryPicker> createState() => _EntryPickerState();
|
||||
}
|
||||
|
||||
class _EntryPickerState extends State<_EntryPicker> {
|
||||
final picked = <String>{};
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
const Text('Make a meal', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||||
const Text('Tick what went into it — or start from scratch.', style: TextStyle(color: muted)),
|
||||
Flexible(child: ListView(shrinkWrap: true, children: [
|
||||
for (final e in widget.es)
|
||||
CheckboxListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
value: picked.contains(e.u),
|
||||
onChanged: (x) => setState(() => x! ? picked.add(e.u) : picked.remove(e.u)),
|
||||
title: Text(e.name),
|
||||
subtitle: Text('${mealLabels[e.meal]} · ${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal',
|
||||
style: const TextStyle(color: muted)),
|
||||
),
|
||||
])),
|
||||
Row(children: [
|
||||
TextButton(onPressed: () => Navigator.pop(context, <Entry>[]), child: const Text('Start from scratch')),
|
||||
const Spacer(),
|
||||
FilledButton(
|
||||
onPressed: picked.isEmpty ? null : () => Navigator.pop(context, widget.es.where((e) => picked.contains(e.u)).toList()),
|
||||
child: Text('Next (${picked.length})'),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class MealBuilder extends StatefulWidget {
|
||||
/// [row] = the meal being edited; [fromEntries] = entries to build it from (they may be replaced).
|
||||
const MealBuilder({super.key, required this.sync, required this.fdb, this.row, this.fromEntries = const []});
|
||||
final SyncService sync;
|
||||
final FoodDb? fdb;
|
||||
final Map<String, dynamic>? row;
|
||||
final List<Entry> fromEntries;
|
||||
@override
|
||||
State<MealBuilder> createState() => _MealBuilderState();
|
||||
}
|
||||
|
||||
class _MealBuilderState extends State<MealBuilder> {
|
||||
late final name = TextEditingController(text: widget.row?['name'] as String? ?? '');
|
||||
late final note = TextEditingController(text: widget.row?['note'] as String? ?? '');
|
||||
late final done = TextEditingController(
|
||||
text: widget.row == null || doneGramsOf(widget.row!) == null ? '' : num1(doneGramsOf(widget.row!)!));
|
||||
late final List<Ingredient> ings = widget.row != null
|
||||
? recipeOf(widget.sync.store, widget.fdb, widget.row!)
|
||||
: [for (final e in widget.fromEntries) _fromEntry(e)];
|
||||
late final amounts = [for (final i in ings) TextEditingController(text: i.amount == null ? '' : num1(i.amount!))];
|
||||
late final portions = [
|
||||
for (final p in (widget.row == null ? <Portion>[] : myFood(widget.row!).portions).where((p) => p.label != 'whole meal'))
|
||||
(TextEditingController(text: p.label), TextEditingController(text: num1(p.grams)))
|
||||
];
|
||||
bool together = true, armed = false;
|
||||
String? error;
|
||||
|
||||
Ingredient _fromEntry(Entry e) {
|
||||
final f = foodOf(widget.sync.store, widget.fdb, e);
|
||||
if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) return Ingredient.food(f, e.amount, e.unit);
|
||||
// its grams when known — an amount in g / ml is its weight
|
||||
final g = e.n('grams') ?? (e.amount != null && (e.unit == 'g' || e.unit == 'ml') ? e.amount : null);
|
||||
return Ingredient.fixed({for (final c in foodCols) c: e.n(c)}, e.name, e.amount, e.unit, g);
|
||||
}
|
||||
|
||||
double? _n(TextEditingController c) => double.tryParse(c.text.trim().replaceAll(',', '.'));
|
||||
|
||||
Future<void> _add() async {
|
||||
final f = await pickFood(context, widget.sync, widget.fdb);
|
||||
if (f == null) return;
|
||||
setState(() {
|
||||
final unit = f.portions.isNotEmpty ? f.portions.first.label : 'g';
|
||||
ings.add(Ingredient.food(f, unit == 'g' ? 100 : 1, unit));
|
||||
amounts.add(TextEditingController(text: unit == 'g' ? '100' : '1'));
|
||||
});
|
||||
}
|
||||
|
||||
void _save() {
|
||||
for (var i = 0; i < ings.length; i++) {
|
||||
ings[i].amount = _n(amounts[i]);
|
||||
}
|
||||
final ps = [for (final (l, g) in portions) if (l.text.trim().isNotEmpty || g.text.trim().isNotEmpty) Portion(l.text, _n(g) ?? 0)];
|
||||
final store = widget.sync.store;
|
||||
final (uid, err) = saveMeal(store, uid: widget.row?['_u'] as String?, name: name.text, ings: ings,
|
||||
doneGrams: _n(done), portions: ps, note: note.text);
|
||||
if (err != null) return setState(() => error = err);
|
||||
if (widget.fromEntries.isNotEmpty && together) {
|
||||
// one entry of the meal (its whole weight) replaces the picked ones: their day, the most common meal
|
||||
final es = widget.fromEntries;
|
||||
final counts = <String, int>{};
|
||||
for (final e in es) {
|
||||
counts[e.meal] = (counts[e.meal] ?? 0) + 1;
|
||||
}
|
||||
final meal = (counts.entries.toList()..sort((a, b) => b.value.compareTo(a.value))).first.key;
|
||||
saveFromFood(store, day: es.first.day, meal: meal.isEmpty ? 'snack' : meal, food: myFoodByUid(store, uid!)!,
|
||||
amount: 1, unit: 'whole meal');
|
||||
for (final e in es) {
|
||||
store.delete('food.entry', e.u);
|
||||
}
|
||||
}
|
||||
widget.sync.changed();
|
||||
Navigator.pop(context, uid);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
for (var i = 0; i < ings.length; i++) {
|
||||
ings[i].amount = _n(amounts[i]);
|
||||
}
|
||||
final tot = <String, double>{};
|
||||
var grams = 0.0;
|
||||
for (final i in ings) {
|
||||
i.values.forEach((c, v) {
|
||||
if (v != null) tot[c] = (tot[c] ?? 0) + v;
|
||||
});
|
||||
grams += i.g ?? 0;
|
||||
}
|
||||
final weight = _n(done) ?? grams;
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(widget.row == null ? 'New meal' : 'Edit meal')),
|
||||
body: ListView(padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), children: [
|
||||
TextField(controller: name, decoration: const InputDecoration(labelText: 'Name (e.g. “Cabbage soup (20th Oct 2026)”)')),
|
||||
const SizedBox(height: 14),
|
||||
Row(children: [
|
||||
const Expanded(child: Text('Ingredients', style: TextStyle(fontWeight: FontWeight.bold))),
|
||||
TextButton.icon(onPressed: _add, icon: const Icon(Icons.add, size: 18), label: const Text('Ingredient')),
|
||||
]),
|
||||
for (var i = 0; i < ings.length; i++) _ing(i),
|
||||
if (ings.isEmpty) const Text('Nothing yet — + Ingredient.', style: TextStyle(color: muted)),
|
||||
const Divider(color: card2, height: 24),
|
||||
Row(children: [
|
||||
const Text('All together ', style: TextStyle(color: muted)),
|
||||
Text('${(tot['kcal'] ?? 0).round()} kcal · ${num1(grams)} g', style: const TextStyle(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(width: 8),
|
||||
macroDots(tot),
|
||||
]),
|
||||
TextField(controller: done, keyboardType: const TextInputType.numberWithOptions(decimal: true), onChanged: (_) => setState(() {}),
|
||||
decoration: InputDecoration(labelText: 'Weight when done (empty = ${num1(grams)} g)', suffixText: 'g')),
|
||||
if (weight > 0)
|
||||
Padding(padding: const EdgeInsets.only(top: 6), child: Text(
|
||||
'Per 100 g: ${((tot['kcal'] ?? 0) * 100 / weight).round()} kcal · '
|
||||
'P ${num1((tot['protein'] ?? 0) * 100 / weight)} · C ${num1((tot['carbs'] ?? 0) * 100 / weight)} · '
|
||||
'F ${num1((tot['fat'] ?? 0) * 100 / weight)} g', style: const TextStyle(color: muted))),
|
||||
const SizedBox(height: 12),
|
||||
Row(children: [
|
||||
const Expanded(child: Text('Portions (“whole meal” is added by itself)', style: TextStyle(color: muted, fontSize: 13))),
|
||||
TextButton.icon(onPressed: () => setState(() => portions.add((TextEditingController(), TextEditingController()))),
|
||||
icon: const Icon(Icons.add, size: 18), label: const Text('Portion')),
|
||||
]),
|
||||
for (var i = 0; i < portions.length; i++)
|
||||
Row(children: [
|
||||
Expanded(flex: 3, child: TextField(controller: portions[i].$1, decoration: const InputDecoration(hintText: 'bowl, plate…', isDense: true))),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(flex: 2, child: TextField(controller: portions[i].$2, keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
decoration: const InputDecoration(suffixText: 'g', isDense: true))),
|
||||
IconButton(onPressed: () => setState(() => portions.removeAt(i)), icon: const Icon(Icons.close, size: 18, color: muted)),
|
||||
]),
|
||||
TextField(controller: note, decoration: const InputDecoration(labelText: 'Note')),
|
||||
if (widget.fromEntries.isNotEmpty)
|
||||
CheckboxListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
value: together,
|
||||
onChanged: (x) => setState(() => together = x!),
|
||||
title: Text('Put the ${widget.fromEntries.length} picked entries together in the diary as one entry'),
|
||||
subtitle: const Text('the day’s total stays the same', style: TextStyle(color: muted)),
|
||||
),
|
||||
if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))),
|
||||
const SizedBox(height: 12),
|
||||
Row(children: [
|
||||
if (widget.row != null)
|
||||
TextButton.icon(
|
||||
icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad),
|
||||
style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null),
|
||||
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)),
|
||||
onPressed: () {
|
||||
if (!armed) return setState(() => armed = true);
|
||||
deleteMyFood(widget.sync.store, widget.row!['_u'] as String);
|
||||
widget.sync.changed();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
const Spacer(),
|
||||
FilledButton(onPressed: _save, child: const Text('Save')),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _ing(int i) {
|
||||
final ing = ings[i];
|
||||
final v = ing.values;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(children: [
|
||||
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(ing.name, maxLines: 2, overflow: TextOverflow.ellipsis),
|
||||
Text(ing.food == null ? 'its own numbers${ing.grams == null ? ' · no weight' : ' · ${num1(ing.grams!)} g'}'
|
||||
: '${(v['kcal'] ?? 0).round()} kcal${ing.g == null ? '' : ' · ${num1(ing.g!)} g'}',
|
||||
style: const TextStyle(color: muted, fontSize: 12.5)),
|
||||
])),
|
||||
if (ing.food != null) ...[
|
||||
SizedBox(width: 64, child: TextField(controller: amounts[i], keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
onChanged: (_) => setState(() {}), decoration: const InputDecoration(isDense: true))),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(
|
||||
width: 110,
|
||||
child: DropdownButton<String>(
|
||||
value: ing.food!.units.contains(ing.unit) ? ing.unit : 'g',
|
||||
isExpanded: true,
|
||||
dropdownColor: card2,
|
||||
items: [for (final u in ing.food!.units) DropdownMenuItem(value: u, child: Text(u, overflow: TextOverflow.ellipsis))],
|
||||
onChanged: (u) => setState(() => ing.unit = u),
|
||||
),
|
||||
),
|
||||
] else
|
||||
Text('${(v['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontWeight: FontWeight.bold)),
|
||||
IconButton(onPressed: () => setState(() {
|
||||
ings.removeAt(i);
|
||||
amounts.removeAt(i);
|
||||
}), icon: const Icon(Icons.close, size: 18, color: muted)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
219
app/lib/health/my_foods.dart
Normal file
219
app/lib/health/my_foods.dart
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
// Food ▸ My foods: your own food database (values per 100 g, portions) — the list (tap = edit; a meal
|
||||
// opens the meal builder), + New food / New meal, and the food editor sheet (also opened from the add
|
||||
// sheet's "+ New food").
|
||||
// Delete = hidden (entries made from it keep their numbers), tap twice.
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'food_model.dart';
|
||||
import 'meal_builder.dart';
|
||||
|
||||
class MyFoodsPage extends StatelessWidget {
|
||||
const MyFoodsPage({super.key, required this.sync});
|
||||
final SyncService sync;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Scaffold(
|
||||
appBar: AppBar(title: const Text('My foods')),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
backgroundColor: accent,
|
||||
foregroundColor: bg,
|
||||
tooltip: 'New food',
|
||||
onPressed: () => showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: card,
|
||||
builder: (c) => SafeArea(child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
ListTile(leading: const Icon(Icons.label_outline), title: const Text('New food'),
|
||||
subtitle: const Text('from its label', style: TextStyle(color: muted)),
|
||||
onTap: () {
|
||||
Navigator.pop(c);
|
||||
openFoodEditor(context, sync);
|
||||
}),
|
||||
ListTile(leading: const Icon(Icons.soup_kitchen_outlined), title: const Text('New meal'),
|
||||
subtitle: const Text('from its ingredients', style: TextStyle(color: muted)),
|
||||
onTap: () async {
|
||||
Navigator.pop(c);
|
||||
final fdb = await FoodDb.open();
|
||||
if (context.mounted) {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: sync, fdb: fdb)));
|
||||
}
|
||||
}),
|
||||
])),
|
||||
),
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
body: ListenableBuilder(
|
||||
listenable: sync,
|
||||
builder: (context, _) {
|
||||
final all = allMyFoods(sync.store);
|
||||
if (all.isEmpty) {
|
||||
return const Center(child: Text('None yet — + to add a food from its label.', style: TextStyle(color: muted)));
|
||||
}
|
||||
return ListView(padding: const EdgeInsets.fromLTRB(12, 8, 12, 88), children: [
|
||||
for (final (r, uses) in all)
|
||||
Card(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
child: ListTile(
|
||||
title: Text(r['name'] as String),
|
||||
subtitle: Text([
|
||||
'${((r['kcal'] as num?) ?? 0).round()} kcal / 100 g',
|
||||
if (r['recipe'] != null) 'meal',
|
||||
...((jsonDecode((r['portions'] as String?) ?? '[]') as List).map((p) => '${p['label']} ${num1((p['grams'] as num).toDouble())} g')),
|
||||
if (uses > 0) 'used $uses×',
|
||||
].join(' · '), style: const TextStyle(color: muted)),
|
||||
onTap: () async {
|
||||
if (r['recipe'] == null) {
|
||||
await openFoodEditor(context, sync, row: r);
|
||||
return;
|
||||
}
|
||||
final fdb = await FoodDb.open();
|
||||
if (context.mounted) {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: sync, fdb: fdb, row: r)));
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
]);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// The editor as a bottom sheet; → the saved food's id (null = cancelled / deleted).
|
||||
Future<String?> openFoodEditor(BuildContext context, SyncService sync, {Map<String, dynamic>? row, String name = ''}) =>
|
||||
showModalBottomSheet<String>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: card,
|
||||
builder: (_) => FoodEditor(sync: sync, row: row, name: name),
|
||||
);
|
||||
|
||||
class FoodEditor extends StatefulWidget {
|
||||
const FoodEditor({super.key, required this.sync, this.row, this.name = ''});
|
||||
final SyncService sync;
|
||||
final Map<String, dynamic>? row;
|
||||
final String name;
|
||||
@override
|
||||
State<FoodEditor> createState() => _FoodEditorState();
|
||||
}
|
||||
|
||||
class _FoodEditorState extends State<FoodEditor> {
|
||||
late final name = TextEditingController(text: widget.row?['name'] as String? ?? widget.name);
|
||||
late final note = TextEditingController(text: widget.row?['note'] as String? ?? '');
|
||||
late String sugarKind = widget.row?['sugar_kind'] as String? ?? ''; // '' = estimated (sugar.dart)
|
||||
late final values = {
|
||||
for (final k in foodFields.keys)
|
||||
k: TextEditingController(text: widget.row?[k] == null ? '' : num1((widget.row![k] as num).toDouble()))
|
||||
};
|
||||
late final portions = [
|
||||
for (final p in (jsonDecode((widget.row?['portions'] as String?) ?? '[]') as List).cast<Map<String, dynamic>>())
|
||||
(TextEditingController(text: p['label'] as String), TextEditingController(text: num1((p['grams'] as num).toDouble())))
|
||||
];
|
||||
String? error;
|
||||
bool armed = false;
|
||||
|
||||
bool get isMeal => widget.row?['recipe'] != null;
|
||||
|
||||
double? _n(TextEditingController c) => double.tryParse(c.text.trim().replaceAll(',', '.'));
|
||||
|
||||
void _save() {
|
||||
final ps = <Portion>[];
|
||||
for (final (l, g) in portions) {
|
||||
if (l.text.trim().isEmpty && g.text.trim().isEmpty) continue;
|
||||
ps.add(Portion(l.text, _n(g) ?? 0));
|
||||
}
|
||||
final (uid, err) = saveMyFood(widget.sync.store, uid: widget.row?['_u'] as String?, name: name.text,
|
||||
per100: isMeal ? {for (final k in foodFields.keys) k: (widget.row![k] as num?)?.toDouble()} : {for (final e in values.entries) e.key: _n(e.value)},
|
||||
portions: ps, note: note.text, sugarKind: sugarKind);
|
||||
if (err != null) return setState(() => error = err);
|
||||
widget.sync.changed();
|
||||
Navigator.pop(context, uid);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 16, 16, 12 + MediaQuery.of(context).viewInsets.bottom),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Text(widget.row == null ? 'New food' : isMeal ? 'Meal' : 'Edit food',
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||||
TextField(controller: name, autofocus: widget.row == null && widget.name.isEmpty,
|
||||
decoration: const InputDecoration(labelText: 'Name')),
|
||||
const SizedBox(height: 10),
|
||||
Text(isMeal ? 'Per 100 g — from its ingredients (change them with the meal builder)' : 'Per 100 g (from the label)',
|
||||
style: const TextStyle(color: muted, fontSize: 13)),
|
||||
GridView.count(
|
||||
crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
|
||||
crossAxisSpacing: 12, childAspectRatio: 3.2,
|
||||
children: [
|
||||
for (final e in foodFields.entries)
|
||||
TextField(
|
||||
controller: values[e.key],
|
||||
enabled: !isMeal,
|
||||
autofocus: widget.row == null && widget.name.isNotEmpty && e.key == 'kcal',
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
textInputAction: TextInputAction.next,
|
||||
decoration: InputDecoration(labelText: e.value.$1, suffixText: e.value.$2),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Row(children: [
|
||||
const Expanded(child: Text('Portions', style: TextStyle(color: muted, fontSize: 13))),
|
||||
TextButton.icon(
|
||||
onPressed: () => setState(() => portions.add((TextEditingController(), TextEditingController()))),
|
||||
icon: const Icon(Icons.add, size: 18), label: const Text('Portion'),
|
||||
),
|
||||
]),
|
||||
for (var i = 0; i < portions.length; i++)
|
||||
Row(children: [
|
||||
Expanded(flex: 3, child: TextField(controller: portions[i].$1,
|
||||
decoration: const InputDecoration(hintText: 'slice, pot, bowl…', isDense: true))),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(flex: 2, child: TextField(controller: portions[i].$2,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
decoration: const InputDecoration(suffixText: 'g', isDense: true))),
|
||||
IconButton(onPressed: () => setState(() => portions.removeAt(i)), icon: const Icon(Icons.close, size: 18, color: muted)),
|
||||
]),
|
||||
TextField(controller: note, decoration: const InputDecoration(labelText: 'Note')),
|
||||
// when the added-sugar estimate gets this one wrong (homemade jam, unsweetened yogurt …)
|
||||
Row(children: [
|
||||
const Expanded(child: Text('Sugar counts as', style: TextStyle(color: muted))),
|
||||
DropdownButton<String>(
|
||||
value: sugarKind,
|
||||
underline: const SizedBox(),
|
||||
dropdownColor: card2,
|
||||
items: const [
|
||||
DropdownMenuItem(value: '', child: Text('estimated')),
|
||||
DropdownMenuItem(value: 'added', child: Text('all added')),
|
||||
DropdownMenuItem(value: 'dairy', child: Text('milk\'s own, beyond it added')),
|
||||
DropdownMenuItem(value: 'natural', child: Text('natural (none added)')),
|
||||
],
|
||||
onChanged: (v) => setState(() => sugarKind = v ?? ''),
|
||||
),
|
||||
]),
|
||||
if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))),
|
||||
const SizedBox(height: 10),
|
||||
Row(children: [
|
||||
if (widget.row != null)
|
||||
TextButton.icon(
|
||||
icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad),
|
||||
style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null),
|
||||
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)),
|
||||
onPressed: () {
|
||||
if (!armed) return setState(() => armed = true);
|
||||
deleteMyFood(widget.sync.store, widget.row!['_u'] as String);
|
||||
widget.sync.changed();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
const Spacer(),
|
||||
FilledButton(onPressed: _save, child: const Text('Save')),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
120
app/lib/health/overview_page.dart
Normal file
120
app/lib/health/overview_page.dart
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
// Health ▸ Overview: today at a glance — the food eaten today (the Food page's day card), last night's
|
||||
// sleep (Sleep's night card, or that it isn't in yet), then steps today | the next period. Each part's
|
||||
// heading opens its page.
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import 'activity_page.dart' show thousands;
|
||||
import 'cycle_model.dart' show CycleSettings, CycleView, Status, iso, parseDay, plus, today;
|
||||
import 'cycle_page.dart' show cycleStatus;
|
||||
import 'food_model.dart' show FoodDb;
|
||||
import 'food_page.dart' show FoodDayCard;
|
||||
import 'body_page.dart' show dm;
|
||||
import 'sleep_page.dart' show Night, NightCard;
|
||||
import 'summaries.dart';
|
||||
|
||||
class OverviewPage extends StatefulWidget {
|
||||
const OverviewPage({super.key, required this.sync, required this.onFood});
|
||||
final SyncService sync;
|
||||
final VoidCallback onFood; // → the Food section
|
||||
@override
|
||||
State<OverviewPage> createState() => _OverviewPageState();
|
||||
}
|
||||
|
||||
class _OverviewPageState extends State<OverviewPage> {
|
||||
FoodDb? fdb;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
FoodDb.open().then((x) => mounted ? setState(() => fdb = x) : null);
|
||||
}
|
||||
|
||||
void _tab(String name) {
|
||||
const tabs = ['Overview', 'Cycle', 'Body', 'Sleep', 'Heart', 'Activity'];
|
||||
DefaultTabController.of(context).animateTo(tabs.indexOf(name));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: widget.sync,
|
||||
builder: (context, _) {
|
||||
final sm = Summaries(widget.sync.store);
|
||||
final now = today();
|
||||
final nights = [for (final x in sm.all('night', a: iso(plus(now, -400)))) Night(parseDay(x['_day'] as String), x)];
|
||||
final goal = (((sm.meta('sleep') ?? {})['goal'] as num?) ?? 8).toDouble();
|
||||
final last = nights.isNotEmpty && nights.last.day == now;
|
||||
final steps = sm.day(iso(now))?['steps'] as num?;
|
||||
final week = [for (var k = 1; k <= 7; k++) sm.day(iso(plus(now, -k)))?['steps'] as num?].whereType<num>().toList();
|
||||
final cv = CycleView(widget.sync.store, const CycleSettings());
|
||||
var (head, sub) = cycleStatus(cv);
|
||||
if (cv.status == Status.wait) head = cv.daysToNext == 0 ? 'today' : 'in ${cv.daysToNext} ${cv.daysToNext == 1 ? 'day' : 'days'}';
|
||||
if (cv.status == Status.period) head = 'day ${cv.cycleDay}';
|
||||
final wide = MediaQuery.of(context).size.width >= 700;
|
||||
|
||||
final food = Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
_heading('Food today', widget.onFood),
|
||||
FoodDayCard(sync: widget.sync, day: now, fdb: fdb),
|
||||
]);
|
||||
final sleep = Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
_heading('Sleep', () => _tab('Sleep')),
|
||||
if (last)
|
||||
NightCard(all: nights, i: nights.length - 1, goal: goal)
|
||||
else
|
||||
Card(child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
'Last night isn\'t logged yet${nights.isEmpty ? '' : ' — the latest is the night to ${dm(nights.last.day)}'}. '
|
||||
'It comes from the band once Gadgetbridge has exported and the dashboard has synced.',
|
||||
style: const TextStyle(color: muted)),
|
||||
)),
|
||||
]);
|
||||
final tiles = Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Expanded(child: _tile('Steps today', steps == null ? '—' : thousands(steps),
|
||||
week.isEmpty ? 'nothing from the band yet' : 'last 7 days: ${thousands(week.reduce((a, b) => a + b) / week.length)} a day',
|
||||
() => _tab('Activity'))),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(child: _tile(cv.status == Status.period ? 'Period' : 'Next period', head, sub, () => _tab('Cycle'),
|
||||
color: cv.status == Status.late ? bad : cv.status == Status.period ? const Color(0xFFFF6B7A) : null)),
|
||||
]);
|
||||
return ListView(padding: const EdgeInsets.fromLTRB(12, 4, 12, 24), children: [
|
||||
if (wide)
|
||||
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Expanded(child: food),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Column(children: [sleep, const SizedBox(height: 12), tiles])),
|
||||
])
|
||||
else ...[food, const SizedBox(height: 4), sleep, const SizedBox(height: 12), tiles],
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
Widget _heading(String title, VoidCallback go) => InkWell(
|
||||
onTap: go,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),
|
||||
child: Row(children: [
|
||||
Text(title, style: const TextStyle(color: muted, fontSize: 13, fontWeight: FontWeight.bold, letterSpacing: .5)),
|
||||
const Icon(Icons.chevron_right, size: 18, color: muted),
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _tile(String label, String value, String sub, VoidCallback go, {Color? color}) => Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: go,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||||
const SizedBox(height: 2),
|
||||
Text(value, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: color)),
|
||||
const SizedBox(height: 2),
|
||||
Text(sub, style: const TextStyle(color: muted, fontSize: 12)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
27
app/lib/health/range.dart
Normal file
27
app/lib/health/range.dart
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// The one time period every Health chart shows (as the web pages' shared range): 1 day … all.
|
||||
// Any chart's corner chip changes it for all of them; kept on this phone (store meta, not synced).
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../sync/store.dart';
|
||||
import 'cycle_model.dart' show plus;
|
||||
|
||||
const ranges = [('1d', '1 day', 1), ('1w', '1 week', 7), ('1m', '1 month', 30), ('3m', '3 months', 91),
|
||||
('1y', '1 year', 365), ('all', 'All', 0)];
|
||||
|
||||
class HealthRange extends ValueNotifier<String> {
|
||||
HealthRange(this._store) : super(ranges[(_store.meta('ui_range') == 0 ? 2 : _store.meta('ui_range')) - 1].$1);
|
||||
final SyncStore _store;
|
||||
|
||||
String get label => ranges.firstWhere((r) => r.$1 == value).$2;
|
||||
|
||||
void set(String key) {
|
||||
value = key;
|
||||
_store.setMeta('ui_range', ranges.indexWhere((r) => r.$1 == key) + 1); // 0 = never set → 1 week
|
||||
}
|
||||
|
||||
/// The first day shown: [days] back including today, or (All) the data's first day.
|
||||
DateTime from(DateTime first, DateTime now) {
|
||||
final days = ranges.firstWhere((r) => r.$1 == value).$3;
|
||||
return days == 0 ? first : plus(now, -(days - 1));
|
||||
}
|
||||
}
|
||||
620
app/lib/health/sleep_page.dart
Normal file
620
app/lib/health/sleep_page.dart
Normal file
|
|
@ -0,0 +1,620 @@
|
|||
// Health ▸ Sleep (as on the web page's Sleep tab), from the Pi's summaries: one night on top (score ring —
|
||||
// breakdown on tap —, numbers, the hypnogram; ‹ › or a bar below picks another), then over the shared
|
||||
// period: tiles, stages per night (stacked, goal line), bedtime → wake-up, score per night, What stands
|
||||
// out (the Pi's watch.findings) and by weekday. Per week from 4 months: the average night.
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../app/sync_service.dart';
|
||||
import '../app/theme.dart';
|
||||
import '../widgets/bar_chart.dart' show weeklyFrom;
|
||||
import '../widgets/line_chart.dart';
|
||||
import 'activity_page.dart' show hm;
|
||||
import 'body_page.dart' show dm;
|
||||
import 'cycle_model.dart' show daysBetween, parseDay, plus, today;
|
||||
import 'range.dart';
|
||||
import 'summaries.dart';
|
||||
|
||||
const stages = ['deep', 'light', 'rem', 'asleep', 'awake', 'nap']; // stacking order, bottom up (watch.STAGES)
|
||||
const stageNames = {'deep': 'Deep', 'light': 'Light', 'rem': 'REM', 'asleep': 'Asleep (no stage)', 'awake': 'Awake', 'nap': 'Nap'};
|
||||
const stageColors = {
|
||||
'deep': Color(0xFF4F6BED), 'light': Color(0xFF5CC8FF), 'rem': Color(0xFFC792EA),
|
||||
'asleep': Color(0xFF7A8399), 'awake': Color(0xFFFFB33A), 'nap': Color(0xFFFF8FC8),
|
||||
};
|
||||
const _scoreC = Color(0xFF4F6BED);
|
||||
const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||||
const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
|
||||
/// watch._from_noon: hours since the noon before (21:00 → 9, 07:00 → 19)
|
||||
double fromNoon(DateTime t) {
|
||||
final h = t.hour + t.minute / 60;
|
||||
return h >= 12 ? h - 12 : h + 12;
|
||||
}
|
||||
|
||||
/// watch._wake: wake-up as hours from the noon before the night began (07:00 → 19, 13:00 → 25)
|
||||
double wakeH(DateTime start, DateTime end) {
|
||||
final s = DateTime(start.year, start.month, start.day, 12);
|
||||
final noon = start.hour >= 12 ? s : s.subtract(const Duration(days: 1));
|
||||
return end.difference(noon).inMinutes / 60;
|
||||
}
|
||||
|
||||
/// watch.clock: hours since noon → "HH:MM"
|
||||
String clock(double h) {
|
||||
final m = ((h + 12) * 60).round() % (24 * 60);
|
||||
return '${(m ~/ 60).toString().padLeft(2, '0')}:${(m % 60).toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
String _t(DateTime d) => d.toIso8601String().substring(11, 16);
|
||||
|
||||
class Night {
|
||||
Night(this.day, this.m) : start = DateTime.parse(m['start'] as String), end = DateTime.parse(m['end'] as String);
|
||||
final DateTime day; // the wake-up day
|
||||
final Map<String, dynamic> m;
|
||||
final DateTime start, end;
|
||||
num n(String k) => (m[k] as num?) ?? 0;
|
||||
double get asleep => n('asleep').toDouble();
|
||||
int get score => n('score').round();
|
||||
double? get deepPct => (m['deep_pct'] as num?)?.toDouble();
|
||||
double get bed => fromNoon(start);
|
||||
double get up => wakeH(start, end);
|
||||
Map<String, double> get parts => {
|
||||
'deep': n('deep').toDouble(), 'light': n('light').toDouble(), 'rem': n('rem').toDouble(),
|
||||
'asleep': n('unstaged').toDouble(), 'awake': n('awake').toDouble(),
|
||||
};
|
||||
}
|
||||
|
||||
class SleepPage extends StatefulWidget {
|
||||
const SleepPage({super.key, required this.sync, required this.range});
|
||||
final SyncService sync;
|
||||
final HealthRange range;
|
||||
@override
|
||||
State<SleepPage> createState() => _SleepPageState();
|
||||
}
|
||||
|
||||
class _SleepPageState extends State<SleepPage> {
|
||||
DateTime? picked; // the night shown on top (null = the last)
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.sync, widget.range]),
|
||||
builder: (context, _) {
|
||||
final sm = Summaries(widget.sync.store);
|
||||
final all = [for (final x in sm.all('night')) Night(parseDay(x['_day'] as String), x)];
|
||||
if (all.isEmpty) {
|
||||
return const Center(child: Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Text('No nights from the band yet — they come from the dashboard once it has synced.',
|
||||
textAlign: TextAlign.center, style: TextStyle(color: muted)),
|
||||
));
|
||||
}
|
||||
final meta = sm.meta('sleep') ?? {};
|
||||
final goal = ((meta['goal'] as num?) ?? 8).toDouble();
|
||||
final now = today();
|
||||
final a = widget.range.from(all.first.day, now);
|
||||
final ns = all.where((n) => !n.day.isBefore(a)).toList();
|
||||
final naps = <DateTime, double>{
|
||||
for (final d in sm.all('day', a: _iso(a)))
|
||||
if ((d['naps'] as List?)?.isNotEmpty ?? false)
|
||||
parseDay(d['_day'] as String): (d['naps'] as List).fold<double>(0, (s, p) => s + ((p as Map)['minutes'] as num))
|
||||
};
|
||||
var i = picked == null ? all.length - 1 : all.indexWhere((n) => n.day == picked);
|
||||
if (i < 0) i = all.length - 1;
|
||||
double? avg(Iterable<double?> xs) {
|
||||
final v = xs.whereType<double>().toList();
|
||||
return v.isEmpty ? null : v.reduce((p, q) => p + q) / v.length;
|
||||
}
|
||||
|
||||
final found = ((meta['findings'] as Map?)?[widget.range.value] as List?) ?? const [];
|
||||
final wide = MediaQuery.of(context).size.width >= 700;
|
||||
void pick(DateTime d) => setState(() => picked = d);
|
||||
|
||||
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
|
||||
NightCard(all: all, i: i, goal: goal, onPick: (d) => setState(() => picked = d)),
|
||||
const SizedBox(height: 12),
|
||||
GridView.count(
|
||||
crossAxisCount: wide ? 4 : 2,
|
||||
shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
|
||||
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.75,
|
||||
children: [
|
||||
_tile('Asleep', hm(avg(ns.map((n) => n.asleep))), 'a night · goal ${goal.toStringAsFixed(goal % 1 == 0 ? 0 : 1)} h',
|
||||
'The average night of the ${ns.length} in this period'),
|
||||
_tile('Score', avg(ns.map((n) => n.score.toDouble()))?.round().toString() ?? '—', 'of 100, on average',
|
||||
'Our own 0–100: duration 50, deep sleep 20, efficiency 15, interruptions 15'),
|
||||
_tile('Deep', '${avg(ns.map((n) => n.deepPct))?.round() ?? '—'} %', 'of sleep · typical 13–23 %',
|
||||
'Deep sleep as a share of the staged sleep'),
|
||||
_tile('Bed → up', ns.isEmpty ? '—' : '${clock(avg(ns.map((n) => n.bed))!)}–${clock(avg(ns.map((n) => n.up))!)}', 'on average',
|
||||
'Average bedtime and wake-up time'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_card('Stages per night', 'Hours of each stage a night (pink = naps that day), the dashed line = your goal. '
|
||||
'Tap a night to show it on top.',
|
||||
_Stacked(nights: ns, naps: naps, from: a, to: now, goal: goal, range: widget.range, onPick: pick)),
|
||||
const SizedBox(height: 12),
|
||||
_card('Bedtime → wake-up', 'Each night from going to bed to getting up (evening on top); red = under 7 h asleep.',
|
||||
_Window(nights: ns, from: a, to: now, onPick: pick)),
|
||||
const SizedBox(height: 12),
|
||||
_card('Score per night', 'Our sleep score, 0–100',
|
||||
LineChart(from: a, to: now, decimals: 0, limits: (0, 100), series: [
|
||||
Series('Score', [for (final n in ns) (n.day, n.score.toDouble())], _scoreC),
|
||||
])),
|
||||
if (found.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Card(child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
const Text('What stands out', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
|
||||
for (final f in found)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 10),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text((f as List)[0] as String, style: const TextStyle(color: accent, fontWeight: FontWeight.bold)),
|
||||
Text(f[1] as String, style: const TextStyle(height: 1.35)),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)),
|
||||
],
|
||||
if (ns.length >= 7) ...[const SizedBox(height: 12), _weekdayCard(ns)],
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
Widget _weekdayCard(List<Night> ns) {
|
||||
final by = <int, List<Night>>{};
|
||||
for (final n in ns) {
|
||||
by.putIfAbsent(plus(n.day, -1).weekday - 1, () => []).add(n); // the evening you went to bed
|
||||
}
|
||||
double? av(List<Night> xs, double Function(Night) f) => xs.isEmpty ? null : xs.map(f).reduce((p, q) => p + q) / xs.length;
|
||||
final top = [for (var i = 0; i < 7; i++) av(by[i] ?? [], (n) => n.asleep) ?? 0].reduce(max);
|
||||
return _card('By weekday', 'The night after each weekday evening: average asleep, bedtime and score', Column(children: [
|
||||
for (var i = 0; i < 7; i++)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(children: [
|
||||
SizedBox(width: 38, child: Text(_weekdays[i])),
|
||||
Expanded(child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
child: LinearProgressIndicator(value: top == 0 ? 0 : (av(by[i] ?? [], (n) => n.asleep) ?? 0) / top,
|
||||
minHeight: 8, color: stageColors['light'], backgroundColor: card2),
|
||||
)),
|
||||
SizedBox(width: 150, child: Text(
|
||||
by[i] == null ? '—' : '${hm(av(by[i]!, (n) => n.asleep))} · ${clock(av(by[i]!, (n) => n.bed)!)} · ${av(by[i]!, (n) => n.score.toDouble())!.round()}',
|
||||
textAlign: TextAlign.right, style: const TextStyle(fontSize: 12.5))),
|
||||
]),
|
||||
),
|
||||
]));
|
||||
}
|
||||
|
||||
Widget _tile(String label, String value, String sub, String tip) => Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
showDuration: const Duration(seconds: 6),
|
||||
message: tip,
|
||||
child: Card(child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||||
FittedBox(fit: BoxFit.scaleDown, child: Text(value, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold))),
|
||||
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)),
|
||||
]),
|
||||
)),
|
||||
);
|
||||
|
||||
Widget _card(String title, String tip, Widget child) => Card(child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 8, 10, 10),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||||
Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
showDuration: const Duration(seconds: 8),
|
||||
message: tip,
|
||||
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
|
||||
),
|
||||
]),
|
||||
child,
|
||||
]),
|
||||
));
|
||||
}
|
||||
|
||||
/// One night: ‹ › (with [onPick]), score ring (breakdown on tap), numbers, the hypnogram — Sleep's top card,
|
||||
/// also on Health ▸ Overview (last night, no arrows).
|
||||
class NightCard extends StatelessWidget {
|
||||
const NightCard({super.key, required this.all, required this.i, required this.goal, this.onPick});
|
||||
final List<Night> all;
|
||||
final int i;
|
||||
final double goal;
|
||||
final void Function(DateTime)? onPick;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final n = all[i];
|
||||
final p = (n.m['parts'] as Map?)?.cast<String, dynamic>() ?? {};
|
||||
const maxOf = {'Duration': 50, 'Deep sleep': 20, 'Efficiency': 15, 'Interruptions': 15};
|
||||
final stats = [
|
||||
('Asleep', hm(n.asleep)),
|
||||
('In bed', '${_t(n.start)}–${_t(n.end)}'),
|
||||
('Deep', n.deepPct == null ? '—' : '${hm(n.n('deep'))} · ${n.deepPct!.round()} %'),
|
||||
('Light', n.n('light') > 0 ? hm(n.n('light')) : '—'),
|
||||
('Awake', '${hm(n.n('awake'))} · ${n.n('wakeups')}×'),
|
||||
('Efficiency', '${(n.n('eff') * 100).round()} %'),
|
||||
];
|
||||
final night = '${dm(plus(n.day, -1))} → ${dm(n.day)}${n.day.year != today().year ? ' ${n.day.year}' : ''}';
|
||||
return Card(child: Padding(
|
||||
padding: EdgeInsets.fromLTRB(6, onPick == null ? 14 : 6, 6, 12),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
if (onPick != null) IconButton(onPressed: i > 0 ? () => onPick!(all[i - 1].day) : null, icon: const Icon(Icons.chevron_left)),
|
||||
Expanded(child: Text(i == all.length - 1 && n.day == today() ? 'Last night · $night' : night,
|
||||
textAlign: TextAlign.center, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: accent))),
|
||||
if (onPick != null) IconButton(onPressed: i < all.length - 1 ? () => onPick!(all[i + 1].day) : null, icon: const Icon(Icons.chevron_right)),
|
||||
]),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Row(children: [
|
||||
Tooltip(
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
showDuration: const Duration(seconds: 10),
|
||||
message: 'Sleep score ${n.score} / 100\n'
|
||||
'${maxOf.entries.map((e) => '${e.key}: ${p[e.key] ?? '—'} / ${e.value}').join('\n')}\n'
|
||||
'Duration: full at ${(min(goal, 8) - 0.5).toStringAsFixed(1)} h+; deep: full at 20 %;\n'
|
||||
'efficiency: asleep ÷ in bed, full at 95 %; interruptions: −4 per wake-up.',
|
||||
child: SizedBox(
|
||||
width: 82, height: 82,
|
||||
child: CustomPaint(
|
||||
painter: _ScoreRing(n.score / 100),
|
||||
child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text('${n.score}', style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold, height: 1)),
|
||||
const Text('score', style: TextStyle(color: muted, fontSize: 12)),
|
||||
])),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(child: Wrap(runSpacing: 8, children: [
|
||||
for (final (l, v) in stats)
|
||||
SizedBox(width: 120, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(l.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11)),
|
||||
Text(v, style: const TextStyle(fontWeight: FontWeight.bold)),
|
||||
])),
|
||||
])),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
if ((n.m['stages'] as List?)?.isNotEmpty ?? false)
|
||||
Padding(padding: const EdgeInsets.symmetric(horizontal: 8), child: _Hypnogram(night: n))
|
||||
else
|
||||
const Padding(padding: EdgeInsets.all(8), child: Text('No stages recorded for this night', style: TextStyle(color: muted))),
|
||||
]),
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
String _iso(DateTime d) => d.toIso8601String().substring(0, 10);
|
||||
|
||||
class _ScoreRing extends CustomPainter {
|
||||
_ScoreRing(this.f);
|
||||
final double f;
|
||||
@override
|
||||
void paint(Canvas c, Size s) {
|
||||
final r = Rect.fromCircle(center: s.center(Offset.zero), radius: s.width / 2 - 4);
|
||||
Paint p(Color col) => Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = 6..strokeCap = StrokeCap.round;
|
||||
c.drawArc(r, 0, 2 * pi, false, p(card2));
|
||||
if (f > 0) c.drawArc(r, -pi / 2, 2 * pi * f.clamp(0, 1), false, p(_scoreC));
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _ScoreRing old) => old.f != f;
|
||||
}
|
||||
|
||||
/// One night's stages: lanes awake / REM / light / deep, a block per run (watch.hypnogram); tap = that run.
|
||||
class _Hypnogram extends StatefulWidget {
|
||||
const _Hypnogram({required this.night});
|
||||
final Night night;
|
||||
@override
|
||||
State<_Hypnogram> createState() => _HypnogramState();
|
||||
}
|
||||
|
||||
class _HypnogramState extends State<_Hypnogram> {
|
||||
int? hit;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _Hypnogram old) {
|
||||
super.didUpdateWidget(old);
|
||||
if (old.night.day != widget.night.day) hit = null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final runs = (widget.night.m['stages'] as List).cast<List>();
|
||||
final n = widget.night;
|
||||
final h = hit == null ? null : runs[hit!];
|
||||
String at(num min) => _t(n.start.add(Duration(seconds: (min * 60).round())));
|
||||
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
LayoutBuilder(builder: (context, box) {
|
||||
final painter = _HypPainter(n, runs, hit);
|
||||
return GestureDetector(
|
||||
onTapDown: (d) {
|
||||
final m = painter.minuteAt(d.localPosition.dx, box.maxWidth);
|
||||
final j = runs.indexWhere((r) => (r[0] as num) <= m && m <= (r[1] as num));
|
||||
setState(() => hit = j < 0 ? null : j);
|
||||
},
|
||||
child: CustomPaint(size: Size(box.maxWidth, 140), painter: painter),
|
||||
);
|
||||
}),
|
||||
SizedBox(
|
||||
height: 20,
|
||||
child: Text(
|
||||
h == null
|
||||
? 'Tap a block for its times'
|
||||
: '${stageNames[h[2]] ?? h[2]} · ${at(h[0] as num)} – ${at(h[1] as num)} · ${hm((h[1] as num) - (h[0] as num))}',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: h == null ? muted : Colors.white, fontSize: 12.5)),
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
class _HypPainter extends CustomPainter {
|
||||
_HypPainter(this.n, this.runs, this.hit);
|
||||
final Night n;
|
||||
final List<List> runs;
|
||||
final int? hit;
|
||||
static const ml = 46.0, mb = 18.0, pad = 15.0; // minutes either side (as the web's)
|
||||
|
||||
double get total => n.end.difference(n.start).inMinutes + 2 * pad;
|
||||
double x(num min, double w) => ml + (w - ml) * (min + pad) / total;
|
||||
double minuteAt(double dx, double w) => (dx - ml) / (w - ml) * total - pad;
|
||||
|
||||
@override
|
||||
void paint(Canvas c, Size size) {
|
||||
const lanes = {'awake': 0, 'rem': 1, 'light': 2, 'asleep': 2, 'deep': 3};
|
||||
final lh = (size.height - mb) / 4;
|
||||
final txt = const TextStyle(color: muted, fontSize: 10.5);
|
||||
void label(String s, Offset o, {bool right = false}) {
|
||||
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
|
||||
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
|
||||
}
|
||||
|
||||
for (var i = 0; i < 4; i++) {
|
||||
c.drawLine(Offset(ml, i * lh), Offset(size.width, i * lh), Paint()..color = card2);
|
||||
label(['Awake', 'REM', 'Light', 'Deep'][i], Offset(ml - 6, i * lh + lh / 2), right: true);
|
||||
}
|
||||
for (var i = 0; i < runs.length; i++) {
|
||||
final r = runs[i];
|
||||
final lane = lanes[r[2]] ?? 2;
|
||||
final x0 = x(r[0] as num, size.width), x1 = x(r[1] as num, size.width);
|
||||
c.drawRRect(RRect.fromRectAndRadius(Rect.fromLTRB(x0, lane * lh + 2, max(x0 + 0.8, x1), (lane + 1) * lh - 2), const Radius.circular(2)),
|
||||
Paint()..color = hit == i ? Colors.white : stageColors[r[2]] ?? muted);
|
||||
}
|
||||
// hour ticks (every 2 h for long nights)
|
||||
final a = n.start.subtract(const Duration(minutes: 15)), z = n.end.add(const Duration(minutes: 15));
|
||||
final step = z.difference(a).inHours < 6 ? 1 : 2;
|
||||
for (var t = DateTime(a.year, a.month, a.day, a.hour + 1); t.isBefore(z); t = t.add(const Duration(hours: 1))) {
|
||||
if (t.hour % step == 0) label(_t(t), Offset(x(t.difference(n.start).inMinutes, size.width), size.height - mb + 4));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _HypPainter old) => true;
|
||||
}
|
||||
|
||||
/// Stages per night, stacked (hours), naps on top, the goal dashed; from [weeklyFrom] days the average
|
||||
/// night of each week. Tap = its numbers (and that night on top).
|
||||
class _Stacked extends StatefulWidget {
|
||||
const _Stacked({required this.nights, required this.naps, required this.from, required this.to, required this.goal,
|
||||
required this.range, required this.onPick});
|
||||
final List<Night> nights;
|
||||
final Map<DateTime, double> naps;
|
||||
final DateTime from, to;
|
||||
final double goal;
|
||||
final HealthRange range;
|
||||
final void Function(DateTime) onPick;
|
||||
@override
|
||||
State<_Stacked> createState() => _StackedState();
|
||||
}
|
||||
|
||||
class _StackedState extends State<_Stacked> {
|
||||
String? tip;
|
||||
|
||||
/// [(first day, {stage: minutes} or null, label, the night's day if one)]
|
||||
List<(DateTime, Map<String, double>?, String, DateTime?)> _buckets() {
|
||||
final per = <DateTime, Map<String, double>>{for (final n in widget.nights) n.day: n.parts};
|
||||
widget.naps.forEach((d, m) => (per[d] ??= {})['nap'] = m);
|
||||
final n = daysBetween(widget.from, widget.to) + 1;
|
||||
final out = <(DateTime, Map<String, double>?, String, DateTime?)>[];
|
||||
if (n >= weeklyFrom) {
|
||||
for (var s = plus(widget.from, -(widget.from.weekday - 1)); !s.isAfter(widget.to); s = plus(s, 7)) {
|
||||
final vs = [for (var i = 0; i < 7; i++) per[plus(s, i)]].whereType<Map<String, double>>().toList();
|
||||
out.add((s, vs.isEmpty ? null : {for (final st in stages) st: vs.fold<double>(0, (a, v) => a + (v[st] ?? 0)) / vs.length},
|
||||
'Week of ${s.day} ${_mon[s.month - 1]} · the average night (${vs.length})', null));
|
||||
}
|
||||
} else {
|
||||
for (var i = 0; i < n; i++) {
|
||||
final d = plus(widget.from, i);
|
||||
out.add((d, per[d], 'Night to ${d.day} ${_mon[d.month - 1]}', per.containsKey(d) ? d : null));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final b = _buckets();
|
||||
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Row(children: [
|
||||
Expanded(child: Text(tip ?? 'Tap a night for its numbers',
|
||||
style: TextStyle(color: tip == null ? muted : Colors.white, fontSize: 12.5))),
|
||||
RangeChip(widget.range),
|
||||
]),
|
||||
const SizedBox(height: 6),
|
||||
LayoutBuilder(builder: (context, box) => GestureDetector(
|
||||
onTapDown: (d) {
|
||||
final i = ((d.localPosition.dx - 30) / (box.maxWidth - 30) * b.length).floor().clamp(0, b.length - 1);
|
||||
final (_, v, label, day) = b[i];
|
||||
if (v == null) return setState(() => tip = '$label · nothing');
|
||||
final asleep = ['deep', 'light', 'rem', 'asleep'].fold<double>(0, (s, k) => s + (v[k] ?? 0));
|
||||
setState(() => tip = '$label · asleep ${hm(asleep)}'
|
||||
'${(v['deep'] ?? 0) > 0 ? ', deep ${hm(v['deep'])}' : ''}${(v['nap'] ?? 0) > 0 ? ', nap ${hm(v['nap'])}' : ''}');
|
||||
if (day != null) widget.onPick(day);
|
||||
},
|
||||
child: CustomPaint(size: Size(box.maxWidth, 170), painter: _StackPainter(b, widget.goal)),
|
||||
)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
class _StackPainter extends CustomPainter {
|
||||
_StackPainter(this.b, this.goal);
|
||||
final List<(DateTime, Map<String, double>?, String, DateTime?)> b;
|
||||
final double goal;
|
||||
|
||||
@override
|
||||
void paint(Canvas c, Size size) {
|
||||
const ml = 30.0, mb = 16.0, mt = 4.0;
|
||||
final h = size.height - mb - mt;
|
||||
final peak = max(goal + 1, [for (final x in b) if (x.$2 != null) x.$2!.values.fold<double>(0, (a, v) => a + v) / 60].fold<double>(0, max));
|
||||
final top = (peak / 2).ceil() * 2.0;
|
||||
double y(double hours) => mt + h - h * hours / top;
|
||||
final txt = const TextStyle(color: muted, fontSize: 10.5);
|
||||
void label(String s, Offset o, {bool right = false}) {
|
||||
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
|
||||
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
|
||||
}
|
||||
|
||||
for (var v = 0.0; v <= top; v += top > 10 ? 4 : 2) {
|
||||
c.drawLine(Offset(ml, y(v)), Offset(size.width, y(v)), Paint()..color = card2);
|
||||
label('${v.round()}h', Offset(ml - 4, y(v)), right: true);
|
||||
}
|
||||
final bw = (size.width - ml) / max(1, b.length), pad = bw > 4 ? bw * 0.18 : 0.0;
|
||||
final weekly = b.length > 1 && b[1].$1.difference(b[0].$1).inDays == 7;
|
||||
for (var i = 0; i < b.length; i++) {
|
||||
final (d, v, _, _) = b[i];
|
||||
final x0 = ml + i * bw;
|
||||
if (v != null) {
|
||||
var base = 0.0;
|
||||
for (final st in stages) {
|
||||
final m = (v[st] ?? 0) / 60;
|
||||
if (m > 0) c.drawRect(Rect.fromLTRB(x0 + pad, y(base + m), x0 + bw - pad, y(base)), Paint()..color = stageColors[st]!);
|
||||
base += m;
|
||||
}
|
||||
}
|
||||
final l = weekly
|
||||
? (d.day <= 7 && (b.length <= 30 || d.month % 3 == 1) ? _mon[d.month - 1] : null)
|
||||
: b.length > 35 ? (d.day == 1 ? _mon[d.month - 1] : null) : (d.weekday == 1 || b.length <= 8 ? '${d.day} ${_mon[d.month - 1]}' : null);
|
||||
if (l != null) label(l, Offset(x0 + bw / 2, size.height - mb + 3));
|
||||
}
|
||||
final gy = y(goal);
|
||||
for (var x = ml; x < size.width; x += 8) {
|
||||
c.drawLine(Offset(x, gy), Offset(min(x + 4, size.width), gy), Paint()..color = accent..strokeWidth = 1.2);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _StackPainter old) => true;
|
||||
}
|
||||
|
||||
/// Each night as a bar from bedtime to wake-up (watch.window_chart); weekly: the average night.
|
||||
class _Window extends StatefulWidget {
|
||||
const _Window({required this.nights, required this.from, required this.to, required this.onPick});
|
||||
final List<Night> nights;
|
||||
final DateTime from, to;
|
||||
final void Function(DateTime) onPick;
|
||||
@override
|
||||
State<_Window> createState() => _WindowState();
|
||||
}
|
||||
|
||||
class _WindowState extends State<_Window> {
|
||||
String? tip;
|
||||
|
||||
/// [(first day, bed, up, asleep min, label, night day?)]
|
||||
List<(DateTime, double, double, double, String, DateTime?)> _bars() {
|
||||
final n = daysBetween(widget.from, widget.to) + 1;
|
||||
if (n < weeklyFrom) {
|
||||
return [
|
||||
for (final x in widget.nights)
|
||||
(x.day, x.bed, x.up, x.asleep, 'Night to ${x.day.day} ${_mon[x.day.month - 1]} · ${_t(x.start)} → ${_t(x.end)} · asleep ${hm(x.asleep)}', x.day)
|
||||
];
|
||||
}
|
||||
final wk = <DateTime, List<Night>>{};
|
||||
for (final x in widget.nights) {
|
||||
wk.putIfAbsent(plus(x.day, -(x.day.weekday - 1)), () => []).add(x);
|
||||
}
|
||||
double av(List<Night> xs, double Function(Night) f) => xs.map(f).reduce((p, q) => p + q) / xs.length;
|
||||
return [
|
||||
for (final e in wk.entries)
|
||||
(e.key, av(e.value, (x) => x.bed), av(e.value, (x) => x.up), av(e.value, (x) => x.asleep),
|
||||
'Week of ${e.key.day} ${_mon[e.key.month - 1]} · average of ${e.value.length} · '
|
||||
'${clock(av(e.value, (x) => x.bed))} → ${clock(av(e.value, (x) => x.up))} · asleep ${hm(av(e.value, (x) => x.asleep))}', null)
|
||||
];
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bars = _bars();
|
||||
if (bars.isEmpty) return const SizedBox(height: 40, child: Center(child: Text('No nights in this period', style: TextStyle(color: muted))));
|
||||
final weekly = daysBetween(widget.from, widget.to) + 1 >= weeklyFrom;
|
||||
final slots = weekly ? ((daysBetween(widget.from, widget.to) + 7) ~/ 7 + 1) : daysBetween(widget.from, widget.to) + 1;
|
||||
final a0 = weekly ? plus(widget.from, -(widget.from.weekday - 1)) : widget.from;
|
||||
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Text(tip ?? 'Tap a night for its times', style: TextStyle(color: tip == null ? muted : Colors.white, fontSize: 12.5)),
|
||||
const SizedBox(height: 6),
|
||||
LayoutBuilder(builder: (context, box) => GestureDetector(
|
||||
onTapDown: (d) {
|
||||
final slot = ((d.localPosition.dx - 40) / (box.maxWidth - 40) * slots).floor();
|
||||
final hit = bars.where((x) => (daysBetween(a0, x.$1) ~/ (weekly ? 7 : 1)) == slot).toList();
|
||||
setState(() => tip = hit.isEmpty ? null : hit.first.$5);
|
||||
if (hit.isNotEmpty && hit.first.$6 != null) widget.onPick(hit.first.$6!);
|
||||
},
|
||||
child: CustomPaint(size: Size(box.maxWidth, 180), painter: _WindowPainter(bars, a0, slots, weekly)),
|
||||
)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
class _WindowPainter extends CustomPainter {
|
||||
_WindowPainter(this.bars, this.a0, this.slots, this.weekly);
|
||||
final List<(DateTime, double, double, double, String, DateTime?)> bars;
|
||||
final DateTime a0;
|
||||
final int slots;
|
||||
final bool weekly;
|
||||
|
||||
@override
|
||||
void paint(Canvas c, Size size) {
|
||||
const ml = 40.0, mb = 16.0, mt = 4.0;
|
||||
final top = max(6, bars.map((x) => x.$2).reduce(min).floor() - 1).toDouble();
|
||||
final bot = min(26, bars.map((x) => x.$3).reduce(max).floor() + 2).toDouble();
|
||||
double y(double hh) => mt + (size.height - mt - mb) * (hh.clamp(top, bot) - top) / (bot - top);
|
||||
final txt = const TextStyle(color: muted, fontSize: 10.5);
|
||||
void label(String s, Offset o, {bool right = false}) {
|
||||
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
|
||||
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
|
||||
}
|
||||
|
||||
final step = bot - top > 8 ? 2 : 1;
|
||||
for (var hh = top.toInt(); hh <= bot; hh++) {
|
||||
if (hh % step != 0) continue;
|
||||
c.drawLine(Offset(ml, y(hh.toDouble())), Offset(size.width, y(hh.toDouble())), Paint()..color = card2);
|
||||
label(clock(hh.toDouble()), Offset(ml - 4, y(hh.toDouble())), right: true);
|
||||
}
|
||||
final bw = (size.width - ml) / max(1, slots), pad = bw > 4 ? bw * 0.18 : 0.0;
|
||||
for (final (d, bed, up, asleep, _, _) in bars) {
|
||||
final i = daysBetween(a0, d) ~/ (weekly ? 7 : 1);
|
||||
final x0 = ml + i * bw;
|
||||
c.drawRRect(RRect.fromRectAndRadius(Rect.fromLTRB(x0 + pad, y(bed), x0 + bw - pad, y(up)), const Radius.circular(2)),
|
||||
Paint()..color = asleep < 7 * 60 ? bad : stageColors['light']!);
|
||||
}
|
||||
for (var i = 0; i < slots; i++) {
|
||||
final d = plus(a0, i * (weekly ? 7 : 1));
|
||||
final l = weekly
|
||||
? (d.day <= 7 && (slots <= 30 || d.month % 3 == 1) ? _mon[d.month - 1] : null)
|
||||
: slots > 35 ? (d.day == 1 ? _mon[d.month - 1] : null) : (d.weekday == 1 || slots <= 8 ? '${d.day} ${_mon[d.month - 1]}' : null);
|
||||
if (l != null) label(l, Offset(ml + i * bw + bw / 2, size.height - mb + 3));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _WindowPainter old) => true;
|
||||
}
|
||||
184
app/lib/health/sugar.dart
Normal file
184
app/lib/health/sugar.dart
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
// Added sugar, estimated — a port of the dashboard's plugins/food/sugar.py (keep the word lists and
|
||||
// rules identical): the sugars WHO's limit is about ("free sugars": sugar, honey, syrups added to food,
|
||||
// plus fruit juice), not the sugar inside whole fruit, vegetables and plain milk. Each food gets a kind
|
||||
// from its category / name: added (all its sugar counts), dairy (only beyond the milk's own lactose), natural (none).
|
||||
// Shop products: the label's added-sugar figure, else NOVA 1 / "no added sugar", else their ingredients
|
||||
// (sugarsIn / dairy, off.py) — see sugar.py's top. Names are matched folded (no diacritics, lower case).
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import '../sync/store.dart';
|
||||
import 'food_model.dart';
|
||||
import 'sugar_kinds.g.dart';
|
||||
|
||||
const lactose = 5.0; // g per 100 g of milk / yogurt that is the milk's own sugar
|
||||
|
||||
// lower-cased letters with diacritics → plain ones (sugar.py's FOLD)
|
||||
final _foldMap = <String, String>{
|
||||
for (final (from, to) in [
|
||||
('áàâäãåāăą', 'a'), ('çčć', 'c'), ('ďđ', 'd'), ('éèêëěęē', 'e'), ('íìîïī', 'i'), ('ľĺł', 'l'), ('ňńñ', 'n'),
|
||||
('óòôöõőø', 'o'), ('řŕ', 'r'), ('śšşș', 's'), ('ťţț', 't'), ('úùûüůűū', 'u'), ('ýÿ', 'y'), ('žźż', 'z'),
|
||||
])
|
||||
for (final c in from.split('')) c: to,
|
||||
'ß': 'ss', 'æ': 'ae', 'œ': 'oe',
|
||||
};
|
||||
|
||||
/// 'Zahăr Brun' → 'zahar brun' (what the word lists are matched against).
|
||||
String fold(String s) => s.toLowerCase().split('').map((c) => _foldMap[c] ?? c).join();
|
||||
|
||||
final _added = RegExp(
|
||||
r'juice|nectar(?!ine)|syrup|honey|\bjam\b|jelly|marmalade|candy|candies|chocolate|cocoa|(?<!un)sweetened|frosted|glazed|candied|'
|
||||
r'\bcake|cookie|biscuit|brownie|\bpie\b|pastr|doughnut|donut|croissant|muffin|waffle|pancake|dessert|pudding|'
|
||||
r'ice cream|sorbet|gelatin|soda|soft drink|\bcola\b|lemonade|energy drink|sport drink|sports drink|\bpunch\b|'
|
||||
r'smoothie|milkshake|milk shake|ketchup|bbq|barbecue|sweet and sour|teriyaki|\bsugar\b|sugared|granola|cereal bar|'
|
||||
r'nutrition bar|protein bar|wafer|caramel|toffee|fudge|marzipan|nutella|'
|
||||
r'strudel|tart\b|cheesecake|tiramisu|liqueur|cocktail|flavored|flavoured|vanilla|'
|
||||
r'fruit drink|flavou?r drink|breakfast drink|drink mix|beverage mix|ready.to.drink|carbonated|tonic|ginger ale|limeade|'
|
||||
r'lemonad|sour mix|creme de|pina colada|daiquiri|shake mix|ovaltine|malted|\bbars?\b|treats|sundae|cobbler|'
|
||||
r'cinnamon roll|hotcake|french toast|mcgriddle|coleslaw|banana chips|zwieback|\bcran |'
|
||||
r'schoko|marlenka|sernik|malt loaf|\bbeer|\bbere\b|\bpivo|\bwines?\b|\bcider|\bvin\b|v[ií]no\b|cidru|ciocolat|pr[aă]jitur|\bdulce|zahar|cukor|cukr|'
|
||||
r'zucker|sucre|zucchero|azucar|acucar|cukier|suiker|sirop|sirup|syrop|sciroppo|honig|\bmiere\b|\bmiel\b|\bmiod|\bmedov|'
|
||||
r'chocolat|cioccolat|czekolad|cokolad|csokolad|keks|kuchen|torte\b|\btort\b|\bgateau|biscott|gallet|ciastk|susienk|susenk|'
|
||||
r'oplatk|napolitane\b|\blody\b|zmrzlin|fagylalt|gelato|helado|limonad|saft\b|\bjus\b|succo|\bzumo|\bdzus|\bdzem|'
|
||||
r'konfit|marmelad|kompot|compot|bonbon|bomboan|pralin|lizak|\bsuc\b|\bsucuri',
|
||||
caseSensitive: false, unicode: true);
|
||||
final _dairy = RegExp(
|
||||
r'\bmilk\b|yogh?urt|jogurt|iaurt|kefir|skyr|quark|tvaroh|buttermilk|cottage|ricotta|cream cheese|\bcream\b|'
|
||||
r'lapte|mlieko|sm[aâ]nt[aâ]n[aă]|smotana|br[aâ]nz[aă]|\burda\b|chefir|\bsana\b|'
|
||||
r'\blait\b|milch|\blatte\b|\bleche\b|\bleite\b|\bmlek|\bmlecz|\bmleko|\btej\b|\btejf|\bmelk\b|yaourt|joghurt|'
|
||||
r'yogur|iogurt|fromage blanc|twarog|\bturo\b|\bsahne|creme fraiche|smietan|smetan|\bnata\b|\bpanna\b|kwark',
|
||||
caseSensitive: false, unicode: true);
|
||||
/// The reviewed table's kind for a USDA category (sugar_kinds.g.dart = the dashboard's sugar_kinds.json), or null:
|
||||
/// by the name. [name]: folded.
|
||||
String? categoryKind(String category, String name) {
|
||||
final k = sugarKinds[category.toLowerCase()];
|
||||
if (k == null) return null;
|
||||
final (kind, except) = k;
|
||||
return except != null && RegExp(except).hasMatch(name) ? null : kind;
|
||||
}
|
||||
final _notDairy = RegExp(
|
||||
r'coconut milk|chocolate milk|\b(soy|soya|almond|oat|rice) ?(milk|drink)|(soja|hafer|mandel|reis|kokos)(milch|drink)|'
|
||||
r'lapte (vegetal|de (soia|migdale|ovaz|cocos|orez))|\bvegan\b',
|
||||
caseSensitive: false);
|
||||
final _natural = RegExp(
|
||||
r'(apple|banana|grape|orange|pear|peach|plum|berr|cherr|melon|mango|pineapple|kiwi|\bfig|\bdate|apricot|raisin|'
|
||||
r'tomato|onion|carrot|cabbage|potato|pepper|cucumber|lettuce|salad|spinach|broccoli|bean|pea|lentil|corn|squash|'
|
||||
r'zucchini|pumpkin|beet|garlic|mushroom|rice|oat|bread|pasta|egg|chicken|beef|pork|fish|tuna|salmon|ham|turkey|'
|
||||
r'cheese|nut|almond|walnut|seed|soup|pickle|clementin|mandarin|grepfruit|grapefruit|\bm[aă]r\b|morcov|sfecl|telin|'
|
||||
r'ceap|ro[sș]ii|cartof|varz|legume|borsc?h|\bbor[sș]|ciorb|sup[aă]\b|pizza|goulash|gul[aá][sšș]|\bmici\b|congelat)',
|
||||
caseSensitive: false, unicode: true);
|
||||
final _flavour = RegExp(r'flavou?red|fruit|vanilla|strawberr|banana', caseSensitive: false);
|
||||
final _notFlavourDairy = RegExp(r'chocolate|ice cream|shake', caseSensitive: false);
|
||||
|
||||
/// A food → "added" / "dairy" / "natural" (sugar.kind). sugarsIn / dairy: off.py's columns (null: not known).
|
||||
String sugarKind(String name, {String category = '', String source = '', int? nova, String labels = '', String? sugarsIn, int? dairy}) {
|
||||
name = fold(name);
|
||||
final ck = categoryKind(category, name);
|
||||
final isDairy = ((dairy ?? 0) != 0 || ck == 'dairy' || _dairy.hasMatch(name)) && !_notDairy.hasMatch(name);
|
||||
if (source == 'off') {
|
||||
if (labels.toLowerCase().contains('no added sugar') || nova == 1) return isDairy ? 'dairy' : 'natural';
|
||||
if (sugarsIn != null) return isDairy ? 'dairy' : sugarsIn.isNotEmpty ? 'added' : 'natural'; // its ingredients are known
|
||||
if (isDairy && !_added.hasMatch(name)) return 'dairy';
|
||||
return 'added';
|
||||
}
|
||||
if (ck == 'added' || _added.hasMatch(name)) { // words: the name only ("Fruits and Fruit Juices")
|
||||
return isDairy && _flavour.hasMatch(name) && !_notFlavourDairy.hasMatch(name) ? 'dairy' : 'added';
|
||||
}
|
||||
return isDairy ? 'dairy' : 'natural';
|
||||
}
|
||||
|
||||
double addedPart(String kind, double sugar, double? grams) {
|
||||
if (sugar == 0) return 0;
|
||||
if (kind == 'added') return sugar;
|
||||
if (kind == 'dairy') return max(0, sugar - (grams != null && grams > 0 ? lactose * grams / 100 : sugar));
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool _says(String name) {
|
||||
name = fold(name);
|
||||
return _added.hasMatch(name) || _dairy.hasMatch(name) || _natural.hasMatch(name);
|
||||
}
|
||||
String _byName(String name) => _says(name) ? sugarKind(name) : 'added';
|
||||
|
||||
String foodKind(Food f) => sugarKind(f.name, category: f.category, source: f.kind == 'off' ? 'off' : f.source, nova: f.nova,
|
||||
labels: f.labels, sugarsIn: f.sugarsIn, dairy: f.dairy);
|
||||
|
||||
/// Added sugar (g) of [sugar] g of a foods.db food (sugar.food_part): the label's own figure when it gives one, else by its kind.
|
||||
double foodPart(Food f, double sugar, double? grams) {
|
||||
final s100 = f.per100['sugar'];
|
||||
// "0 added" yet sugar in the ingredients: a crowd-typed 0, not the label
|
||||
final a = f.addedSugar == 0 && (f.sugarsIn ?? '').isNotEmpty ? null : f.addedSugar;
|
||||
if (a != null && s100 != null && s100 > 0) return sugar * min(1.0, a / s100);
|
||||
return addedPart(foodKind(f), sugar, grams);
|
||||
}
|
||||
|
||||
/// Added sugar of entries (sugar.entry_added), the foods they were made from looked up once.
|
||||
class AddedSugar {
|
||||
AddedSugar(this.store, this.fdb);
|
||||
final SyncStore store;
|
||||
final FoodDb? fdb;
|
||||
final _foods = <int, Food?>{};
|
||||
final _mine = <String, Map<String, dynamic>?>{};
|
||||
|
||||
Food? _food(int id) => _foods.putIfAbsent(id, () => fdb?.food(id));
|
||||
Map<String, dynamic>? _my(String uid) => _mine.putIfAbsent(uid, () => store.row('food.food', uid));
|
||||
|
||||
double entry(Entry e) {
|
||||
final sugar = e.n('sugar') ?? 0;
|
||||
if (sugar == 0) return 0;
|
||||
final grams = e.n('grams');
|
||||
if (e.foodId != null) {
|
||||
final f = _food(e.foodId!);
|
||||
if (f != null) return foodPart(f, sugar, grams);
|
||||
}
|
||||
if (e.myFoodId != null) {
|
||||
final m = _my(e.myFoodId!);
|
||||
if (m != null) return _myAdded(m, sugar, grams, 0);
|
||||
}
|
||||
return addedPart(_byName(e.name), sugar, grams);
|
||||
}
|
||||
|
||||
double _myAdded(Map<String, dynamic> m, double sugar, double? grams, int depth) {
|
||||
final set = m['sugar_kind']; // "Sugar counts as" (My foods): as set, whatever the estimate says
|
||||
if (set is String && const ['added', 'dairy', 'natural'].contains(set)) return addedPart(set, sugar, grams);
|
||||
final recipe = m['recipe'] is String ? jsonDecode(m['recipe'] as String) as Map<String, dynamic>? : null;
|
||||
final ings = (recipe?['ingredients'] as List?)?.cast<Map<String, dynamic>>();
|
||||
if (ings != null && ings.isNotEmpty) {
|
||||
var totSugar = 0.0, totAdded = 0.0;
|
||||
for (final ing in ings) {
|
||||
final ref = (ing['food'] as String?) ?? '';
|
||||
final g = (ing['grams'] as num?)?.toDouble();
|
||||
if (ref.startsWith('usda:') && g != null) {
|
||||
final f = _food(int.parse(ref.substring(5)));
|
||||
if (f != null) {
|
||||
final s = (f.per100['sugar'] ?? 0) * g / 100;
|
||||
totSugar += s;
|
||||
totAdded += foodPart(f, s, g);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (ref.startsWith('my:') && g != null && depth < 4) {
|
||||
final sub = _my(ref.substring(3).replaceFirst('~', '')); // synced refs are "my:~<id>"
|
||||
if (sub != null) {
|
||||
final s = ((sub['sugar'] as num?)?.toDouble() ?? 0) * g / 100;
|
||||
totSugar += s;
|
||||
totAdded += _myAdded(sub, s, g, depth + 1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
final s = (ing['sugar'] as num?)?.toDouble() ?? 0; // a fixed ingredient: its own numbers
|
||||
if (s > 0) {
|
||||
totSugar += s;
|
||||
totAdded += addedPart(_byName((ing['name'] as String?) ?? ''), s, g);
|
||||
}
|
||||
}
|
||||
return totSugar > 0 ? sugar * totAdded / totSugar : 0;
|
||||
}
|
||||
final base = (m['based_on'] as num?)?.toInt();
|
||||
if (base != null) {
|
||||
final f = _food(base);
|
||||
if (f != null) return foodPart(f, sugar, grams);
|
||||
}
|
||||
return addedPart(_byName((m['name'] as String?) ?? ''), sugar, grams);
|
||||
}
|
||||
}
|
||||
56
app/lib/health/sugar_kinds.g.dart
Normal file
56
app/lib/health/sugar_kinds.g.dart
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// GENERATED from the dashboard's plugins/food/sugar_kinds.json by `python3 plugins/food/sugar.py --dart <this file>`
|
||||
// — don't edit; change the table and run it again. USDA category (lower case) → (kind, names going by their name).
|
||||
const sugarKinds = <String, (String, String?)>{
|
||||
r'apple juice': (r'added', null),
|
||||
r'baby food: snacks and sweets': (r'added', null),
|
||||
r'baby juice': (r'added', null),
|
||||
r'baked products': (r'added', null),
|
||||
r'biscuits, muffins, quick breads': (r'added', null),
|
||||
r'breakfast cereals': (r'added', r'\bplain\b|grits|farina|regular and quick|unsweetened'),
|
||||
r'cakes and pies': (r'added', null),
|
||||
r'candy containing chocolate': (r'added', null),
|
||||
r'candy not containing chocolate': (r'added', null),
|
||||
r'cereal bars': (r'added', null),
|
||||
r'cheese': (r'dairy', null),
|
||||
r'cheese sandwiches': (r'dairy', null),
|
||||
r'citrus juice': (r'added', null),
|
||||
r'cookies and brownies': (r'added', null),
|
||||
r'cottage/ricotta cheese': (r'dairy', null),
|
||||
r'cream and cream substitutes': (r'dairy', null),
|
||||
r'cream cheese, sour cream, whipped cream': (r'dairy', null),
|
||||
r'dairy and egg products': (r'dairy', null),
|
||||
r'doughnuts, sweet rolls, pastries': (r'added', null),
|
||||
r'flavored milk, lowfat': (r'added', null),
|
||||
r'flavored milk, nonfat': (r'added', null),
|
||||
r'flavored milk, reduced fat': (r'added', null),
|
||||
r'flavored milk, whole': (r'added', null),
|
||||
r'fruit drinks': (r'added', null),
|
||||
r'gelatins, ices, sorbets': (r'added', null),
|
||||
r'ice cream and frozen dairy desserts': (r'added', null),
|
||||
r'jams, syrups, toppings': (r'added', null),
|
||||
r'liquor and cocktails': (r'added', null),
|
||||
r'milk shakes and other dairy drinks': (r'added', null),
|
||||
r'milk, lowfat': (r'dairy', null),
|
||||
r'milk, nonfat': (r'dairy', null),
|
||||
r'milk, reduced fat': (r'dairy', null),
|
||||
r'milk, whole': (r'dairy', null),
|
||||
r'nutrition bars': (r'added', null),
|
||||
r'nutritional beverages': (r'added', null),
|
||||
r'other fruit juice': (r'added', null),
|
||||
r'pancakes, waffles, french toast': (r'added', null),
|
||||
r'plant-based milk': (r'dairy', null),
|
||||
r'plant-based yogurt': (r'dairy', null),
|
||||
r'pudding': (r'added', null),
|
||||
r'ready-to-eat cereal, higher sugar (>21.2g/100g)': (r'added', null),
|
||||
r'ready-to-eat cereal, lower sugar (=<21.2g/100g)': (r'added', null),
|
||||
r'smoothies and grain drinks': (r'added', null),
|
||||
r'soft drinks': (r'added', null),
|
||||
r'sport and energy drinks': (r'added', null),
|
||||
r'sugars and honey': (r'added', null),
|
||||
r'sweets': (r'added', null),
|
||||
r'tomato-based condiments': (r'added', null),
|
||||
r'turnovers and other grain-based items': (r'added', null),
|
||||
r'vegetable juice': (r'added', null),
|
||||
r'yogurt, greek': (r'dairy', null),
|
||||
r'yogurt, regular': (r'dairy', null),
|
||||
};
|
||||
34
app/lib/health/summaries.dart
Normal file
34
app/lib/health/summaries.dart
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
// The Pi's Health summaries (dashboard plugins/health/summary.py), synced one way as "health.summary"
|
||||
// rows: day:<date>, night:<date>, wk:<id>, meta:energy, meta:person — each {k, kind, day, data (JSON)}.
|
||||
// Read-only here: what the band measured, worked out on the Pi with the Health pages' own functions.
|
||||
import 'dart:convert';
|
||||
|
||||
import '../sync/store.dart';
|
||||
|
||||
class Summaries {
|
||||
Summaries(this.store);
|
||||
final SyncStore store;
|
||||
|
||||
Map<String, dynamic>? _get(String k) {
|
||||
final r = store.row('health.summary', k);
|
||||
return r == null ? null : jsonDecode(r['data'] as String) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Map<String, dynamic>? day(String iso) => _get('day:$iso');
|
||||
Map<String, dynamic>? night(String iso) => _get('night:$iso');
|
||||
Map<String, dynamic>? meta(String name) => _get('meta:$name');
|
||||
|
||||
/// Every row of a kind (day / night / workout) in [a, z] (ISO days; null = all), by day.
|
||||
List<Map<String, dynamic>> all(String kind, {String? a, String? z}) {
|
||||
final rs = store.rows('health.summary', where: "json_extract(data, '\$.kind') = ?", args: [kind]);
|
||||
final out = <Map<String, dynamic>>[];
|
||||
for (final r in rs) {
|
||||
final d = r['day'] as String?;
|
||||
if (a != null && d != null && d.compareTo(a) < 0) continue;
|
||||
if (z != null && d != null && d.compareTo(z) > 0) continue;
|
||||
out.add({'_day': d, ...jsonDecode(r['data'] as String) as Map<String, dynamic>});
|
||||
}
|
||||
out.sort((x, y) => ((x['_day'] as String?) ?? '').compareTo((y['_day'] as String?) ?? ''));
|
||||
return out;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue