dashboard/app/lib/health/sleep_page.dart
bashynx fb3c01cdd7 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>
2026-10-24 09:56:19 +02:00

620 lines
29 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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;
}