// Bars over dates for the health pages (steps, energy …): one per day, or from [weeklyFrom] days one // per week = the average day of the days with data (as the web's weekly grouping). Tap or drag = that // bar's numbers above the chart; [range] = the shared Health period as a chip in the corner. import 'dart:math'; import 'package:flutter/material.dart'; import '../app/theme.dart'; import '../health/cycle_model.dart' show daysBetween, plus; import '../health/range.dart'; import 'line_chart.dart' show RangeChip; const weeklyFrom = 120; const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; class BarChart extends StatefulWidget { const BarChart({super.key, required this.points, required this.from, required this.to, required this.color, this.fmt, this.goal, this.height = 160, this.range}); final List<(DateTime, double)> points; // one per day final DateTime from, to; final Color color; final String Function(double)? fmt; // the tip's value final double? goal; // a dashed line (per day) final double height; final HealthRange? range; @override State createState() => _BarChartState(); } class _BarChartState extends State { int? hit; /// [(first day, value or null, label)] List<(DateTime, double?, String)> _buckets() { final byDay = {for (final p in widget.points) p.$1: p.$2}; final n = daysBetween(widget.from, widget.to) + 1; final out = <(DateTime, double?, String)>[]; 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++) byDay[plus(s, i)]].whereType().toList(); out.add((s, vs.isEmpty ? null : vs.reduce((a, b) => a + b) / vs.length, 'Week of ${s.day} ${_mon[s.month - 1]} ${s.year} · a day')); } } else { for (var i = 0; i < n; i++) { final d = plus(widget.from, i); out.add((d, byDay[d], '${d.day} ${_mon[d.month - 1]} ${d.year}')); } } return out; } @override Widget build(BuildContext context) { final b = _buckets(); final fmt = widget.fmt ?? (double v) => v.round().toString(); final h = hit != null && hit! < b.length ? b[hit!] : null; return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row(children: [ Expanded( child: Text(h == null ? 'Tap a bar for its numbers' : '${h.$3}: ${h.$2 == null ? 'nothing' : fmt(h.$2!)}', style: TextStyle(color: h == null ? muted : Colors.white, fontSize: 12.5)), ), if (widget.range != null) RangeChip(widget.range!), ]), const SizedBox(height: 6), LayoutBuilder(builder: (context, box) { void pick(Offset o) => setState(() => hit = ((o.dx - 34) / (box.maxWidth - 34) * b.length).floor().clamp(0, b.length - 1)); return GestureDetector( onTapDown: (d) => pick(d.localPosition), onHorizontalDragUpdate: (d) => pick(d.localPosition), child: CustomPaint(size: Size(box.maxWidth, widget.height), painter: _Painter(b, widget, hit)), ); }), ]); } } class _Painter extends CustomPainter { _Painter(this.b, this.w, this.hit); final List<(DateTime, double?, String)> b; final BarChart w; final int? hit; static double _nice(double x) { final e = pow(10, (log(x) / ln10).floor()).toDouble(), f = x / e; return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * e; } @override void paint(Canvas c, Size size) { const ml = 34.0, mb = 16.0, mt = 4.0; final h = size.height - mb - mt; final peak = max(1.0, [w.goal ?? 0, for (final x in b) x.$2 ?? 0].reduce(max)); final step = _nice(peak / 3), top = (peak / step).ceil() * step; double y(double v) => mt + h - h * v / 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 + 0.001; v += step) { c.drawLine(Offset(ml, y(v)), Offset(size.width, y(v)), Paint()..color = card2); label(v >= 1000 ? '${(v / 1000).toStringAsFixed(v % 1000 == 0 ? 0 : 1)}k' : v.round().toString(), 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 && v > 0) { c.drawRect(Rect.fromLTRB(x0 + pad, y(v), x0 + bw - pad, y(0)), Paint()..color = hit == i ? Colors.white : w.color.withValues(alpha: hit == null ? 1 : .75)); } 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)); } if (w.goal != null) { final gy = y(w.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 _Painter old) => true; }