// DAY STRAIN — when the day's effort actually happened. // // `getDayStrain` was fully implemented and called by nothing. Everything drawn // here was already computed and persisted: `series.strain_curve` (one point per // WAKE MINUTE), the zone minutes, and `max_hr_used` — the ceiling the pipeline // actually integrated against, printed rather than laundered into the score. // // The CURVE leads. The 0–21 is a summary of the curve, not the other way round: // two days can land on the same number with completely different shapes, and // the shape is the thing you can act on. // // What this screen deliberately does NOT draw: // * CTL/ATL/TSB. That is a fortnight of history and it already has a card one // tap away on the Workout tab. A day screen repeating it is noise. // * the resting heart rate TRIMP was anchored on. `getDayHeart`'s // `resting_hr` is now that same nocturnal number (`scalars.rhr` no longer // falls back to daytime HR), so it COULD be printed — it just does not earn // a line on a day screen whose subject is the curve. Naming the input in a // sentence is enough. import 'dart:async' show unawaited; import 'package:flutter/material.dart'; import 'package:lucide_icons_flutter/lucide_icons.dart'; import 'package:provider/provider.dart'; import '../../compute/activity_watch.dart' show kDefaultWeeklyActivityGoal, kWeeklyActivityGoalMax, kWeeklyActivityGoalMin; import '../../data/day_label.dart'; import '../../data/local_repository.dart'; import '../../l10n/app_localizations.dart'; import '../../l10n/date_text.dart'; import '../../l10n/decimal_text.dart'; import '../../models/metric.dart' show whyFromNote; import '../screens/home_screen.dart' show asOfText, repoOf; import '../screens/metric_detail.dart' show dayNavRow, detailScaffold; import '../../state/app_state.dart'; import '../ui2.dart'; import 'catalogue.dart' show zonesWhy; import 'zones.dart' show ZonesDetail; /// Below this the day is not comparable to a full one and the screen says so. /// Wear coverage is a percentage of the whole day, so a normal night off the /// wrist already costs ~30 points — this is "most of the waking day", not /// "nearly all of it". const _lowCoveragePct = 60; /// The trace, the score, and everything needed to say what the score is made /// of. Every field is nullable: a day the band never saw renders its absence. class DayStrainData { /// The local day the curve actually came from. `getDayStrain` falls back to /// the last settled bundle while today is still deriving, so this is read off /// the curve's own timestamps rather than off the label we asked for. final DateTime? day; /// One slot per minute of [day], null where nothing was recorded. A compacted /// curve under a 00:00–24:00 axis draws a sync gap as though it were measured. final List curve; final double? strain; /// Five zone minutes, or null when the day banked no split. final List? zoneMin; /// The HR ceiling the pipeline integrated against — `max_hr_used`, the same /// number the maths saw. final num? maxHrUsed; /// TS-04 — which anchors THIS day's zone bars were binned on: 'karvonen' /// (observed ceiling + measured resting HR), 'observed' (measured ceiling /// only) or 'tanaka' (the age estimate). The bar's footnote states what the /// bar IS, rather than what it usually is. final String? zoneSource; final num? zoneMaxHr; /// The five lower zone edges, in bpm, of the set this day was binned with. final List? zoneLowerBpm; final int? peakHr, wornMin, coveragePct; /// When [wornMin] and [coveragePct] were last computed, if an earlier /// derive's wear was carried forward (#450). Null when they are current. final int? wearAsOf; /// WHY the day has no strain, as the bundle said it — never a sentence /// written on this screen. Null means nothing came back with the absence, and /// the screen then says exactly that. final String? note; /// The days that derived, NEWEST FIRST, for the day stepper. Empty when the /// screen was handed its data (goldens) or the list could not be read; with /// fewer than two the stepper draws nothing. final List days; const DayStrainData({ this.day, this.curve = const [], this.strain, this.zoneMin, this.maxHrUsed, this.zoneSource, this.zoneMaxHr, this.zoneLowerBpm, this.peakHr, this.wornMin, this.coveragePct, this.wearAsOf, this.note, this.days = const [], }); bool get hasCurve => curve.any((v) => v != null); /// The local label of the day this screen shows (today when [day] is null). String get shownDay => day == null ? todayLabel() : dayLabelOf(day!); /// Lays the curve's epoch-second points onto the fixed 00:00–24:00 axis, /// one slot per WALL-CLOCK minute of the first point's local day. /// /// The slot is the local `hour * 60 + minute`, not minutes elapsed since /// midnight: a fall-back day is 1500 minutes long and a spring-forward day /// 1380, so elapsed minutes pushed everything after the transition an hour /// off the axis labels, and on fall-back cut 23:00–24:00 — the end of a /// cumulative curve, which left the trace short of the day strain printed /// under it. On the repeated hour the later sample wins (points arrive in /// time order), which is the right one for a running total. static (DateTime?, List) gridCurve(List<(int, double)> pts) { if (pts.isEmpty) return (null, const []); final first = DateTime.fromMillisecondsSinceEpoch(pts.first.$1 * 1000); final day = DateTime(first.year, first.month, first.day); final out = List.filled(1440, null); for (final p in pts) { final t = DateTime.fromMillisecondsSinceEpoch(p.$1 * 1000); if (t.year != day.year || t.month != day.month || t.day != day.day) { continue; } out[t.hour * 60 + t.minute] = p.$2; } return (day, out); } /// [forDay] is the label the caller is looking at; null means today. Home's /// day switcher passes it, so a past day's strain ring opens that day's /// curve rather than today's. static Future load(LocalRepository repo, {String? forDay}) async { final asked = forDay ?? todayLabel(); // The stepper's days, read beside the strain rather than before it. A // failed read costs the stepper, never the screen. Future> readDays() async { try { return await repo.availableDays(); } catch (_) { return const []; } } final daysRead = readDays(); final s = await repo.getDayStrain(asked); final days = await daysRead; if (s.isEmpty) return DayStrainData(days: days); final pts = <(int, double)>[ for (final e in (s['curve'] as List? ?? const [])) if (e is Map && e['t'] is num && e['v'] is num) ((e['t'] as num).toInt(), (e['v'] as num).toDouble()), ]; final (day, grid) = gridCurve(pts); // Wear for THE DAY THE CURVE CAME FROM, not the day we asked for — both // reads fall back the same way, so asking for the resolved label is what // keeps the coverage figure and the trace describing one day. // // Read even when there is NO curve, which it did not used to be. Whether // the band saw the day is what decides if "wear the band through the day" // is an instruction or an insult, and a day with no strain is exactly the // day that question gets asked on. Map wear = const {}; try { wear = await repo.getDayWear(day == null ? asked : dayLabelOf(day)); } catch (_) { wear = const {}; } final z = s['zones']; final zoneMin = z is Map && [for (var i = 1; i <= 5; i++) z['z$i']].every((v) => v is num) ? [for (var i = 1; i <= 5; i++) (z['z$i'] as num).toInt()] : null; final hr = s['hr']; return DayStrainData( day: day, curve: grid, strain: (s['strain'] as num?)?.toDouble(), zoneMin: zoneMin, maxHrUsed: s['max_hr_used'] as num?, zoneSource: s['zone_source'] as String?, zoneMaxHr: s['zone_max_hr'] as num?, zoneLowerBpm: switch (s['zone_lower_bpm']) { final List e when e.length == 5 && e.every((v) => v is num) => e.cast(), _ => null, }, peakHr: hr is Map ? (hr['max'] as num?)?.toInt() : null, wornMin: (wear['worn_min'] as num?)?.toInt(), coveragePct: (wear['coverage_pct'] as num?)?.toInt(), wearAsOf: (wear['as_of'] as num?)?.toInt(), // The headline absence's reason, at the top level of the payload — the // same string as `absent.strain`. note: s['note'] as String?, days: days, ); } } class DayStrainDetail extends StatefulWidget { /// Preloaded, for goldens. Null means read the repo on open. final DayStrainData? data; /// The day to read, as a local label. Null means today. final String? day; const DayStrainDetail({super.key, this.data, this.day}); @override State createState() => _DayStrainDetailState(); } class _DayStrainDetailState extends State { DayStrainData? _d; bool _loading = true; /// The day being shown, as a label; null is today. Starts as the caller's /// and moves with the stepper. String? _day; /// The day whose data `_d` holds. A step that cannot be read returns here, /// not to the day the stepper named before it, which may itself have been /// overtaken before it loaded. String? _shownDay; // A quick second tap on the stepper starts a second load; the first can // finish last and must not paint the old day under the new label. int _loadToken = 0; @override void initState() { super.initState(); _day = widget.day; _shownDay = widget.day; if (widget.data != null) { _d = widget.data; _loading = false; return; } WidgetsBinding.instance.addPostFrameCallback((_) => _load()); } Future _load() async { final token = ++_loadToken; final repo = repoOf(context); if (repo == null) { if (mounted) setState(() => _loading = false); return; } try { final day = _day; final d = await DayStrainData.load(repo, forDay: day); if (mounted && token == _loadToken) { setState(() => (_d = d, _shownDay = day, _loading = false)); } } catch (_) { // A step that could not be read stays on the day whose data is still // on screen, so the stepper never names a day the curve is not. if (mounted && token == _loadToken) { setState(() => (_day = _shownDay, _loading = false)); } } } void _goDay(String day) { setState(() { _day = day; _loading = true; }); _load(); } @override Widget build(BuildContext c) { final p = P.of(c); final l = AppLocalizations.of(c); final d = _d ?? const DayStrainData(); final day = d.day; // The date the drawn day IS. `getDayStrain` serves the last settled bundle // while today is still deriving, and a screen headed "Today" over // yesterday's trace is the whole reason this is read off the curve. // Same rule as Day Steps: the stepper names the day, so the nav bar only // does when there is no stepper. final sub = day == null || d.days.length >= 2 ? '' : dayLabelOf(day) == todayLabel() ? (l?.dayStrainToday ?? 'TODAY') : localizedDate(day, l?.localeName ?? 'en', pattern: 'd MMMM'); return detailScaffold( c, l?.dayStrainTitle ?? 'Day strain', [ ...dayNavRow(_day ?? d.shownDay, d.days, _goDay), // While a step loads, the previous day's curve must not sit under // the new day's name. if (_loading) ...[ const SizedBox(height: S.x8), const Center(child: CircularProgressIndicator()), ] else ...[ ..._trace(p, l, d), ..._zones(p, l, d), // The weekly activity goal the inactivity watch compares the 7-day // strain total against (activity_watch.dart). Lives here because this // screen is where the 0–21 scale is explained. Section(l?.activityGoalSection ?? 'Weekly activity goal', const _WeeklyGoalRow()), Section(l?.dayStrainInputsSection ?? 'What this is made of', _inputs(p, l, d)), ], ], sub: sub, ); } // ── the curve, and only then the number ──────────────────────────────────── List _trace(P p, AppLocalizations? l, DayStrainData d) { if (!d.hasCurve) { // THE BUNDLE'S REASON, or none. This card used to state one — "it needs a // resting heart rate from a scored night and a day the band was on your // wrist" — and it printed that on a day with a scored night (RHR 56.8) // and 89 % wear, because the sentence was written here rather than // handed over. A cause the screen did not receive is a guess. final why = whyFromNote(d.note, unit: 'days'); // And "wear the band" is only an instruction on a day the band did not // see. Offered on a day it was on the wrist all along it is worse than // no button, because the user spends trust doing it. final saw = (d.wornMin ?? 0) > 0 || (d.coveragePct ?? 0) > 0; // A day CAN carry a strain with no trace behind it: `backfillStrainScale` // rescales the stored headline onto the current scale and DROPS the // per-minute curve, which cannot be rescaled with it. Measured on // whoop-4, that is 6 of 17 days — and on every one of them this card said // "this day produced no strain" directly above a day that produced 10.8. // The absence is the TRACE, so that is what the card is allowed to name; // why the trace is not stored is not something this screen was told. final s = d.strain; return [ StatusCard( s == null ? (l?.dayStrainNoTraceTitle ?? 'No strain trace for this day') : (l?.dayStrainNoMinuteTraceTitle ?? 'No minute-by-minute trace for this day'), s == null ? why ?? (l?.dayStrainNoReasonBody ?? 'Nothing recorded says why this day produced no strain.') : (l?.dayStrainScoredNoTraceBody(displayFixed(s, 1)) ?? 'The day strain is ${displayFixed(s, 1)}. The waking minutes ' 'it was built from are not stored for this day.'), fix: (s == null && !saw) ? (l?.dayStrainWearBandFix ?? 'Wear the band through the day') : '', icon: LucideIcons.trendingUp, ), ]; } // The whole 0–21 scale the header names, so the ticks and the header // agree and two days can be compared by eye. const axis = AxisSpec(min: 0, max: 21, ticks: 4, format: axisInt); final drawn = d.curve.where((v) => v != null).length; return [ Surface( child: Column(children: [ ChartFrame( title: l?.dayStrainChartTitle ?? 'Strain through the day', unit: '0–21', height: 170, yAxis: axis, xLabels: const ['00:00', '12:00', '24:00'], series: d.curve, footnote: l?.dayStrainChartFootnote(drawn) ?? 'Effort above your usual waking pace. It can ease later if you slow back toward that pace. From $drawn recorded waking minutes.', child: CustomPaint( size: Size.infinite, painter: LineChart(d.curve, p.on(C.purple), axis: axis, t: animate(context, 1)), ), ), if (d.strain != null || d.peakHr != null || d.wornMin != null) ...[ const SizedBox(height: S.x4), InlineMetrics([ if (d.strain != null) (l?.dayStrainTitle ?? 'Day strain', displayFixed(d.strain!, 1), C.purple), if (d.peakHr != null) (l?.dayStrainPeakHr ?? 'Peak HR', '${d.peakHr} bpm', C.red), if (d.wornMin != null) // #450: a carried figure says where it stops, or a frozen // morning reads as the whole day so far. ( d.wearAsOf == null ? (l?.dayStrainWorn ?? 'Worn') : (l?.dayStrainWornAsOf( asOfText(d.wearAsOf!, d.shownDay, l)) ?? 'Worn as of ${asOfText(d.wearAsOf!, d.shownDay, l)}'), '${d.wornMin} min', C.teal, ), ]), ], ]), ), if (d.coveragePct != null && d.coveragePct! < _lowCoveragePct) Padding( padding: const EdgeInsets.only(top: S.x4), child: StatusCard( l?.dayStrainLowCoverageTitle(d.coveragePct!) ?? 'The band saw ${d.coveragePct}% of this day', l?.dayStrainLowCoverageBody ?? 'Strain is a total over the minutes that were recorded, so a ' 'partly-worn day reads lower than a full one and the two are ' 'not comparable.', icon: LucideIcons.watch, ), ), ]; } // ── where the effort sat ─────────────────────────────────────────────────── List _zones(P p, AppLocalizations? l, DayStrainData d) { final z = d.zoneMin; if (z == null) return const []; final total = z.fold(0, (a, b) => a + b); if (total <= 0) return const []; return [ Section( l?.dayStrainTimeInZonesSection ?? 'Time in zones', Surface( child: ZoneRows( [for (final v in z) v.toDouble()], lowerBpm: d.zoneLowerBpm, title: l?.dayStrainZonesChartTitle ?? 'Time in zones', // TS-03/TS-04 — the edges, and where THIS day's came from. Stated // per day, not as a standing hedge: the same screen tomorrow can be // banded on a measured ceiling, and a footnote that still said // "estimated from your age" would then be false. The 28-day // distribution is NOT here — it lives one tap away and is gated on // the same anchors (TS-05). footnote: zonesWhy(d.zoneSource, d.zoneMaxHr, l), ), ), // Progressive disclosure: this day screen gains a LINK, not a row. The // ceiling, the edges in bpm and the 28-day distribution are all one tap // behind it. action: l?.dayStrainHowSet ?? 'How these are set', onAction: () => Navigator.of(context) .push(MaterialPageRoute(builder: (_) => const ZonesDetail())), ), ]; } // ── the inputs, named ────────────────────────────────────────────────────── Widget _inputs(P p, AppLocalizations? l, DayStrainData d) { final max = d.maxHrUsed; return Surface( elevation: 0, color: p.card2, child: Text( [ l?.dayStrainInputsBase ?? 'How hard your heart worked while awake, by minutes in each heart-rate zone, on a 0–21 scale.', if (max != null) l?.dayStrainInputsMaxHr(max.round()) ?? 'It was integrated against an assumed maximum of ' '${max.round()} bpm — estimated from your age and your strap, ' 'not measured.', // Said out loud because the zone bar above can now be banded on a // MEASURED ceiling while this number is still the age estimate, and // two different ceilings on one screen with nothing saying so is // exactly the defect TS-03a removed. if (max != null && d.zoneSource != null && d.zoneSource != 'tanaka') l?.dayStrainInputsMeasuredCeilingNote ?? 'The zone bar uses your measured maximum. Strain does not, so the strain scores you have already seen stay the same.', l?.dayStrainInputsRhrAnchor ?? 'The other anchor is your resting heart rate from the night before, ' 'so a night the band missed moves the whole day.', ].join(' '), style: F.cap.copyWith(color: p.ink3, height: 1.5), ), ); } } /// The weekly activity goal row (PR 3): the inactivity watch compares the /// 7-day strain total against this goal. Tap to edit in place; the value is /// stored on the profile as `weekly_activity_goal` (strain-points/week) and /// read by the cross-day bundle through `profile`. class _WeeklyGoalRow extends StatefulWidget { const _WeeklyGoalRow(); @override State<_WeeklyGoalRow> createState() => _WeeklyGoalRowState(); } class _WeeklyGoalRowState extends State<_WeeklyGoalRow> { int _goal = kDefaultWeeklyActivityGoal.round(); bool _editing = false; bool _loaded = false; late final TextEditingController _ctrl = TextEditingController(); @override void didChangeDependencies() { super.didChangeDependencies(); if (_loaded) return; _loaded = true; unawaited(_loadGoal()); } Future _loadGoal() async { final repo = repoOf(context); if (repo == null) return; try { final p = await repo.getProfile(); if (!mounted) return; setState(() { _goal = ((p['weekly_activity_goal'] as num?)?.toDouble() ?? kDefaultWeeklyActivityGoal) .round(); _ctrl.text = '$_goal'; }); } catch (_) { // A repo that cannot answer (e.g. a test double) keeps the default shown; // the row still renders and editing still works. } } @override void dispose() { _ctrl.dispose(); super.dispose(); } Future _save(BuildContext c) async { final l = AppLocalizations.of(c); final t = Typed.of(_ctrl.text); if (t.bad) { sayUnreadable(c, [l?.activityGoalRow ?? 'Weekly goal']); return; } final typed = t.value?.round(); if (typed == null) { setState(() => _editing = false); return; } if (typed < kWeeklyActivityGoalMin.round() || typed > kWeeklyActivityGoalMax.round()) { ScaffoldMessenger.of(c).showSnackBar( SnackBar( content: Text( l?.activityGoalInvalid(kWeeklyActivityGoalMin.round(), kWeeklyActivityGoalMax.round()) ?? 'A weekly goal of ${kWeeklyActivityGoalMin.round()}–${kWeeklyActivityGoalMax.round()} strain points is a real one. Nothing was saved.', ), ), ); return; } setState(() { _editing = false; _goal = typed; }); await c.read().updateProfile({'weekly_activity_goal': typed}); } @override Widget build(BuildContext c) { final p = P.of(c); final l = AppLocalizations.of(c); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Surface( onTap: () => setState(() { _editing = true; _ctrl.text = '$_goal'; }), child: Row( children: [ Expanded( child: Text( l?.activityGoalRow ?? 'Strain points per week', style: F.body.copyWith(color: p.ink), ), ), if (_editing) SizedBox( width: 90, child: TextField( controller: _ctrl, keyboardType: TextInputType.number, autofocus: true, style: F.body.copyWith(color: p.ink), decoration: const InputDecoration( isDense: true, border: OutlineInputBorder(), ), onSubmitted: (_) => _save(c), ), ) else Text( '$_goal', style: F.body.copyWith( color: p.ink, fontWeight: FontWeight.w600), ), const SizedBox(width: S.x2), Pressable( onTap: _editing ? () => _save(c) : null, child: Icon( _editing ? LucideIcons.check : LucideIcons.pencil, size: 16, color: p.ink2, ), ), ], ), ), const SizedBox(height: S.x2), Text( l?.activityGoalHint ?? 'The inactivity watch compares your last 7 days of strain against this. The default 45 is about 150 minutes of moderate activity a week on this scale.', style: F.cap.copyWith(color: p.ink3, height: 1.5), ), ], ); } }