From 5178bb5732b73a0dc43afdb9ffeae06892ba6b71 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 31 Jul 2026 15:57:07 +0200 Subject: [PATCH] Let a measurement chart draw several named series --- .../widgets/dashboard/widgets/weight.dart | 2 +- lib/features/measurements/widgets/charts.dart | 266 ++++++++++++++---- .../measurements/widgets/helpers.dart | 2 +- .../measurements/widgets/charts_test.dart | 107 +++++++ 4 files changed, 319 insertions(+), 58 deletions(-) diff --git a/lib/core/widgets/dashboard/widgets/weight.dart b/lib/core/widgets/dashboard/widgets/weight.dart index 34fea596c..181b56021 100644 --- a/lib/core/widgets/dashboard/widgets/weight.dart +++ b/lib/core/widgets/dashboard/widgets/weight.dart @@ -130,7 +130,7 @@ class DashboardWeightWidget extends ConsumerWidget { children: [ SizedBox( height: 200, - child: MeasurementChartWidgetFl( + child: MeasurementChartWidgetFl.singleMeasurement( entriesAll, weightUnit(profile.isMetric, context), avgs: entries7dAvg, diff --git a/lib/features/measurements/widgets/charts.dart b/lib/features/measurements/widgets/charts.dart index 2c6533875..15bf43fa4 100644 --- a/lib/features/measurements/widgets/charts.dart +++ b/lib/features/measurements/widgets/charts.dart @@ -55,17 +55,44 @@ String weightUnit(bool isMetric, BuildContext context) { } class MeasurementChartWidgetFl extends StatefulWidget { - final List _entries; - final List? avgs; - final List? trend; + final List _series; final String _unit; - const MeasurementChartWidgetFl(this._entries, this._unit, {this.avgs, this.trend}); + const MeasurementChartWidgetFl(this._series, this._unit); + + /// The usual single-measurement chart: the values plus their average and + /// trend line. + MeasurementChartWidgetFl.singleMeasurement( + List entries, + String unit, { + List? avgs, + List? trend, + super.key, + }) : _unit = unit, + _series = [ + MeasurementChartSeries(entries, MeasurementSeriesRole.raw), + if (avgs != null) MeasurementChartSeries(avgs, MeasurementSeriesRole.average), + if (trend != null && trend.isNotEmpty) + MeasurementChartSeries(trend, MeasurementSeriesRole.trend), + ]; + + /// All points of all series, for the shared axis calculations. + List get _allEntries => _series.expand((s) => s.entries).toList(); @override State createState() => _MeasurementChartWidgetFlState(); } +/// A series resolved into what fl_chart needs: the line itself plus, for range +/// series, the two invisible bounds the band is painted between. +class _ResolvedSeries { + _ResolvedSeries(this.line, this.label, {this.bounds}); + + final LineChartBarData line; + final String? label; + final (LineChartBarData, LineChartBarData)? bounds; +} + class _MeasurementChartWidgetFlState extends State { @override Widget build(BuildContext context) { @@ -78,7 +105,102 @@ class _MeasurementChartWidgetFlState extends State { ); } - LineTouchData tooltipData() { + /// Colours for [MeasurementSeriesRole.component], by position in the group. + List get _componentColors => [ + Theme.of(context).colorScheme.primary, + Theme.of(context).colorScheme.tertiary, + Theme.of(context).colorScheme.secondary, + Theme.of(context).colorScheme.error, + ]; + + List _spots( + List entries, [ + num Function(MeasurementChartEntry)? y, + ]) => entries + .map( + (e) => FlSpot( + e.date.millisecondsSinceEpoch.toDouble(), + (y == null ? e.value : y(e)).toDouble(), + ), + ) + .toList(); + + /// Turns the series into fl_chart lines, styled by their role. + List<_ResolvedSeries> _resolveSeries() { + final scheme = Theme.of(context).colorScheme; + var componentIndex = 0; + + return widget._series.map((series) { + final spots = _spots(series.entries); + final LineChartBarData line; + + switch (series.role) { + case MeasurementSeriesRole.raw: + line = LineChartBarData( + spots: spots, + isCurved: false, + color: scheme.primary, + barWidth: 0, + isStrokeCapRound: true, + dotData: const FlDotData(show: true), + ); + case MeasurementSeriesRole.average: + line = LineChartBarData( + spots: spots, + isCurved: false, + color: scheme.tertiary, + barWidth: 1, + dotData: const FlDotData(show: false), + ); + case MeasurementSeriesRole.trend: + line = LineChartBarData( + spots: spots, + isCurved: true, + curveSmoothness: 0.4, + color: scheme.secondary, + barWidth: 3, + dotData: const FlDotData(show: false), + ); + case MeasurementSeriesRole.component: + line = LineChartBarData( + spots: spots, + isCurved: false, + color: _componentColors[componentIndex++ % _componentColors.length], + barWidth: 2, + isStrokeCapRound: true, + dotData: const FlDotData(show: true), + ); + } + + // Points that summarise a range get a band between their bounds. The + // bounds themselves are invisible; only the fill between them shows. + final ranged = series.entries.where((e) => e.hasRange).toList(); + return _ResolvedSeries( + line, + series.label, + bounds: ranged.length == series.entries.length && ranged.isNotEmpty + ? ( + LineChartBarData( + spots: _spots(ranged, (e) => e.min!), + color: Colors.transparent, + barWidth: 0, + dotData: const FlDotData(show: false), + ), + LineChartBarData( + spots: _spots(ranged, (e) => e.max!), + color: Colors.transparent, + barWidth: 0, + dotData: const FlDotData(show: false), + ), + ) + : null, + ); + }).toList(); + } + + /// [hidden] holds the indices of the invisible band bounds, which must not + /// show up as tooltip lines; [labels] names the series that have a name. + LineTouchData tooltipData(Set hidden, Map labels) { return LineTouchData( touchTooltipData: LineTouchTooltipData( getTooltipColor: (touchedSpot) => Theme.of(context).colorScheme.primaryContainer, @@ -86,6 +208,9 @@ class _MeasurementChartWidgetFlState extends State { final numberFormat = localizedNumberFormat(context); return touchedSpots.map((touchedSpot) { + if (hidden.contains(touchedSpot.barIndex)) { + return null; + } final msSinceEpoch = touchedSpot.x.toInt(); final DateTime date = DateTime.fromMillisecondsSinceEpoch(touchedSpot.x.toInt()); final dateStr = DateFormat.Md( @@ -95,9 +220,12 @@ class _MeasurementChartWidgetFlState extends State { // Check if this is an interpolated point (milliseconds ending with 123) final bool isInterpolated = msSinceEpoch % 1000 == INTERPOLATION_MARKER; final String interpolatedMarker = isInterpolated ? ' (interpolated)' : ''; + final label = labels[touchedSpot.barIndex]; + final prefix = label == null ? '' : '$label '; return LineTooltipItem( - '$dateStr: ${numberFormat.format(touchedSpot.y)} ${widget._unit}$interpolatedMarker', + '$prefix$dateStr: ${numberFormat.format(touchedSpot.y)} ' + '${widget._unit}$interpolatedMarker', TextStyle(color: touchedSpot.bar.color), ); }).toList(); @@ -108,9 +236,39 @@ class _MeasurementChartWidgetFlState extends State { LineChartData mainData() { final numberFormat = localizedNumberFormat(context); + final allEntries = widget._allEntries; + final dates = allEntries.map((e) => e.date).toList()..sort(); + + // Flatten the series into fl_chart's flat bar list, remembering which + // indices are band bounds (invisible) and which carry a name. + final bars = []; + final bands = []; + final hidden = {}; + final labels = {}; + for (final resolved in _resolveSeries()) { + if (resolved.bounds != null) { + final lower = bars.length; + bars.add(resolved.bounds!.$1); + final upper = bars.length; + bars.add(resolved.bounds!.$2); + hidden + ..add(lower) + ..add(upper); + bands.add( + BetweenBarsData( + fromIndex: lower, + toIndex: upper, + color: resolved.line.color?.withValues(alpha: 0.15), + ), + ); + } + labels[bars.length] = resolved.label; + bars.add(resolved.line); + } return LineChartData( - lineTouchData: tooltipData(), + lineTouchData: tooltipData(hidden, labels), + betweenBarsData: bands, gridData: FlGridData( show: true, drawVerticalLine: true, @@ -153,11 +311,8 @@ class _MeasurementChartWidgetFlState extends State { DateFormat.Md(Localizations.localeOf(context).languageCode).format(date), ); }, - interval: widget._entries.isNotEmpty - ? chartGetInterval( - widget._entries.last.date, - widget._entries.first.date, - ) + interval: dates.isNotEmpty + ? chartGetInterval(dates.first, dates.last) : CHART_MILLISECOND_FACTOR, ), ), @@ -182,49 +337,7 @@ class _MeasurementChartWidgetFlState extends State { show: true, border: Border.all(color: Theme.of(context).colorScheme.primaryContainer), ), - lineBarsData: [ - LineChartBarData( - spots: widget._entries - .map( - (e) => FlSpot( - e.date.millisecondsSinceEpoch.toDouble(), - e.value.toDouble(), - ), - ) - .toList(), - isCurved: false, - color: Theme.of(context).colorScheme.primary, - barWidth: 0, - isStrokeCapRound: true, - dotData: const FlDotData(show: true), - ), - if (widget.avgs != null) - LineChartBarData( - spots: widget.avgs! - .map( - (e) => FlSpot( - e.date.millisecondsSinceEpoch.toDouble(), - e.value.toDouble(), - ), - ) - .toList(), - isCurved: false, - color: Theme.of(context).colorScheme.tertiary, - barWidth: 1, - dotData: const FlDotData(show: false), - ), - if (widget.trend != null && widget.trend!.isNotEmpty) - LineChartBarData( - spots: widget.trend! - .map((e) => FlSpot(e.date.millisecondsSinceEpoch.toDouble(), e.value.toDouble())) - .toList(), - isCurved: true, - curveSmoothness: 0.4, - color: Theme.of(context).colorScheme.secondary, - barWidth: 3, - dotData: const FlDotData(show: false), - ), - ], + lineBarsData: bars, ); } } @@ -233,7 +346,48 @@ class MeasurementChartEntry { num value; DateTime date; - MeasurementChartEntry(this.value, this.date); + /// Lower and upper bound of the values [value] summarises. Set for metrics + /// stored as a daily aggregate (heart rate min/max); the chart then draws a + /// band around the line. Both are null for a plain sample. + num? min; + num? max; + + MeasurementChartEntry(this.value, this.date, {this.min, this.max}); + + /// Whether this point carries a range that can be drawn as a band. + bool get hasRange => min != null && max != null; +} + +/// What a series means, which decides how it is drawn. The colours come from +/// the theme when the chart is built, not from the series itself. +enum MeasurementSeriesRole { + /// The measured values themselves, drawn as dots. + raw, + + /// A moving average over [raw]. + average, + + /// The smoothed trend through [raw]. + trend, + + /// One component of a multi-value metric (systolic, diastolic, ...). Every + /// component gets its own colour and appears in the legend by name. + component, +} + +/// One line of a chart: its points and what they mean. +/// +/// A chart takes a list of these, which is what lets one chart show several +/// lines (the components of a group) instead of a single measurement. +class MeasurementChartSeries { + const MeasurementChartSeries(this.entries, this.role, {this.label}); + + final List entries; + final MeasurementSeriesRole role; + + /// Name for the legend and the tooltip. Null for the unnamed series of a + /// plain category, where the chart title already says what is shown. + final String? label; } // for each point, return the average of all the points in the 7 days preceding it diff --git a/lib/features/measurements/widgets/helpers.dart b/lib/features/measurements/widgets/helpers.dart index 79191fcf1..ad4c8bcc7 100644 --- a/lib/features/measurements/widgets/helpers.dart +++ b/lib/features/measurements/widgets/helpers.dart @@ -146,7 +146,7 @@ Widget buildChartForMetricType( // if (metricType.isRangeType) { // return buildRangeChartForMetricType(metricType, raw, unit); // } - return MeasurementChartWidgetFl( + return MeasurementChartWidgetFl.singleMeasurement( raw, unit, avgs: avg, diff --git a/test/features/measurements/widgets/charts_test.dart b/test/features/measurements/widgets/charts_test.dart index 9cbbe1ecb..7f9b15269 100644 --- a/test/features/measurements/widgets/charts_test.dart +++ b/test/features/measurements/widgets/charts_test.dart @@ -74,6 +74,113 @@ void main() { }); }); + group('MeasurementChartEntry', () { + test('only counts as a range when both bounds are set', () { + expect(entry(60, DateTime(2026, 1, 1)).hasRange, isFalse); + expect(MeasurementChartEntry(60, DateTime(2026, 1, 1), min: 50).hasRange, isFalse); + expect( + MeasurementChartEntry(60, DateTime(2026, 1, 1), min: 50, max: 70).hasRange, + isTrue, + ); + }); + }); + + group('MeasurementChartWidgetFl series', () { + /// The chart data fl_chart actually receives + LineChartData chartData(WidgetTester tester) => + tester.widget(find.byType(LineChart)).data; + + final points = [ + entry(60, DateTime(2026, 1, 1)), + entry(70, DateTime(2026, 1, 2)), + ]; + + testWidgets('singleMeasurement draws one line per given role', (tester) async { + await tester.pumpWidget( + _wrap( + MeasurementChartWidgetFl.singleMeasurement( + points, + 'kg', + avgs: points, + trend: points, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(chartData(tester).lineBarsData, hasLength(3)); + expect(chartData(tester).betweenBarsData, isEmpty); + }); + + testWidgets('omits the lines it was not given', (tester) async { + await tester.pumpWidget( + _wrap(MeasurementChartWidgetFl.singleMeasurement(points, 'kg')), + ); + await tester.pumpAndSettle(); + + expect(chartData(tester).lineBarsData, hasLength(1)); + }); + + testWidgets('draws one line per component, in distinct colours', (tester) async { + await tester.pumpWidget( + _wrap( + MeasurementChartWidgetFl([ + MeasurementChartSeries(points, MeasurementSeriesRole.component, label: 'Systolic'), + MeasurementChartSeries(points, MeasurementSeriesRole.component, label: 'Diastolic'), + ], 'mmHg'), + ), + ); + await tester.pumpAndSettle(); + + final bars = chartData(tester).lineBarsData; + expect(bars, hasLength(2)); + expect(bars.first.color, isNot(bars.last.color)); + }); + + testWidgets('a range series adds a band between two invisible bounds', (tester) async { + final ranged = [ + MeasurementChartEntry(60, DateTime(2026, 1, 1), min: 50, max: 80), + MeasurementChartEntry(70, DateTime(2026, 1, 2), min: 55, max: 95), + ]; + await tester.pumpWidget( + _wrap( + MeasurementChartWidgetFl([ + MeasurementChartSeries(ranged, MeasurementSeriesRole.raw), + ], 'bpm'), + ), + ); + await tester.pumpAndSettle(); + + final data = chartData(tester); + // lower bound, upper bound, and the line itself + expect(data.lineBarsData, hasLength(3)); + expect(data.betweenBarsData, hasLength(1)); + expect(data.betweenBarsData.single.fromIndex, 0); + expect(data.betweenBarsData.single.toIndex, 1); + // the bounds carry the range, not the value + expect(data.lineBarsData[0].spots.map((s) => s.y), [50, 55]); + expect(data.lineBarsData[1].spots.map((s) => s.y), [80, 95]); + expect(data.lineBarsData[2].spots.map((s) => s.y), [60, 70]); + }); + + testWidgets('no band when only some points carry a range', (tester) async { + await tester.pumpWidget( + _wrap( + MeasurementChartWidgetFl([ + MeasurementChartSeries([ + MeasurementChartEntry(60, DateTime(2026, 1, 1), min: 50, max: 80), + entry(70, DateTime(2026, 1, 2)), + ], MeasurementSeriesRole.raw), + ], 'bpm'), + ), + ); + await tester.pumpAndSettle(); + + expect(chartData(tester).betweenBarsData, isEmpty); + expect(chartData(tester).lineBarsData, hasLength(1)); + }); + }); + group('aggregatePerDay', () { test('returns an empty list for no entries', () { expect(aggregatePerDay([]), isEmpty);