mirror of
https://github.com/wger-project/flutter.git
synced 2026-11-29 09:20:56 +01:00
Split the measurement charts into four files
This commit is contained in:
File diff suppressed because it is too large
Load Diff
262
lib/features/measurements/widgets/charts/chart_series.dart
Normal file
262
lib/features/measurements/widgets/charts/chart_series.dart
Normal file
@@ -0,0 +1,262 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2020 - 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// A nutrition plan period shown for context: shaded as a vertical band in
|
||||
/// the chart, and named in the tooltip of the points it contains.
|
||||
typedef PlanPeriod = ({DateTimeRange range, String name});
|
||||
|
||||
/// Fill of a plan period band, shared with the legend so its swatch matches.
|
||||
Color planBandColor(BuildContext context) =>
|
||||
Theme.of(context).colorScheme.primary.withValues(alpha: 0.15);
|
||||
|
||||
/// The parts of [periods] that overlap [bounds], clamped to it. Periods
|
||||
/// entirely outside [bounds] are dropped.
|
||||
List<DateTimeRange> clampPeriods(List<DateTimeRange> periods, DateTimeRange bounds) => [
|
||||
for (final period in periods)
|
||||
if (period.start.isBefore(bounds.end) && period.end.isAfter(bounds.start))
|
||||
DateTimeRange(
|
||||
start: period.start.isAfter(bounds.start) ? period.start : bounds.start,
|
||||
end: period.end.isBefore(bounds.end) ? period.end : bounds.end,
|
||||
),
|
||||
];
|
||||
|
||||
/// Colour of the [index]-th [MeasurementSeriesRole.component] line. Shared
|
||||
/// with the legend so a component's colour matches its line.
|
||||
Color componentColor(BuildContext context, int index) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final colors = [scheme.primary, scheme.tertiary, scheme.secondary, scheme.error];
|
||||
return colors[index % colors.length];
|
||||
}
|
||||
|
||||
/// Colour of a change bar, by which way it points. Theme colours rather than
|
||||
/// green and red: which direction is the good one depends on the goal (losing
|
||||
/// weight, building muscle), and the chart should not assert one.
|
||||
Color deltaColor(BuildContext context, num delta) =>
|
||||
delta < 0 ? Theme.of(context).colorScheme.tertiary : Theme.of(context).colorScheme.primary;
|
||||
|
||||
class MeasurementChartEntry {
|
||||
num value;
|
||||
DateTime 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;
|
||||
|
||||
/// How many readings this point stands for, which a condensed one summarises
|
||||
/// several of. Only the distribution asks: a histogram of a handful of
|
||||
/// readings is noise, however many points they were condensed into.
|
||||
int count;
|
||||
|
||||
MeasurementChartEntry(this.value, this.date, {this.min, this.max, this.count = 1});
|
||||
|
||||
/// 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<MeasurementChartEntry> 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;
|
||||
}
|
||||
|
||||
/// One stacked bar: a day, and the value each component contributed to it.
|
||||
///
|
||||
/// [values] runs parallel to the components the chart was given, a null
|
||||
/// standing for a component that has nothing on that day.
|
||||
class MeasurementStackedEntry {
|
||||
const MeasurementStackedEntry(this.date, this.values);
|
||||
|
||||
final DateTime date;
|
||||
final List<num?> values;
|
||||
|
||||
/// The bar's full height, i.e. what the components add up to.
|
||||
num get total => values.fold(0, (sum, value) => sum + (value ?? 0));
|
||||
}
|
||||
|
||||
/// For each point, the average of all the points in the [days] preceding it.
|
||||
List<MeasurementChartEntry> movingAverage(List<MeasurementChartEntry> vals, {int days = 7}) {
|
||||
var start = 0;
|
||||
var end = 0;
|
||||
final List<MeasurementChartEntry> out = <MeasurementChartEntry>[];
|
||||
|
||||
// first make sure our list is in ascending order, without reordering the
|
||||
// caller's own list
|
||||
final sorted = [...vals]..sort((a, b) => a.date.compareTo(b.date));
|
||||
|
||||
// The window total is carried along instead of re-summing the window for
|
||||
// every point: with densely sampled metrics the window holds thousands of
|
||||
// values, and re-adding them each time makes this quadratic
|
||||
num sum = 0;
|
||||
|
||||
while (end < sorted.length) {
|
||||
sum += sorted[end].value;
|
||||
|
||||
// since users can log measurements several days, or minutes apart,
|
||||
// we can't make assumptions. We have to manually advance 'start'
|
||||
// such that it is always the first point within our desired range.
|
||||
// posibly start == end (when there is only one point in the range)
|
||||
final intervalStart = sorted[end].date.subtract(Duration(days: days));
|
||||
while (start < end && sorted[start].date.isBefore(intervalStart)) {
|
||||
sum -= sorted[start].value;
|
||||
start++;
|
||||
}
|
||||
|
||||
out.add(MeasurementChartEntry(sum / (end - start + 1), sorted[end].date));
|
||||
|
||||
end++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Produces a smoothed trendline via an Exponential Moving Average (EMA),
|
||||
/// seeded with the first data point. A larger [period] tracks the raw values
|
||||
/// more loosely (smoother, more lag).
|
||||
List<MeasurementChartEntry> smoothedTrendline(
|
||||
List<MeasurementChartEntry> vals, {
|
||||
int period = 10,
|
||||
}) {
|
||||
if (vals.isEmpty) {
|
||||
return [];
|
||||
}
|
||||
|
||||
final sorted = [...vals]..sort((a, b) => a.date.compareTo(b.date));
|
||||
final List<MeasurementChartEntry> out = [];
|
||||
|
||||
// Seed the initialization layer with the first data point value
|
||||
double currentEma = sorted[0].value.toDouble();
|
||||
final double smoothing = 2 / (period + 1);
|
||||
|
||||
for (int i = 0; i < sorted.length; i++) {
|
||||
final point = sorted[i];
|
||||
|
||||
if (i > 0) {
|
||||
// EMA equation: point.weight * smoothing + ema * (1 - smoothing)
|
||||
currentEma = (point.value * smoothing) + (currentEma * (1 - smoothing));
|
||||
}
|
||||
|
||||
out.add(MeasurementChartEntry(currentEma, point.date));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/// The Monday of the week [date] falls into, at midnight.
|
||||
DateTime weekStart(DateTime date) =>
|
||||
DateTime(date.year, date.month, date.day).subtract(Duration(days: date.weekday - 1));
|
||||
|
||||
/// Sums entries per calendar day. Used for metric types where individual
|
||||
/// samples aren't meaningful on their own (steps, distance, energy, sleep) —
|
||||
/// see MeasurementMetricType.isSummedPerDay.
|
||||
List<MeasurementChartEntry> aggregatePerDay(List<MeasurementChartEntry> vals) {
|
||||
if (vals.isEmpty) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Bucket by the day component only (strip time-of-day).
|
||||
final Map<DateTime, num> sums = {};
|
||||
for (final e in vals) {
|
||||
final day = DateTime(e.date.year, e.date.month, e.date.day);
|
||||
sums.update(day, (existing) => existing + e.value, ifAbsent: () => e.value);
|
||||
}
|
||||
|
||||
final out = sums.entries.map((e) => MeasurementChartEntry(e.value, e.key)).toList()
|
||||
..sort((a, b) => a.date.compareTo(b.date));
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Averages entries per calendar day.
|
||||
///
|
||||
/// The per-day counterpart of [aggregatePerDay] for the sample metrics (body
|
||||
/// weight, heart rate), where a day's readings are repeated measurements of the
|
||||
/// same thing and adding them up would be meaningless. Used by the charts that
|
||||
/// need exactly one value per day.
|
||||
List<MeasurementChartEntry> averagePerDay(List<MeasurementChartEntry> vals) {
|
||||
if (vals.isEmpty) {
|
||||
return [];
|
||||
}
|
||||
|
||||
final byDay = groupBy(
|
||||
vals,
|
||||
(MeasurementChartEntry e) => DateTime(e.date.year, e.date.month, e.date.day),
|
||||
);
|
||||
|
||||
return [
|
||||
for (final day in byDay.keys.toList()..sort())
|
||||
MeasurementChartEntry(byDay[day]!.map((e) => e.value).average, day),
|
||||
];
|
||||
}
|
||||
|
||||
/// The level a week is summarised at: its total for the summed metric types,
|
||||
/// its average for the sample ones, whose readings repeat the same measurement.
|
||||
num _weekLevel(List<MeasurementChartEntry> week, bool summed) =>
|
||||
summed ? week.map((e) => e.value).sum : week.map((e) => e.value).average;
|
||||
|
||||
/// Week-over-week change: one point per calendar week against the last week
|
||||
/// with readings, summarised (see [_weekLevel]) before subtracting so no single
|
||||
/// reading decides a bar. The running week of a summed metric is left out,
|
||||
/// its total is still growing and would read as a drop until Sunday.
|
||||
List<MeasurementChartEntry> weeklyDeltas(
|
||||
List<MeasurementChartEntry> vals, {
|
||||
bool summed = false,
|
||||
DateTime? today,
|
||||
}) {
|
||||
final byWeek = groupBy(vals, (MeasurementChartEntry e) => weekStart(e.date));
|
||||
if (summed) {
|
||||
byWeek.remove(weekStart(today ?? DateTime.now()));
|
||||
}
|
||||
final weeks = byWeek.keys.toList()..sort();
|
||||
|
||||
return [
|
||||
for (final (index, week) in weeks.indexed.skip(1))
|
||||
MeasurementChartEntry(
|
||||
_weekLevel(byWeek[week]!, summed) - _weekLevel(byWeek[weeks[index - 1]]!, summed),
|
||||
week,
|
||||
),
|
||||
];
|
||||
}
|
||||
772
lib/features/measurements/widgets/charts/chart_widgets.dart
Normal file
772
lib/features/measurements/widgets/charts/chart_widgets.dart
Normal file
@@ -0,0 +1,772 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2020 - 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:fl_chart/fl_chart.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:wger/core/charts.dart';
|
||||
import 'package:wger/core/consts.dart';
|
||||
import 'package:wger/core/formatting/formatting.dart';
|
||||
import 'package:wger/features/measurements/widgets/charts/chart_series.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
/// Number of dates to label on the x axis
|
||||
const X_LABEL_COUNT = 4;
|
||||
|
||||
/// Widest a single bar gets, for charts with only a handful of entries
|
||||
const MAX_BAR_WIDTH = 12.0;
|
||||
|
||||
const _hiddenTitles = AxisTitles(sideTitles: SideTitles(showTitles: false));
|
||||
|
||||
class MeasurementOverallChangeWidget extends StatelessWidget {
|
||||
final MeasurementChartEntry _first;
|
||||
final MeasurementChartEntry _last;
|
||||
final String _unit;
|
||||
|
||||
const MeasurementOverallChangeWidget(this._first, this._last, this._unit);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final delta = _last.value - _first.value;
|
||||
String prefix = '';
|
||||
if (delta > 0) {
|
||||
prefix = '+';
|
||||
} else if (delta < 0) {
|
||||
prefix = '-';
|
||||
}
|
||||
|
||||
return Text(
|
||||
'${AppLocalizations.of(context).overallChangeWeight} '
|
||||
'$prefix${measurementWithUnit(context, delta.abs(), _unit)}',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String weightUnit(bool isMetric, BuildContext context) {
|
||||
return isMetric ? AppLocalizations.of(context).kg : AppLocalizations.of(context).lb;
|
||||
}
|
||||
|
||||
/// Y-axis tick label that never wraps: a long value+unit combination shrinks
|
||||
/// to fit the reserved width instead of breaking into overlapping lines.
|
||||
class _YAxisLabel extends StatelessWidget {
|
||||
const _YAxisLabel(this.text);
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FittedBox(
|
||||
fit: BoxFit.scaleDown,
|
||||
child: Text(text, maxLines: 1),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The value axis, drawn the same way by every chart of the set.
|
||||
AxisTitles _valueTitles(BuildContext context, String unit, double? interval) => AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
reservedSize: 65,
|
||||
interval: interval,
|
||||
getTitlesWidget: (value, meta) {
|
||||
// Don't show the first and last entries, to avoid overlap
|
||||
// see https://stackoverflow.com/questions/73355777/flutter-fl-chart-how-can-we-avoid-the-overlap-of-the-ordinate
|
||||
// this is needlessly aggressive if the titles are "sparse", but we should optimize for more busy data
|
||||
if (value == meta.min || value == meta.max) {
|
||||
return const Text('');
|
||||
}
|
||||
|
||||
return _YAxisLabel(measurementWithUnit(context, value, unit));
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
/// The date axis of the bar charts, which draw one title per group: their x
|
||||
/// value is a position in [dates] rather than a timestamp, so thinning the
|
||||
/// labels out has to happen here.
|
||||
AxisTitles _dateIndexTitles(BuildContext context, List<DateTime> dates) {
|
||||
final labelStep = max(1, (dates.length / X_LABEL_COUNT).ceil());
|
||||
// keep the labels away from the chart edges
|
||||
final labelOffset = labelStep ~/ 2;
|
||||
final spansYears = dates.isNotEmpty && dates.first.year != dates.last.year;
|
||||
|
||||
return AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
getTitlesWidget: (value, meta) {
|
||||
final index = value.toInt();
|
||||
if (index < 0 || index >= dates.length) {
|
||||
return const Text('');
|
||||
}
|
||||
if ((index - labelOffset) % labelStep != 0) {
|
||||
return const Text('');
|
||||
}
|
||||
// if we go across years, show years in the ticks. otherwise leave them out
|
||||
final date = dates[index];
|
||||
if (spansYears) {
|
||||
return Text(localizedDate(context).format(date));
|
||||
}
|
||||
return Text(DateFormat.Md(Localizations.localeOf(context).languageCode).format(date));
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Bar width in pixels: the bars share the available width and keep a gap
|
||||
/// between them, but never go below a hairline. Without it a couple of months
|
||||
/// of readings overlap into a solid block.
|
||||
double _barWidth(int count, double availableWidth) =>
|
||||
count == 0 ? MAX_BAR_WIDTH : (availableWidth / count * 0.7).clamp(1.0, MAX_BAR_WIDTH);
|
||||
|
||||
/// Horizontal lines only: a vertical one per bar would only repeat the bars.
|
||||
FlGridData _barGrid(BuildContext context) => FlGridData(
|
||||
show: true,
|
||||
drawVerticalLine: false,
|
||||
getDrawingHorizontalLine: (value) =>
|
||||
FlLine(color: Theme.of(context).colorScheme.primaryContainer, strokeWidth: 1),
|
||||
);
|
||||
|
||||
FlBorderData _barBorder(BuildContext context) => FlBorderData(
|
||||
show: true,
|
||||
border: Border.all(color: Theme.of(context).colorScheme.primaryContainer),
|
||||
);
|
||||
|
||||
/// 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 MeasurementChartWidgetFl extends StatelessWidget {
|
||||
/// Radius of a dot on a chart with room to spare
|
||||
static const MAX_DOT_RADIUS = 4.0;
|
||||
|
||||
final List<MeasurementChartSeries> _series;
|
||||
final String _unit;
|
||||
final List<PlanPeriod> _planPeriods;
|
||||
|
||||
const MeasurementChartWidgetFl(
|
||||
this._series,
|
||||
this._unit, {
|
||||
List<PlanPeriod> planPeriods = const [],
|
||||
super.key,
|
||||
}) : _planPeriods = planPeriods;
|
||||
|
||||
/// The usual single-measurement chart: the values plus their average and
|
||||
/// trend line.
|
||||
MeasurementChartWidgetFl.singleMeasurement(
|
||||
List<MeasurementChartEntry> entries,
|
||||
String unit, {
|
||||
List<MeasurementChartEntry>? avgs,
|
||||
List<MeasurementChartEntry>? trend,
|
||||
List<PlanPeriod> planPeriods = const [],
|
||||
super.key,
|
||||
}) : _unit = unit,
|
||||
_planPeriods = planPeriods,
|
||||
_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<MeasurementChartEntry> get _allEntries => _series.expand((s) => s.entries).toList();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AspectRatio(
|
||||
aspectRatio: 1.70,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
// Dot size is in pixels, so it has to follow from how many points
|
||||
// share the available space, otherwise they merge into a blob
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) => LineChart(mainData(context, constraints.maxWidth)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Dots shrink as points get denser, so they stay distinguishable instead of
|
||||
/// overdrawing each other.
|
||||
FlDotData _dotData(double availableWidth) {
|
||||
final count = _series.map((s) => s.entries.length).fold(0, max);
|
||||
if (count == 0) {
|
||||
return const FlDotData(show: true);
|
||||
}
|
||||
|
||||
final radius = (availableWidth / count / 2).clamp(0.5, MAX_DOT_RADIUS);
|
||||
return FlDotData(
|
||||
show: true,
|
||||
getDotPainter: (spot, percent, barData, index) =>
|
||||
FlDotCirclePainter(radius: radius, color: barData.color ?? Colors.transparent),
|
||||
);
|
||||
}
|
||||
|
||||
List<FlSpot> _spots(
|
||||
List<MeasurementChartEntry> 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(BuildContext context, double availableWidth) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final dots = _dotData(availableWidth);
|
||||
var componentIndex = 0;
|
||||
|
||||
return _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: dots,
|
||||
);
|
||||
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: componentColor(context, componentIndex++),
|
||||
barWidth: 2,
|
||||
isStrokeCapRound: true,
|
||||
dotData: dots,
|
||||
);
|
||||
}
|
||||
|
||||
// Points that summarise a range get a band between their bounds. The
|
||||
// bounds themselves are invisible; only the fill between them shows.
|
||||
//
|
||||
// Only for the measured series: a band says "this is the spread of the
|
||||
// measurements", which a derived line has none of. Condensing attaches a
|
||||
// range to every point, so an average that got downsampled along with
|
||||
// its values would otherwise be given a second band of its own.
|
||||
final carriesSpread =
|
||||
series.role == MeasurementSeriesRole.raw ||
|
||||
series.role == MeasurementSeriesRole.component;
|
||||
final ranged = carriesSpread
|
||||
? series.entries.where((e) => e.hasRange).toList()
|
||||
: const <MeasurementChartEntry>[];
|
||||
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();
|
||||
}
|
||||
|
||||
/// Names of the plans whose period contains [date].
|
||||
List<String> _planNamesAt(DateTime date) => [
|
||||
for (final p in _planPeriods)
|
||||
if (!date.isBefore(p.range.start) && !date.isAfter(p.range.end)) p.name,
|
||||
];
|
||||
|
||||
/// The plan periods as translucent full-height bands, clamped to the span
|
||||
/// of the data so they never draw outside the axes.
|
||||
RangeAnnotations _planBands(BuildContext context, List<DateTime> dates) {
|
||||
if (dates.isEmpty || _planPeriods.isEmpty) {
|
||||
return const RangeAnnotations();
|
||||
}
|
||||
|
||||
final bounds = DateTimeRange(start: dates.first, end: dates.last);
|
||||
return RangeAnnotations(
|
||||
verticalRangeAnnotations: [
|
||||
for (final range in clampPeriods([for (final p in _planPeriods) p.range], bounds))
|
||||
VerticalRangeAnnotation(
|
||||
x1: range.start.millisecondsSinceEpoch.toDouble(),
|
||||
x2: range.end.millisecondsSinceEpoch.toDouble(),
|
||||
color: planBandColor(context),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// [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(BuildContext context, Set<int> hidden, Map<int, String?> labels) {
|
||||
return LineTouchData(
|
||||
touchTooltipData: LineTouchTooltipData(
|
||||
getTooltipColor: (touchedSpot) => Theme.of(context).colorScheme.primaryContainer,
|
||||
getTooltipItems: (touchedSpots) {
|
||||
// The plan context belongs to the touched date, not to a series, so
|
||||
// it goes below the last tooltip line instead of onto every line
|
||||
final lastVisible = touchedSpots.lastWhereOrNull(
|
||||
(s) => !hidden.contains(s.barIndex),
|
||||
);
|
||||
|
||||
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(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(date);
|
||||
|
||||
// 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 ';
|
||||
|
||||
final planNames = identical(touchedSpot, lastVisible)
|
||||
? _planNamesAt(date)
|
||||
: const <String>[];
|
||||
return LineTooltipItem(
|
||||
'$prefix$dateStr: '
|
||||
'${measurementWithUnit(context, touchedSpot.y, _unit)}$interpolatedMarker',
|
||||
TextStyle(color: touchedSpot.bar.color),
|
||||
children: [
|
||||
for (final name in planNames)
|
||||
TextSpan(
|
||||
text: '\n$name',
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer),
|
||||
),
|
||||
],
|
||||
);
|
||||
}).toList();
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
LineChartData mainData(BuildContext context, double availableWidth) {
|
||||
final allEntries = _allEntries;
|
||||
final dates = allEntries.map((e) => e.date).toList()..sort();
|
||||
|
||||
// The bounds of a band reach past the line they wrap, so the axis follows
|
||||
// every value that is drawn, not just the plotted ones
|
||||
final drawn = <num>[
|
||||
for (final entry in allEntries) ...[
|
||||
entry.value,
|
||||
if (entry.min != null) entry.min!,
|
||||
if (entry.max != null) entry.max!,
|
||||
],
|
||||
];
|
||||
final yAxis = drawn.isEmpty ? null : durationAxis(_unit, drawn.reduce(min), drawn.reduce(max));
|
||||
|
||||
// Flatten the series into fl_chart's flat bar list, remembering which
|
||||
// indices are band bounds (invisible) and which carry a name.
|
||||
final bars = <LineChartBarData>[];
|
||||
final bands = <BetweenBarsData>[];
|
||||
final hidden = <int>{};
|
||||
final labels = <int, String?>{};
|
||||
for (final resolved in _resolveSeries(context, availableWidth)) {
|
||||
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(
|
||||
minY: yAxis?.min,
|
||||
maxY: yAxis?.max,
|
||||
lineTouchData: tooltipData(context, hidden, labels),
|
||||
betweenBarsData: bands,
|
||||
rangeAnnotations: _planBands(context, dates),
|
||||
gridData: FlGridData(
|
||||
show: true,
|
||||
drawVerticalLine: true,
|
||||
getDrawingHorizontalLine: (value) {
|
||||
return FlLine(color: Theme.of(context).colorScheme.outlineVariant, strokeWidth: 1);
|
||||
},
|
||||
getDrawingVerticalLine: (value) {
|
||||
return FlLine(color: Theme.of(context).colorScheme.outlineVariant, strokeWidth: 1);
|
||||
},
|
||||
),
|
||||
titlesData: FlTitlesData(
|
||||
show: true,
|
||||
rightTitles: _hiddenTitles,
|
||||
topTitles: _hiddenTitles,
|
||||
bottomTitles: AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
getTitlesWidget: (value, meta) {
|
||||
// Don't show the first and last entries, to avoid overlap
|
||||
// see https://stackoverflow.com/questions/73355777/flutter-fl-chart-how-can-we-avoid-the-overlap-of-the-ordinate
|
||||
// this is needlessly aggressive if the titles are "sparse", but we should optimize for more busy data
|
||||
if (value == meta.min || value == meta.max) {
|
||||
return const Text('');
|
||||
}
|
||||
final DateTime date = DateTime.fromMillisecondsSinceEpoch(value.toInt());
|
||||
// if we go across years, show years in the ticks. otherwise leave them out
|
||||
if (DateTime.fromMillisecondsSinceEpoch(meta.min.toInt()).year !=
|
||||
DateTime.fromMillisecondsSinceEpoch(meta.max.toInt()).year) {
|
||||
return Text(
|
||||
localizedDate(context).format(date),
|
||||
);
|
||||
}
|
||||
return Text(
|
||||
DateFormat.Md(Localizations.localeOf(context).languageCode).format(date),
|
||||
);
|
||||
},
|
||||
interval: dates.isNotEmpty
|
||||
? chartGetInterval(dates.first, dates.last)
|
||||
: CHART_MILLISECOND_FACTOR,
|
||||
),
|
||||
),
|
||||
leftTitles: _valueTitles(context, _unit, yAxis?.interval),
|
||||
),
|
||||
borderData: FlBorderData(
|
||||
show: true,
|
||||
border: Border.all(color: Theme.of(context).colorScheme.outlineVariant),
|
||||
),
|
||||
lineBarsData: bars,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bar chart for entries that are discrete events rather than a continuous
|
||||
/// series: daily totals, and the readings of a multi-value group.
|
||||
///
|
||||
/// Entries carrying a range (see [MeasurementChartEntry.hasRange]) are drawn
|
||||
/// as a bar spanning it, so a blood pressure reading appears as one bar from
|
||||
/// diastolic to systolic. That keeps the pair together as the single event it
|
||||
/// is, and claims nothing about the time between two readings.
|
||||
class MeasurementBarChartWidgetFl extends StatelessWidget {
|
||||
final List<MeasurementChartEntry> _entries;
|
||||
final String _unit;
|
||||
|
||||
/// Whether the values are changes rather than amounts: their bars hang off a
|
||||
/// marked zero line and are coloured by their direction.
|
||||
final bool _signed;
|
||||
|
||||
const MeasurementBarChartWidgetFl(this._entries, this._unit, {bool signed = false, super.key})
|
||||
: _signed = signed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AspectRatio(
|
||||
aspectRatio: 1.70,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) => BarChart(mainData(context, constraints.maxWidth)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
BarTouchData tooltipData(BuildContext context) {
|
||||
return BarTouchData(
|
||||
touchTooltipData: BarTouchTooltipData(
|
||||
getTooltipColor: (group) => Theme.of(context).colorScheme.primaryContainer,
|
||||
getTooltipItem: (group, groupIndex, rod, rodIndex) {
|
||||
if (groupIndex < 0 || groupIndex >= _entries.length) {
|
||||
return null;
|
||||
}
|
||||
final entry = _entries[groupIndex];
|
||||
final dateStr = DateFormat.Md(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(entry.date);
|
||||
// A range is quoted as high over low, the way a blood pressure
|
||||
// reading is written. A change carries its sign, and the plus has to
|
||||
// be added: only the minus comes out of the number format
|
||||
final value = entry.hasRange
|
||||
? '${measurementValue(context, entry.max!, _unit)}'
|
||||
'/${measurementValue(context, entry.min!, _unit)}'
|
||||
: '${_signed && rod.toY > 0 ? '+' : ''}'
|
||||
'${measurementValue(context, rod.toY, _unit)}';
|
||||
|
||||
return BarTooltipItem(
|
||||
'$dateStr: $value ${measurementUnit(_unit)}',
|
||||
TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
BarChartData mainData(BuildContext context, double availableWidth) {
|
||||
// A range bar spans from its lower to its upper bound, so both decide the
|
||||
// axis; a plain bar grows from zero
|
||||
final drawn = <num>[
|
||||
0,
|
||||
for (final entry in _entries) ...[
|
||||
entry.value,
|
||||
if (entry.min != null) entry.min!,
|
||||
if (entry.max != null) entry.max!,
|
||||
],
|
||||
];
|
||||
final yAxis = durationAxis(_unit, drawn.reduce(min), drawn.reduce(max));
|
||||
final barWidth = _barWidth(_entries.length, availableWidth);
|
||||
|
||||
return BarChartData(
|
||||
minY: yAxis?.min,
|
||||
maxY: yAxis?.max,
|
||||
barTouchData: tooltipData(context),
|
||||
gridData: _barGrid(context),
|
||||
titlesData: FlTitlesData(
|
||||
show: true,
|
||||
rightTitles: _hiddenTitles,
|
||||
topTitles: _hiddenTitles,
|
||||
bottomTitles: _dateIndexTitles(context, [for (final entry in _entries) entry.date]),
|
||||
leftTitles: _valueTitles(context, _unit, yAxis?.interval),
|
||||
),
|
||||
borderData: _barBorder(context),
|
||||
// The line the change bars hang off. Without it a chart of only
|
||||
// decreases reads as a normal bar chart pointing the wrong way
|
||||
extraLinesData: ExtraLinesData(
|
||||
horizontalLines: [
|
||||
if (_signed)
|
||||
HorizontalLine(y: 0, color: Theme.of(context).colorScheme.outline, strokeWidth: 1),
|
||||
],
|
||||
),
|
||||
barGroups: _entries
|
||||
.asMap()
|
||||
.entries
|
||||
.map(
|
||||
(e) => BarChartGroupData(
|
||||
x: e.key,
|
||||
barRods: [
|
||||
BarChartRodData(
|
||||
// A range spans its bounds, a plain value grows from zero
|
||||
fromY: e.value.hasRange ? e.value.min!.toDouble() : 0,
|
||||
toY: e.value.hasRange ? e.value.max!.toDouble() : e.value.value.toDouble(),
|
||||
color: _signed
|
||||
? deltaColor(context, e.value.value)
|
||||
: Theme.of(context).colorScheme.primary,
|
||||
width: barWidth,
|
||||
borderRadius: e.value.hasRange
|
||||
? BorderRadius.circular(2)
|
||||
// The rounded end is the one away from the baseline, so
|
||||
// a bar pointing down is capped at the bottom
|
||||
: BorderRadius.vertical(
|
||||
top: e.value.value < 0 ? Radius.zero : const Radius.circular(2),
|
||||
bottom: e.value.value < 0 ? const Radius.circular(2) : Radius.zero,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stacked bar chart for a group whose components are parts of one whole, e.g.
|
||||
/// the sleep stages of a night.
|
||||
///
|
||||
/// One bar per day, split into a segment per component in the components' own
|
||||
/// order, so the bar's height is the night and its segments are how it was
|
||||
/// spent. Colours come from [componentColor] by position, which is what ties a
|
||||
/// segment to its legend entry.
|
||||
class MeasurementStackedBarChartWidgetFl extends StatelessWidget {
|
||||
final List<MeasurementStackedEntry> _entries;
|
||||
final List<String> _labels;
|
||||
final String _unit;
|
||||
|
||||
const MeasurementStackedBarChartWidgetFl(this._entries, this._labels, this._unit, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AspectRatio(
|
||||
aspectRatio: 1.70,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) => BarChart(mainData(context, constraints.maxWidth)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// The whole bar with its parts, since a single segment says little without
|
||||
/// the night it belongs to.
|
||||
BarTouchData tooltipData(BuildContext context) {
|
||||
return BarTouchData(
|
||||
touchTooltipData: BarTouchTooltipData(
|
||||
getTooltipColor: (group) => Theme.of(context).colorScheme.primaryContainer,
|
||||
getTooltipItem: (group, groupIndex, rod, rodIndex) {
|
||||
if (groupIndex < 0 || groupIndex >= _entries.length) {
|
||||
return null;
|
||||
}
|
||||
final entry = _entries[groupIndex];
|
||||
final dateStr = DateFormat.Md(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(entry.date);
|
||||
final parts = [
|
||||
for (final (index, value) in entry.values.indexed)
|
||||
if (value != null) '${_labels[index]}: ${measurementValue(context, value, _unit)}',
|
||||
];
|
||||
|
||||
return BarTooltipItem(
|
||||
'$dateStr: ${measurementWithUnit(context, entry.total, _unit)}'
|
||||
'${parts.isEmpty ? '' : '\n${parts.join('\n')}'}',
|
||||
TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
BarChartData mainData(BuildContext context, double availableWidth) {
|
||||
// The bar is as tall as its segments together, so that is what the axis
|
||||
// has to cover
|
||||
final yAxis = durationAxis(_unit, 0, _entries.map((e) => e.total).fold<num>(0, max));
|
||||
final barWidth = _barWidth(_entries.length, availableWidth);
|
||||
|
||||
return BarChartData(
|
||||
minY: yAxis?.min,
|
||||
maxY: yAxis?.max,
|
||||
barTouchData: tooltipData(context),
|
||||
gridData: _barGrid(context),
|
||||
titlesData: FlTitlesData(
|
||||
show: true,
|
||||
rightTitles: _hiddenTitles,
|
||||
topTitles: _hiddenTitles,
|
||||
bottomTitles: _dateIndexTitles(context, [for (final entry in _entries) entry.date]),
|
||||
leftTitles: _valueTitles(context, _unit, yAxis?.interval),
|
||||
),
|
||||
borderData: _barBorder(context),
|
||||
barGroups: _entries.asMap().entries.map((e) {
|
||||
// fl_chart stacks by absolute offsets rather than by segment heights,
|
||||
// so each part is placed on top of what came before it
|
||||
var offset = 0.0;
|
||||
final stack = <BarChartRodStackItem>[];
|
||||
for (final (index, value) in e.value.values.indexed) {
|
||||
if (value == null || value <= 0) {
|
||||
continue;
|
||||
}
|
||||
stack.add(
|
||||
BarChartRodStackItem(offset, offset + value.toDouble(), componentColor(context, index)),
|
||||
);
|
||||
offset += value.toDouble();
|
||||
}
|
||||
|
||||
return BarChartGroupData(
|
||||
x: e.key,
|
||||
barRods: [
|
||||
BarChartRodData(
|
||||
toY: offset,
|
||||
width: barWidth,
|
||||
rodStackItems: stack,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(2)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class Indicator extends StatelessWidget {
|
||||
const Indicator({
|
||||
super.key,
|
||||
required this.color,
|
||||
required this.text,
|
||||
required this.isSquare,
|
||||
this.size = 16,
|
||||
this.marginRight = 15,
|
||||
this.textColor,
|
||||
});
|
||||
|
||||
final Color color;
|
||||
final String text;
|
||||
final bool isSquare;
|
||||
final double size;
|
||||
final double marginRight;
|
||||
final Color? textColor;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: size,
|
||||
height: size,
|
||||
decoration: BoxDecoration(
|
||||
shape: isSquare ? BoxShape.rectangle : BoxShape.circle,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(text, style: TextStyle(color: textColor)),
|
||||
SizedBox(width: marginRight),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
484
lib/features/measurements/widgets/charts/distribution_chart.dart
Normal file
484
lib/features/measurements/widgets/charts/distribution_chart.dart
Normal file
@@ -0,0 +1,484 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2020 - 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:wger/core/formatting/formatting.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
/// Fewest values a distribution says anything about: below this a histogram
|
||||
/// is noise with gaps, and the chart falls back to the derived default. Same
|
||||
/// principle as a group whose readings are all unpaired falling back to
|
||||
/// lines: never an empty or misleading card.
|
||||
const distributionMinValues = 15;
|
||||
|
||||
/// Widest a histogram gets, in bins. A single outlier (a lb reading stored
|
||||
/// into a kg category) would otherwise stretch a fixed-width histogram into
|
||||
/// hundreds of near-empty bins.
|
||||
const _distributionMaxBins = 100;
|
||||
|
||||
/// A bin width for values nothing is known about: the span split into
|
||||
/// [targetBins], rounded up to 1, 2 or 5 times a power of ten so the edges
|
||||
/// land on round numbers. For the typed metrics the maintained widths in
|
||||
/// MetricType.binWidth are used instead.
|
||||
num niceBinWidth(num min, num max, {int targetBins = 20}) {
|
||||
final span = max - min;
|
||||
if (span <= 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
final raw = span / targetBins;
|
||||
final magnitude = pow(10.0, (log(raw) / ln10).floor());
|
||||
final normalized = raw / magnitude;
|
||||
return (normalized <= 1
|
||||
? 1
|
||||
: normalized <= 2
|
||||
? 2
|
||||
: normalized <= 5
|
||||
? 5
|
||||
: 10) *
|
||||
magnitude;
|
||||
}
|
||||
|
||||
/// A distribution: the values of a period binned by size instead of plotted
|
||||
/// over time, which is what shows the spread and the outliers.
|
||||
class MeasurementHistogram {
|
||||
/// Lower edge of the first bin, a multiple of [binWidth] so the edges land
|
||||
/// on round numbers (60-62, not 59.3-61.3).
|
||||
final num firstEdge;
|
||||
|
||||
final num binWidth;
|
||||
|
||||
/// How many values each bin holds. Bins between the occupied ones are
|
||||
/// present with a zero: a gap in the distribution is worth seeing.
|
||||
final List<int> counts;
|
||||
|
||||
/// Median of the binned values.
|
||||
final num median;
|
||||
|
||||
/// The newest value, i.e. where in the distribution the user is today.
|
||||
final num latest;
|
||||
|
||||
const MeasurementHistogram({
|
||||
required this.firstEdge,
|
||||
required this.binWidth,
|
||||
required this.counts,
|
||||
required this.median,
|
||||
required this.latest,
|
||||
});
|
||||
|
||||
num lowerEdgeOf(int bin) => firstEdge + bin * binWidth;
|
||||
|
||||
num upperEdgeOf(int bin) => firstEdge + (bin + 1) * binWidth;
|
||||
}
|
||||
|
||||
/// One value and how often it occurred.
|
||||
typedef ValueCount = ({num value, int count});
|
||||
|
||||
/// Bins values into a histogram of [binWidth]-wide bins aligned to round
|
||||
/// boundaries; without a width (free-form categories) one is derived from the
|
||||
/// span, see [niceBinWidth].
|
||||
///
|
||||
/// Values arrive counted rather than one by one, which is how the aggregated
|
||||
/// query reads them. [latest] is where the user stands today; it cannot be
|
||||
/// derived here, since counting a value throws away when it was measured.
|
||||
///
|
||||
/// What one value stands for (a reading, a daily total) is the caller's
|
||||
/// decision, the same split as for the heatmap: the summed types distribute
|
||||
/// their days, the sample types every reading.
|
||||
MeasurementHistogram buildWeightedHistogram(
|
||||
List<ValueCount> values, {
|
||||
required num latest,
|
||||
num? binWidth,
|
||||
}) {
|
||||
assert(values.isNotEmpty, 'a histogram of nothing has no bins');
|
||||
|
||||
final sorted = [...values]..sort((a, b) => a.value.compareTo(b.value));
|
||||
final minValue = sorted.first.value;
|
||||
final maxValue = sorted.last.value;
|
||||
|
||||
var width = binWidth ?? niceBinWidth(minValue, maxValue);
|
||||
// Doubling keeps the edges round, unlike recomputing a fitted width
|
||||
while ((maxValue / width).floor() - (minValue / width).floor() >= _distributionMaxBins) {
|
||||
width *= 2;
|
||||
}
|
||||
|
||||
final firstBin = (minValue / width).floor();
|
||||
final counts = List<int>.filled((maxValue / width).floor() - firstBin + 1, 0);
|
||||
for (final entry in sorted) {
|
||||
counts[(entry.value / width).floor() - firstBin] += entry.count;
|
||||
}
|
||||
|
||||
return MeasurementHistogram(
|
||||
firstEdge: firstBin * width,
|
||||
binWidth: width,
|
||||
counts: counts,
|
||||
median: _weightedMedian(sorted),
|
||||
latest: latest,
|
||||
);
|
||||
}
|
||||
|
||||
/// The middle value of [sorted], counting each of them as often as it occurred.
|
||||
num _weightedMedian(List<ValueCount> sorted) {
|
||||
final total = sorted.map((e) => e.count).sum;
|
||||
final firstHalf = _valueAt(sorted, (total - 1) ~/ 2);
|
||||
|
||||
return total.isOdd ? firstHalf : (firstHalf + _valueAt(sorted, total ~/ 2)) / 2;
|
||||
}
|
||||
|
||||
num _valueAt(List<ValueCount> sorted, int index) {
|
||||
var seen = 0;
|
||||
for (final entry in sorted) {
|
||||
seen += entry.count;
|
||||
if (index < seen) {
|
||||
return entry.value;
|
||||
}
|
||||
}
|
||||
return sorted.last.value;
|
||||
}
|
||||
|
||||
/// Histogram of how often each value occurred: the values of the selected
|
||||
/// range binned by size, with the median and the newest value marked.
|
||||
///
|
||||
/// The one chart of the set without a time axis. It answers what is normal
|
||||
/// and what is an outlier, which no chart over time shows, and the marked
|
||||
/// newest value places today within that. Painted by hand like the heatmap:
|
||||
/// fl_chart's BarChart cannot draw the vertical marker lines.
|
||||
class MeasurementDistributionWidgetFl extends StatefulWidget {
|
||||
/// The values with how often each occurred, and where the user stands today.
|
||||
final List<ValueCount> values;
|
||||
final num latest;
|
||||
final String unit;
|
||||
|
||||
/// Width of one bin, null to derive it from the data.
|
||||
final num? binWidth;
|
||||
|
||||
/// Whether a bin's count is a number of days (the summed types) rather than
|
||||
/// a number of readings, which is how the readout words it.
|
||||
final bool countsAreDays;
|
||||
|
||||
const MeasurementDistributionWidgetFl(
|
||||
this.values, {
|
||||
required this.latest,
|
||||
required this.unit,
|
||||
this.binWidth,
|
||||
this.countsAreDays = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MeasurementDistributionWidgetFl> createState() => _MeasurementDistributionWidgetFlState();
|
||||
}
|
||||
|
||||
class _MeasurementDistributionWidgetFlState extends State<MeasurementDistributionWidgetFl> {
|
||||
/// Bin the user tapped, read out above the bars like the heatmap's day.
|
||||
int? _selected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (widget.values.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final histogram = buildWeightedHistogram(
|
||||
widget.values,
|
||||
latest: widget.latest,
|
||||
binWidth: widget.binWidth,
|
||||
);
|
||||
final theme = Theme.of(context);
|
||||
// Tapping outside the grid clears the selection, so a stale bin does not
|
||||
// stick around after the histogram underneath changed
|
||||
if (_selected != null && _selected! >= histogram.counts.length) {
|
||||
_selected = null;
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
SizedBox(height: 20, child: _readout(histogram, theme)),
|
||||
Expanded(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final layout = _DistributionLayout(constraints.biggest, histogram.counts.length);
|
||||
|
||||
return GestureDetector(
|
||||
onTapDown: (details) {
|
||||
final bin = layout.binAt(details.localPosition, histogram.counts.length);
|
||||
setState(() => _selected = bin == _selected ? null : bin);
|
||||
},
|
||||
child: CustomPaint(
|
||||
size: constraints.biggest,
|
||||
painter: _DistributionPainter(
|
||||
histogram: histogram,
|
||||
layout: layout,
|
||||
selected: _selected,
|
||||
bar: theme.colorScheme.primary,
|
||||
median: theme.colorScheme.tertiary,
|
||||
latest: theme.colorScheme.secondary,
|
||||
grid: theme.colorScheme.outlineVariant,
|
||||
outline: theme.colorScheme.outline,
|
||||
labelStyle:
|
||||
theme.textTheme.bodySmall?.copyWith(fontSize: 9) ??
|
||||
const TextStyle(fontSize: 9),
|
||||
formatValue: (value) => measurementValue(context, value, widget.unit),
|
||||
formatCount: (count) => localizedNumberFormat(context).format(count),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// The line above the bars: the tapped bin as its range and count, or the
|
||||
/// median and newest value while nothing is selected, coloured like their
|
||||
/// marker lines so the numbers say what the lines only place.
|
||||
Widget _readout(MeasurementHistogram histogram, ThemeData theme) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final selected = _selected;
|
||||
|
||||
if (selected != null) {
|
||||
final count = histogram.counts[selected];
|
||||
return Text(
|
||||
'${measurementValue(context, histogram.lowerEdgeOf(selected), widget.unit)}'
|
||||
'-${measurementWithUnit(context, histogram.upperEdgeOf(selected), widget.unit)}: '
|
||||
'${widget.countsAreDays ? l10n.distributionDayCount(count) : l10n.distributionEntryCount(count)}',
|
||||
style: theme.textTheme.bodySmall,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
);
|
||||
}
|
||||
|
||||
return Text.rich(
|
||||
TextSpan(
|
||||
style: theme.textTheme.bodySmall,
|
||||
children: [
|
||||
TextSpan(
|
||||
text:
|
||||
'${l10n.distributionMedian}: '
|
||||
'${measurementWithUnit(context, histogram.median, widget.unit)}',
|
||||
style: TextStyle(color: theme.colorScheme.tertiary),
|
||||
),
|
||||
const TextSpan(text: ' · '),
|
||||
TextSpan(
|
||||
text:
|
||||
'${l10n.distributionLatest}: '
|
||||
'${measurementWithUnit(context, histogram.latest, widget.unit)}',
|
||||
style: TextStyle(color: theme.colorScheme.secondary),
|
||||
),
|
||||
],
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the bars of a histogram sit, shared by the painter and the hit test
|
||||
/// so a tap lands on the bin it looks like it lands on.
|
||||
class _DistributionLayout {
|
||||
/// Room for the count labels on the left and the edge labels below.
|
||||
static const countLabelWidth = 30.0;
|
||||
static const edgeLabelHeight = 14.0;
|
||||
|
||||
final double left;
|
||||
final double plotWidth;
|
||||
final double plotHeight;
|
||||
|
||||
/// Width of one bin on screen, gap included.
|
||||
final double step;
|
||||
|
||||
factory _DistributionLayout(Size size, int bins) {
|
||||
final plotWidth = max(1.0, size.width - countLabelWidth);
|
||||
return _DistributionLayout._(
|
||||
left: countLabelWidth,
|
||||
plotWidth: plotWidth,
|
||||
plotHeight: max(1.0, size.height - edgeLabelHeight),
|
||||
step: plotWidth / max(bins, 1),
|
||||
);
|
||||
}
|
||||
|
||||
const _DistributionLayout._({
|
||||
required this.left,
|
||||
required this.plotWidth,
|
||||
required this.plotHeight,
|
||||
required this.step,
|
||||
});
|
||||
|
||||
double xOfEdge(num edge) => left + edge * step;
|
||||
|
||||
/// The bin at [position], null when the tap missed the bars.
|
||||
int? binAt(Offset position, int bins) {
|
||||
final bin = ((position.dx - left) / step).floor();
|
||||
if (bin < 0 || bin >= bins || position.dy > plotHeight) {
|
||||
return null;
|
||||
}
|
||||
return bin;
|
||||
}
|
||||
}
|
||||
|
||||
class _DistributionPainter extends CustomPainter {
|
||||
final MeasurementHistogram histogram;
|
||||
final _DistributionLayout layout;
|
||||
final int? selected;
|
||||
final Color bar;
|
||||
final Color median;
|
||||
final Color latest;
|
||||
final Color grid;
|
||||
final Color outline;
|
||||
final TextStyle labelStyle;
|
||||
final String Function(num) formatValue;
|
||||
final String Function(int) formatCount;
|
||||
|
||||
_DistributionPainter({
|
||||
required this.histogram,
|
||||
required this.layout,
|
||||
required this.selected,
|
||||
required this.bar,
|
||||
required this.median,
|
||||
required this.latest,
|
||||
required this.grid,
|
||||
required this.outline,
|
||||
required this.labelStyle,
|
||||
required this.formatValue,
|
||||
required this.formatCount,
|
||||
});
|
||||
|
||||
/// Number of labelled gridlines and bin edges the chart aims for.
|
||||
static const _tickCount = 4;
|
||||
|
||||
/// The x pixel of [value] on the value axis the bins tile.
|
||||
double _xOf(num value) => layout.xOfEdge((value - histogram.firstEdge) / histogram.binWidth);
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final counts = histogram.counts;
|
||||
final maxCount = counts.max;
|
||||
|
||||
// The count axis climbs in round steps, and its top is the tick strictly
|
||||
// above the tallest bin, so the tallest bar keeps headroom instead of
|
||||
// ending flush at the canvas edge
|
||||
final interval = max(1, niceBinWidth(0, maxCount, targetBins: _tickCount)).toInt();
|
||||
final top = (maxCount ~/ interval + 1) * interval;
|
||||
double yOf(num count) => layout.plotHeight * (1 - count / top);
|
||||
|
||||
final gridPaint = Paint()
|
||||
..color = grid
|
||||
..strokeWidth = 1;
|
||||
const countLabelRight = _DistributionLayout.countLabelWidth - 4;
|
||||
for (var tick = 0; tick <= top; tick += interval) {
|
||||
final y = yOf(tick);
|
||||
canvas.drawLine(Offset(layout.left, y), Offset(layout.left + layout.plotWidth, y), gridPaint);
|
||||
if (tick > 0) {
|
||||
// Right-aligned against the plot, centred on its gridline
|
||||
final label = _layoutLabel(formatCount(tick), maxWidth: countLabelRight);
|
||||
label.paint(canvas, Offset(countLabelRight - label.width, y - label.height / 2));
|
||||
}
|
||||
}
|
||||
|
||||
// The gap follows the bin width on screen, like the bar charts leave a
|
||||
// gap between neighbouring bars but never go below a hairline
|
||||
final gap = (layout.step * 0.15).clamp(0.5, 2.0);
|
||||
final barPaint = Paint()..color = bar;
|
||||
for (final (bin, count) in counts.indexed) {
|
||||
if (count == 0) {
|
||||
continue;
|
||||
}
|
||||
final rect = Rect.fromLTRB(
|
||||
layout.xOfEdge(bin) + gap / 2,
|
||||
yOf(count),
|
||||
layout.xOfEdge(bin + 1) - gap / 2,
|
||||
layout.plotHeight,
|
||||
);
|
||||
canvas.drawRect(rect, barPaint);
|
||||
|
||||
if (bin == selected) {
|
||||
canvas.drawRect(
|
||||
rect,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.5
|
||||
..color = outline,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// The markers sit at the exact value, not on a bin: that precision is why
|
||||
// the histogram is painted by hand
|
||||
_paintMarker(canvas, histogram.median, median);
|
||||
_paintMarker(canvas, histogram.latest, latest, tipped: true);
|
||||
|
||||
_paintEdgeLabels(canvas, size, counts.length);
|
||||
}
|
||||
|
||||
/// A vertical line at [value], with a small tip for the marker that means a
|
||||
/// single point rather than a summary, so the two stay apart when they
|
||||
/// coincide.
|
||||
void _paintMarker(Canvas canvas, num value, Color color, {bool tipped = false}) {
|
||||
final x = _xOf(value);
|
||||
canvas.drawLine(
|
||||
Offset(x, 0),
|
||||
Offset(x, layout.plotHeight),
|
||||
Paint()
|
||||
..color = color
|
||||
..strokeWidth = 1.5,
|
||||
);
|
||||
|
||||
if (tipped) {
|
||||
canvas.drawPath(
|
||||
Path()
|
||||
..moveTo(x - 4, 0)
|
||||
..lineTo(x + 4, 0)
|
||||
..lineTo(x, 6)
|
||||
..close(),
|
||||
Paint()..color = color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every k-th bin edge, labelled with its value: the edges are the round
|
||||
/// numbers the bins were aligned to, so they are the natural ticks.
|
||||
void _paintEdgeLabels(Canvas canvas, Size size, int bins) {
|
||||
final labelEvery = max(1, (bins / _tickCount).ceil());
|
||||
for (var edge = 0; edge <= bins; edge += labelEvery) {
|
||||
final label = _layoutLabel(
|
||||
formatValue(histogram.lowerEdgeOf(edge)),
|
||||
maxWidth: layout.step * labelEvery,
|
||||
);
|
||||
// Centred on its edge, but kept inside the canvas
|
||||
final x = (layout.xOfEdge(edge) - label.width / 2).clamp(0.0, size.width - label.width);
|
||||
label.paint(canvas, Offset(x, layout.plotHeight + 2));
|
||||
}
|
||||
}
|
||||
|
||||
/// Lays [text] out as a single unwrapped line; the call sites position it.
|
||||
TextPainter _layoutLabel(String text, {required double maxWidth}) => TextPainter(
|
||||
text: TextSpan(text: text, style: labelStyle),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '',
|
||||
)..layout(maxWidth: maxWidth);
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_DistributionPainter oldDelegate) =>
|
||||
oldDelegate.selected != selected || oldDelegate.histogram != histogram;
|
||||
}
|
||||
433
lib/features/measurements/widgets/charts/heatmap_chart.dart
Normal file
433
lib/features/measurements/widgets/charts/heatmap_chart.dart
Normal file
@@ -0,0 +1,433 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2020 - 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:wger/core/formatting/formatting.dart';
|
||||
import 'package:wger/features/measurements/widgets/charts/chart_series.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
/// A calendar heatmap laid out as a grid of week columns and weekday rows,
|
||||
/// with the values it draws.
|
||||
///
|
||||
/// Days are addressed by their position in the grid, so nothing downstream has
|
||||
/// to do calendar arithmetic: column 0 row 0 is [start], which is always a
|
||||
/// Monday.
|
||||
class MeasurementHeatmapGrid {
|
||||
/// Monday of the first (oldest) week column.
|
||||
final DateTime start;
|
||||
|
||||
/// Number of week columns.
|
||||
final int weeks;
|
||||
|
||||
/// Value of each day the grid shows that has one, keyed by the day at
|
||||
/// midnight. Days outside the window are not part of this chart and are left
|
||||
/// out, see [buildHeatmapGrid].
|
||||
final Map<DateTime, num> values;
|
||||
|
||||
/// Largest value in [values], the top of the colour scale. Zero for an empty
|
||||
/// grid, and for a history that holds nothing but zeroes.
|
||||
final num maxValue;
|
||||
|
||||
const MeasurementHeatmapGrid({
|
||||
required this.start,
|
||||
required this.weeks,
|
||||
required this.values,
|
||||
required this.maxValue,
|
||||
});
|
||||
|
||||
/// The day in column [week], row [weekday] (0 = Monday).
|
||||
DateTime dayAt(int week, int weekday) =>
|
||||
DateTime(start.year, start.month, start.day + week * 7 + weekday);
|
||||
|
||||
/// The value of that day, null when nothing was measured on it. That is the
|
||||
/// distinction the chart exists for, so it is kept apart from a zero.
|
||||
num? valueAt(int week, int weekday) => values[dayAt(week, weekday)];
|
||||
}
|
||||
|
||||
/// Widest a heatmap gets, in week columns.
|
||||
///
|
||||
/// A year is where the grid stops being readable: 53 columns already put the
|
||||
/// cells at a few pixels each, and a history of several years would be a wall
|
||||
/// rather than a chart. The range selector above the chart can go further
|
||||
/// (all-time), so the heatmap caps itself here; the month labels along the top
|
||||
/// say which span is actually drawn.
|
||||
const heatmapMaxWeeks = 53;
|
||||
|
||||
/// Lays [days] out as a calendar grid, newest week last.
|
||||
///
|
||||
/// Expects one entry per calendar day (see [aggregatePerDay] and
|
||||
/// [averagePerDay]). The grid ends with the current week, so a stretch without
|
||||
/// measurements at the end stays visible as empty cells; only a history that
|
||||
/// ended longer ago than the grid is wide is anchored at its own last day
|
||||
/// instead, since an empty grid shows nothing at all.
|
||||
MeasurementHeatmapGrid buildHeatmapGrid(
|
||||
List<MeasurementChartEntry> days, {
|
||||
int maxWeeks = heatmapMaxWeeks,
|
||||
DateTime? today,
|
||||
}) {
|
||||
// Calendar arithmetic, not Duration: a DST day is 23 or 25 hours long
|
||||
DateTime dayOf(DateTime date) => DateTime(date.year, date.month, date.day);
|
||||
DateTime shift(DateTime day, int days) => DateTime(day.year, day.month, day.day + days);
|
||||
DateTime mondayOf(DateTime date) => shift(date, -(date.weekday - 1));
|
||||
int daysBetween(DateTime from, DateTime to) => DateTime.utc(
|
||||
to.year,
|
||||
to.month,
|
||||
to.day,
|
||||
).difference(DateTime.utc(from.year, from.month, from.day)).inDays;
|
||||
|
||||
final values = {for (final day in days) dayOf(day.date): day.value};
|
||||
final now = dayOf(today ?? DateTime.now());
|
||||
|
||||
if (values.isEmpty) {
|
||||
return MeasurementHeatmapGrid(
|
||||
start: shift(mondayOf(now), -7 * (maxWeeks - 1)),
|
||||
weeks: maxWeeks,
|
||||
values: const {},
|
||||
maxValue: 0,
|
||||
);
|
||||
}
|
||||
|
||||
final first = values.keys.reduce((a, b) => a.isBefore(b) ? a : b);
|
||||
final last = values.keys.reduce((a, b) => a.isAfter(b) ? a : b);
|
||||
final oldestVisible = shift(mondayOf(now), -7 * (maxWeeks - 1));
|
||||
final end = mondayOf(last).isBefore(oldestVisible) ? last : now;
|
||||
|
||||
final endMonday = mondayOf(end);
|
||||
final weeks = min(maxWeeks, daysBetween(mondayOf(first), endMonday) ~/ 7 + 1);
|
||||
final start = shift(endMonday, -7 * (weeks - 1));
|
||||
final lastDay = shift(start, 7 * weeks - 1);
|
||||
|
||||
// Only the days the grid actually shows. A history longer than the grid is
|
||||
// wide keeps its older days out of the window, and a spike among them would
|
||||
// otherwise set the top of the colour scale without being visible itself,
|
||||
// washing out every cell that is
|
||||
final visible = {
|
||||
for (final MapEntry(key: day, value: value) in values.entries)
|
||||
if (!day.isBefore(start) && !day.isAfter(lastDay)) day: value,
|
||||
};
|
||||
|
||||
return MeasurementHeatmapGrid(
|
||||
start: start,
|
||||
weeks: weeks,
|
||||
values: visible,
|
||||
maxValue: visible.isEmpty ? 0 : visible.values.max,
|
||||
);
|
||||
}
|
||||
|
||||
/// Calendar heatmap: one cell per day, coloured by that day's value.
|
||||
///
|
||||
/// Where a line or a bar answers how much, this answers how regularly, which
|
||||
/// for steps or sleep is often the more interesting question. It is also the
|
||||
/// only chart of the set where a gap is visible: a day without a measurement
|
||||
/// is an empty cell instead of a line segment that silently spans it.
|
||||
///
|
||||
/// Takes one entry per calendar day; how a day's readings became that value
|
||||
/// (summed, averaged) is decided by the caller, see [aggregatePerDay] and
|
||||
/// [averagePerDay].
|
||||
class MeasurementHeatmapWidgetFl extends StatefulWidget {
|
||||
/// One entry per calendar day, see [aggregatePerDay] and [averagePerDay].
|
||||
final List<MeasurementChartEntry> days;
|
||||
final String unit;
|
||||
|
||||
const MeasurementHeatmapWidgetFl(this.days, this.unit, {super.key});
|
||||
|
||||
@override
|
||||
State<MeasurementHeatmapWidgetFl> createState() => _MeasurementHeatmapWidgetFlState();
|
||||
}
|
||||
|
||||
class _MeasurementHeatmapWidgetFlState extends State<MeasurementHeatmapWidgetFl> {
|
||||
/// Day the user tapped, read out above the grid. A heatmap has no axis to
|
||||
/// read a value off, so this is what the tooltip is on the other charts.
|
||||
DateTime? _selected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final grid = buildHeatmapGrid(widget.days);
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 20,
|
||||
child: Text(
|
||||
_readout(grid),
|
||||
style: theme.textTheme.bodySmall,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final layout = _HeatmapLayout(constraints.biggest, grid.weeks);
|
||||
|
||||
return GestureDetector(
|
||||
onTapDown: (details) {
|
||||
final day = layout.dayAt(details.localPosition, grid);
|
||||
setState(() => _selected = day == _selected ? null : day);
|
||||
},
|
||||
child: CustomPaint(
|
||||
size: constraints.biggest,
|
||||
painter: _HeatmapPainter(
|
||||
grid: grid,
|
||||
layout: layout,
|
||||
selected: _selected,
|
||||
filled: theme.colorScheme.primary,
|
||||
empty: theme.colorScheme.surfaceContainerHighest,
|
||||
outline: theme.colorScheme.outline,
|
||||
labelStyle:
|
||||
theme.textTheme.bodySmall?.copyWith(fontSize: 9) ??
|
||||
const TextStyle(fontSize: 9),
|
||||
locale: Localizations.localeOf(context).toString(),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// The line above the grid: the tapped day, or the span the grid covers
|
||||
/// while nothing is selected.
|
||||
String _readout(MeasurementHeatmapGrid grid) {
|
||||
final dateFormat = localizedDate(context);
|
||||
final selected = _selected;
|
||||
if (selected == null) {
|
||||
// The grid is whole weeks and its last one usually runs past today, so
|
||||
// the span it covers ends today rather than on that Sunday
|
||||
final today = DateTime.now();
|
||||
final last = grid.dayAt(grid.weeks - 1, DateTime.daysPerWeek - 1);
|
||||
final end = last.isAfter(today) ? today : last;
|
||||
return '${dateFormat.format(grid.start)} - ${dateFormat.format(end)}';
|
||||
}
|
||||
|
||||
final value = grid.values[selected];
|
||||
if (value == null) {
|
||||
return '${dateFormat.format(selected)}: ${AppLocalizations.of(context).noDataAvailable}';
|
||||
}
|
||||
|
||||
return '${dateFormat.format(selected)}: '
|
||||
'${measurementWithUnit(context, value, widget.unit)}';
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the cells of a heatmap sit, shared by the painter and the hit test so
|
||||
/// a tap lands on the cell it looks like it lands on.
|
||||
class _HeatmapLayout {
|
||||
/// Room for the weekday labels on the left and the month labels on top.
|
||||
static const weekdayLabelWidth = 22.0;
|
||||
static const monthLabelHeight = 12.0;
|
||||
|
||||
/// Smallest a cell and its gap may get before the grid is unreadable rather
|
||||
/// than merely dense.
|
||||
static const minCell = 4.0;
|
||||
|
||||
final double step;
|
||||
final double cell;
|
||||
final double left;
|
||||
final double top;
|
||||
|
||||
factory _HeatmapLayout(Size size, int weeks) {
|
||||
final available = Size(
|
||||
size.width - weekdayLabelWidth,
|
||||
size.height - monthLabelHeight,
|
||||
);
|
||||
// Square cells, so the grid keeps the calendar's proportions whatever box
|
||||
// it is given. A year of columns is limited by the width, a quarter by the
|
||||
// height
|
||||
final step = max(
|
||||
minCell,
|
||||
min(available.width / max(weeks, 1), available.height / DateTime.daysPerWeek),
|
||||
);
|
||||
// The gap follows the cell size: a fixed one is a hairline on a wide grid
|
||||
// and half the cell on a year of columns, where it turns the squares into
|
||||
// scattered dots
|
||||
final gap = (step * 0.18).clamp(1.0, 3.0);
|
||||
|
||||
return _HeatmapLayout._(
|
||||
step: step,
|
||||
cell: step - gap,
|
||||
left: weekdayLabelWidth,
|
||||
// A year of columns is wider than it is tall, so it would otherwise sit
|
||||
// against the top edge with the rest of the box empty below it
|
||||
top: monthLabelHeight + max(0.0, available.height - step * DateTime.daysPerWeek) / 2,
|
||||
);
|
||||
}
|
||||
|
||||
const _HeatmapLayout._({
|
||||
required this.step,
|
||||
required this.cell,
|
||||
required this.left,
|
||||
required this.top,
|
||||
});
|
||||
|
||||
Offset originOf(int week, int weekday) => Offset(left + week * step, top + weekday * step);
|
||||
|
||||
/// The day at [position], null when the tap missed the grid.
|
||||
DateTime? dayAt(Offset position, MeasurementHeatmapGrid grid) {
|
||||
final week = ((position.dx - left) / step).floor();
|
||||
final weekday = ((position.dy - top) / step).floor();
|
||||
if (week < 0 || week >= grid.weeks || weekday < 0 || weekday >= DateTime.daysPerWeek) {
|
||||
return null;
|
||||
}
|
||||
return grid.dayAt(week, weekday);
|
||||
}
|
||||
}
|
||||
|
||||
class _HeatmapPainter extends CustomPainter {
|
||||
final MeasurementHeatmapGrid grid;
|
||||
final _HeatmapLayout layout;
|
||||
final DateTime? selected;
|
||||
final Color filled;
|
||||
final Color empty;
|
||||
final Color outline;
|
||||
final TextStyle labelStyle;
|
||||
final String locale;
|
||||
|
||||
_HeatmapPainter({
|
||||
required this.grid,
|
||||
required this.layout,
|
||||
required this.selected,
|
||||
required this.filled,
|
||||
required this.empty,
|
||||
required this.outline,
|
||||
required this.labelStyle,
|
||||
required this.locale,
|
||||
});
|
||||
|
||||
/// Colour of a cell holding [value].
|
||||
///
|
||||
/// A day without a measurement is neutral, everything else is tinted by how
|
||||
/// large its value is within the grid. The scale is continuous and starts
|
||||
/// well above transparent: a day that was measured has to read as measured
|
||||
/// even when its value is the smallest one.
|
||||
Color _cellColor(num? value) {
|
||||
if (value == null) {
|
||||
return empty;
|
||||
}
|
||||
final share = grid.maxValue <= 0 ? 1.0 : (value / grid.maxValue).clamp(0.0, 1.0);
|
||||
return Color.lerp(filled.withValues(alpha: 0.3), filled, share)!;
|
||||
}
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final paint = Paint()..style = PaintingStyle.fill;
|
||||
final today = DateTime.now();
|
||||
final endOfToday = DateTime(today.year, today.month, today.day);
|
||||
|
||||
for (var week = 0; week < grid.weeks; week++) {
|
||||
for (var weekday = 0; weekday < DateTime.daysPerWeek; weekday++) {
|
||||
final day = grid.dayAt(week, weekday);
|
||||
// The grid is whole weeks, so the last one runs past today. Those days
|
||||
// have not happened yet and are left blank rather than drawn as a gap
|
||||
if (day.isAfter(endOfToday)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final rect = RRect.fromRectAndRadius(
|
||||
layout.originOf(week, weekday) & Size(layout.cell, layout.cell),
|
||||
// Rounded, but never so much that a small cell becomes a dot
|
||||
Radius.circular(min(2, layout.cell / 4)),
|
||||
);
|
||||
canvas.drawRRect(rect, paint..color = _cellColor(grid.valueAt(week, weekday)));
|
||||
|
||||
if (day == selected) {
|
||||
canvas.drawRRect(
|
||||
rect,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.5
|
||||
..color = outline,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_paintWeekdayLabels(canvas);
|
||||
_paintMonthLabels(canvas);
|
||||
}
|
||||
|
||||
/// Every other weekday, the way a calendar heatmap is usually labelled:
|
||||
/// naming all seven needs more room than the rows have.
|
||||
void _paintWeekdayLabels(Canvas canvas) {
|
||||
final format = DateFormat.E(locale);
|
||||
for (var weekday = 0; weekday < DateTime.daysPerWeek; weekday += 2) {
|
||||
final origin = layout.originOf(0, weekday);
|
||||
_paintText(
|
||||
canvas,
|
||||
format.format(grid.dayAt(0, weekday)),
|
||||
Offset(0, origin.dy + layout.cell / 2),
|
||||
maxWidth: _HeatmapLayout.weekdayLabelWidth - 2,
|
||||
centered: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The month above the column it starts in, which is what says where in the
|
||||
/// year the grid is without a date axis.
|
||||
void _paintMonthLabels(Canvas canvas) {
|
||||
final format = DateFormat.MMM(locale);
|
||||
var previous = -1;
|
||||
for (var week = 0; week < grid.weeks; week++) {
|
||||
final month = grid.dayAt(week, 0).month;
|
||||
if (month == previous) {
|
||||
continue;
|
||||
}
|
||||
previous = month;
|
||||
_paintText(
|
||||
canvas,
|
||||
format.format(grid.dayAt(week, 0)),
|
||||
// Sits right above the first column of the month
|
||||
Offset(
|
||||
layout.originOf(week, 0).dx,
|
||||
layout.top - _HeatmapLayout.monthLabelHeight,
|
||||
),
|
||||
maxWidth: layout.step * 4,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws [text] at [at], which is its top left corner or, with [centered],
|
||||
/// the middle of its left edge.
|
||||
void _paintText(
|
||||
Canvas canvas,
|
||||
String text,
|
||||
Offset at, {
|
||||
required double maxWidth,
|
||||
bool centered = false,
|
||||
}) {
|
||||
final painter = TextPainter(
|
||||
text: TextSpan(text: text, style: labelStyle),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '',
|
||||
)..layout(maxWidth: maxWidth);
|
||||
painter.paint(canvas, centered ? at.translate(0, -painter.height / 2) : at);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_HeatmapPainter oldDelegate) =>
|
||||
oldDelegate.selected != selected || oldDelegate.grid != grid;
|
||||
}
|
||||
327
test/features/measurements/widgets/charts/chart_series_test.dart
Normal file
327
test/features/measurements/widgets/charts/chart_series_test.dart
Normal file
@@ -0,0 +1,327 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:wger/features/measurements/widgets/charts/chart_series.dart';
|
||||
|
||||
void main() {
|
||||
MeasurementChartEntry entry(num value, DateTime date) => MeasurementChartEntry(value, date);
|
||||
|
||||
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('clampPeriods', () {
|
||||
final bounds = DateTimeRange(start: DateTime(2026, 1, 10), end: DateTime(2026, 1, 20));
|
||||
|
||||
test('keeps a period inside the bounds untouched', () {
|
||||
final period = DateTimeRange(start: DateTime(2026, 1, 12), end: DateTime(2026, 1, 15));
|
||||
expect(clampPeriods([period], bounds), [period]);
|
||||
});
|
||||
|
||||
test('clamps overlapping periods to the bounds', () {
|
||||
final result = clampPeriods([
|
||||
DateTimeRange(start: DateTime(2026, 1, 1), end: DateTime(2026, 1, 12)),
|
||||
DateTimeRange(start: DateTime(2026, 1, 15), end: DateTime(2026, 2, 1)),
|
||||
], bounds);
|
||||
|
||||
expect(result, [
|
||||
DateTimeRange(start: DateTime(2026, 1, 10), end: DateTime(2026, 1, 12)),
|
||||
DateTimeRange(start: DateTime(2026, 1, 15), end: DateTime(2026, 1, 20)),
|
||||
]);
|
||||
});
|
||||
|
||||
test('drops periods outside the bounds, including touching ones', () {
|
||||
final result = clampPeriods([
|
||||
DateTimeRange(start: DateTime(2026, 1, 1), end: DateTime(2026, 1, 5)),
|
||||
// ends exactly at the bounds' start: zero width, nothing to draw
|
||||
DateTimeRange(start: DateTime(2026, 1, 1), end: DateTime(2026, 1, 10)),
|
||||
DateTimeRange(start: DateTime(2026, 2, 1), end: DateTime(2026, 2, 5)),
|
||||
], bounds);
|
||||
|
||||
expect(result, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('movingAverage', () {
|
||||
test('returns an empty list for no entries', () {
|
||||
expect(movingAverage([]), isEmpty);
|
||||
});
|
||||
|
||||
test('averages over everything within the preceding 7 days', () {
|
||||
final result = movingAverage([
|
||||
entry(10, DateTime(2026, 1, 1)),
|
||||
entry(20, DateTime(2026, 1, 2)),
|
||||
entry(30, DateTime(2026, 1, 3)),
|
||||
]);
|
||||
|
||||
expect(result.map((e) => e.value), [10, 15, 20]);
|
||||
expect(result.map((e) => e.date), [
|
||||
DateTime(2026, 1, 1),
|
||||
DateTime(2026, 1, 2),
|
||||
DateTime(2026, 1, 3),
|
||||
]);
|
||||
});
|
||||
|
||||
test('drops points that fell out of the window', () {
|
||||
final result = movingAverage([
|
||||
entry(10, DateTime(2026, 1, 1)),
|
||||
entry(20, DateTime(2026, 1, 20)),
|
||||
]);
|
||||
|
||||
// the january 1st entry is far outside the 7 days before january 20th
|
||||
expect(result.last.value, 20);
|
||||
});
|
||||
|
||||
test('sorts unordered input by date first', () {
|
||||
final result = movingAverage([
|
||||
entry(30, DateTime(2026, 1, 3)),
|
||||
entry(10, DateTime(2026, 1, 1)),
|
||||
entry(20, DateTime(2026, 1, 2)),
|
||||
]);
|
||||
|
||||
expect(result.map((e) => e.value), [10, 15, 20]);
|
||||
});
|
||||
|
||||
test('stays accurate over a long dense series', () {
|
||||
// The window total is carried along rather than re-summed, so this
|
||||
// guards against drift piling up
|
||||
final result = movingAverage([
|
||||
for (var i = 0; i < 5000; i++) entry(100, DateTime(2026, 1, 1).add(Duration(minutes: i))),
|
||||
]);
|
||||
|
||||
expect(result.every((e) => (e.value - 100).abs() < 0.000001), isTrue);
|
||||
});
|
||||
|
||||
test('a wider window reaches further back', () {
|
||||
final points = [
|
||||
entry(10, DateTime(2026, 1, 1)),
|
||||
entry(20, DateTime(2026, 1, 12)),
|
||||
];
|
||||
|
||||
// the january 1st entry is outside 7 days but inside 14
|
||||
expect(movingAverage(points, days: 7).last.value, 20);
|
||||
expect(movingAverage(points, days: 14).last.value, 15);
|
||||
});
|
||||
});
|
||||
|
||||
group('aggregatePerDay', () {
|
||||
test('returns an empty list for no entries', () {
|
||||
expect(aggregatePerDay([]), isEmpty);
|
||||
});
|
||||
|
||||
test('sums entries sharing a calendar day into one point', () {
|
||||
final result = aggregatePerDay([
|
||||
entry(1000, DateTime(2026, 1, 1, 8)),
|
||||
entry(2500, DateTime(2026, 1, 1, 20)),
|
||||
]);
|
||||
|
||||
expect(result.length, 1);
|
||||
expect(result.single.value, 3500);
|
||||
// time-of-day is stripped to the day boundary
|
||||
expect(result.single.date, DateTime(2026, 1, 1));
|
||||
});
|
||||
|
||||
test('keeps separate days apart and sorts them ascending', () {
|
||||
final result = aggregatePerDay([
|
||||
entry(30, DateTime(2026, 1, 3)),
|
||||
entry(10, DateTime(2026, 1, 1, 6)),
|
||||
entry(5, DateTime(2026, 1, 1, 23)),
|
||||
entry(20, DateTime(2026, 1, 2)),
|
||||
]);
|
||||
|
||||
expect(result.map((e) => e.date), [
|
||||
DateTime(2026, 1, 1),
|
||||
DateTime(2026, 1, 2),
|
||||
DateTime(2026, 1, 3),
|
||||
]);
|
||||
expect(result.map((e) => e.value), [15, 20, 30]);
|
||||
});
|
||||
});
|
||||
|
||||
group('averagePerDay', () {
|
||||
test('returns an empty list for no entries', () {
|
||||
expect(averagePerDay([]), isEmpty);
|
||||
});
|
||||
|
||||
test('averages entries sharing a calendar day into one point', () {
|
||||
final result = averagePerDay([
|
||||
entry(80, DateTime(2026, 1, 1, 8)),
|
||||
entry(82, DateTime(2026, 1, 1, 20)),
|
||||
]);
|
||||
|
||||
expect(result.single.value, 81);
|
||||
expect(result.single.date, DateTime(2026, 1, 1));
|
||||
});
|
||||
|
||||
test('keeps separate days apart and sorts them ascending', () {
|
||||
final result = averagePerDay([
|
||||
entry(30, DateTime(2026, 1, 3)),
|
||||
entry(10, DateTime(2026, 1, 1)),
|
||||
entry(20, DateTime(2026, 1, 2)),
|
||||
]);
|
||||
|
||||
expect(result.map((e) => e.date), [
|
||||
DateTime(2026, 1, 1),
|
||||
DateTime(2026, 1, 2),
|
||||
DateTime(2026, 1, 3),
|
||||
]);
|
||||
expect(result.map((e) => e.value), [10, 20, 30]);
|
||||
});
|
||||
});
|
||||
|
||||
group('weeklyDeltas', () {
|
||||
// 5 January 2026 is a Monday
|
||||
final monday = DateTime(2026, 1, 5);
|
||||
DateTime week(int index) => monday.add(Duration(days: 7 * index));
|
||||
|
||||
test('returns an empty list for no entries', () {
|
||||
expect(weeklyDeltas([]), isEmpty);
|
||||
});
|
||||
|
||||
test('has no bar for a single week, which has nothing to compare against', () {
|
||||
expect(
|
||||
weeklyDeltas([entry(80, monday), entry(81, monday.add(const Duration(days: 2)))]),
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test('subtracts the previous week, dated on the week it belongs to', () {
|
||||
final result = weeklyDeltas([
|
||||
entry(80, monday),
|
||||
entry(79, week(1)),
|
||||
entry(79.5, week(2)),
|
||||
]);
|
||||
|
||||
expect(result.map((e) => e.date), [week(1), week(2)]);
|
||||
expect(result.map((e) => e.value), [-1, 0.5]);
|
||||
});
|
||||
|
||||
test('compares the weeks by their average, not by single readings', () {
|
||||
// the low reading is an outlier within its week and must not decide the bar
|
||||
final result = weeklyDeltas([
|
||||
entry(80, monday),
|
||||
entry(82, monday.add(const Duration(days: 3))),
|
||||
entry(75, week(1)),
|
||||
entry(87, week(1).add(const Duration(days: 3))),
|
||||
]);
|
||||
|
||||
expect(result.single.value, 0);
|
||||
});
|
||||
|
||||
test('sums the weeks of a metric that is read as a total', () {
|
||||
final result = weeklyDeltas([
|
||||
entry(3000, monday),
|
||||
entry(4000, monday.add(const Duration(days: 1))),
|
||||
entry(9000, week(1)),
|
||||
], summed: true);
|
||||
|
||||
expect(result.single.value, 2000);
|
||||
});
|
||||
|
||||
test('takes the week after a gap against the last week that has readings', () {
|
||||
final result = weeklyDeltas([entry(80, monday), entry(77, week(3))]);
|
||||
|
||||
// one bar on the week that was measured, holding the whole change, so the
|
||||
// bars still add up to the change across the range
|
||||
expect(result.single.date, week(3));
|
||||
expect(result.single.value, -3);
|
||||
});
|
||||
|
||||
test('sorts unordered input by week first', () {
|
||||
final result = weeklyDeltas([entry(79, week(1)), entry(80, monday)]);
|
||||
|
||||
expect(result.single.value, -1);
|
||||
});
|
||||
|
||||
test('leaves the running week out of a summed metric', () {
|
||||
// its total is still growing and would read as a drop until Sunday
|
||||
final result = weeklyDeltas(
|
||||
[entry(7000, monday), entry(3000, week(1))],
|
||||
summed: true,
|
||||
today: week(1).add(const Duration(days: 2)),
|
||||
);
|
||||
|
||||
expect(result, isEmpty);
|
||||
});
|
||||
|
||||
test('keeps the running week of an averaged metric', () {
|
||||
final result = weeklyDeltas(
|
||||
[entry(80, monday), entry(79, week(1))],
|
||||
today: week(1).add(const Duration(days: 2)),
|
||||
);
|
||||
|
||||
expect(result.single.value, -1);
|
||||
});
|
||||
});
|
||||
|
||||
group('smoothedTrendline', () {
|
||||
test('returns an empty list for no entries', () {
|
||||
expect(smoothedTrendline([]), isEmpty);
|
||||
});
|
||||
|
||||
test('seeds the first point with the raw value and keeps the dates', () {
|
||||
final input = [
|
||||
entry(10, DateTime(2026, 1, 1)),
|
||||
entry(20, DateTime(2026, 1, 2)),
|
||||
entry(30, DateTime(2026, 1, 3)),
|
||||
];
|
||||
final result = smoothedTrendline(input, period: 10);
|
||||
|
||||
expect(result.length, 3);
|
||||
expect(result.first.value, 10); // seed == first raw value
|
||||
expect(result.map((e) => e.date), input.map((e) => e.date));
|
||||
});
|
||||
|
||||
test('EMA follows a rising series but lags behind the raw values', () {
|
||||
final result = smoothedTrendline([
|
||||
entry(10, DateTime(2026, 1, 1)),
|
||||
entry(20, DateTime(2026, 1, 2)),
|
||||
entry(30, DateTime(2026, 1, 3)),
|
||||
], period: 10);
|
||||
|
||||
// smoothing k = 2 / (10 + 1) ~= 0.1818
|
||||
// point 2: 20*k + 10*(1-k) = 11.818...
|
||||
expect(result[1].value, closeTo(11.818, 0.001));
|
||||
// point 3: 30*k + 11.818*(1-k) = 15.123...
|
||||
expect(result[2].value, closeTo(15.123, 0.001));
|
||||
// trend trails the raw climb
|
||||
expect(result[2].value, lessThan(30));
|
||||
});
|
||||
|
||||
test('sorts unordered input by date before smoothing', () {
|
||||
final result = smoothedTrendline([
|
||||
entry(30, DateTime(2026, 1, 3)),
|
||||
entry(10, DateTime(2026, 1, 1)),
|
||||
entry(20, DateTime(2026, 1, 2)),
|
||||
], period: 10);
|
||||
|
||||
expect(result.first.date, DateTime(2026, 1, 1));
|
||||
expect(result.first.value, 10);
|
||||
expect(result.last.date, DateTime(2026, 1, 3));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:fl_chart/fl_chart.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:wger/features/measurements/widgets/charts/chart_series.dart';
|
||||
import 'package:wger/features/measurements/widgets/charts/chart_widgets.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
Widget _wrap(Widget child) => MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SizedBox(width: 400, height: 300, child: child),
|
||||
),
|
||||
);
|
||||
|
||||
void main() {
|
||||
MeasurementChartEntry entry(num value, DateTime date) => MeasurementChartEntry(value, date);
|
||||
|
||||
group('MeasurementBarChartWidgetFl', () {
|
||||
testWidgets('renders without error for empty entries', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(const MeasurementBarChartWidgetFl([], 'steps')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('BarChart is present for non-empty entries', (tester) async {
|
||||
final entries = [
|
||||
entry(1000, DateTime(2026, 1, 1)),
|
||||
entry(2000, DateTime(2026, 1, 2)),
|
||||
entry(1500, DateTime(2026, 1, 3)),
|
||||
];
|
||||
await tester.pumpWidget(_wrap(MeasurementBarChartWidgetFl(entries, 'steps')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(BarChart), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('only labels a few dates on the x axis', (tester) async {
|
||||
final entries = List.generate(
|
||||
40,
|
||||
(i) => entry(1000 + i, DateTime(2026, 1, 1).add(Duration(days: i))),
|
||||
);
|
||||
await tester.pumpWidget(_wrap(MeasurementBarChartWidgetFl(entries, 'steps')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final dateLabels = find.byWidgetPredicate(
|
||||
(w) => w is Text && RegExp(r'^\d+/\d+$').hasMatch(w.data ?? ''),
|
||||
);
|
||||
expect(dateLabels, findsNWidgets(4));
|
||||
// the labels are spread out and kept away from the axis edges
|
||||
expect(find.text('1/6'), findsOneWidget);
|
||||
expect(find.text('2/5'), findsOneWidget);
|
||||
expect(find.text('1/1'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
group('MeasurementChartWidgetFl series', () {
|
||||
/// The chart data fl_chart actually receives
|
||||
LineChartData chartData(WidgetTester tester) =>
|
||||
tester.widget<LineChart>(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('only the measured series gets a band, not its average', (tester) async {
|
||||
// Condensing attaches a range to every point, so a downsampled average
|
||||
// would otherwise be drawn with a band of its own. The band means "this
|
||||
// is the spread of the measurements", which a smoothed line has not.
|
||||
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),
|
||||
MeasurementChartSeries(ranged, MeasurementSeriesRole.average),
|
||||
MeasurementChartSeries(ranged, MeasurementSeriesRole.trend),
|
||||
], 'bpm'),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(chartData(tester).betweenBarsData, hasLength(1));
|
||||
});
|
||||
|
||||
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('MeasurementChartWidgetFl plan periods', () {
|
||||
LineChartData chartData(WidgetTester tester) =>
|
||||
tester.widget<LineChart>(find.byType(LineChart)).data;
|
||||
|
||||
final points = [
|
||||
entry(60, DateTime(2026, 1, 1)),
|
||||
entry(70, DateTime(2026, 1, 10)),
|
||||
];
|
||||
|
||||
testWidgets('periods become vertical bands clamped to the data', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
MeasurementChartWidgetFl.singleMeasurement(
|
||||
points,
|
||||
'kg',
|
||||
planPeriods: [
|
||||
(
|
||||
range: DateTimeRange(start: DateTime(2025, 12, 20), end: DateTime(2026, 1, 5)),
|
||||
name: 'Cut',
|
||||
),
|
||||
(
|
||||
range: DateTimeRange(start: DateTime(2026, 2, 1), end: DateTime(2026, 2, 10)),
|
||||
name: 'Bulk',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final annotations = chartData(tester).rangeAnnotations.verticalRangeAnnotations;
|
||||
// the february plan does not overlap the data and draws nothing
|
||||
expect(annotations, hasLength(1));
|
||||
expect(annotations.single.x1, DateTime(2026, 1, 1).millisecondsSinceEpoch.toDouble());
|
||||
expect(annotations.single.x2, DateTime(2026, 1, 5).millisecondsSinceEpoch.toDouble());
|
||||
});
|
||||
|
||||
testWidgets('no bands without periods', (tester) async {
|
||||
await tester.pumpWidget(_wrap(MeasurementChartWidgetFl.singleMeasurement(points, 'kg')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(chartData(tester).rangeAnnotations.verticalRangeAnnotations, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('tooltip names the plan once, below the last line', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
MeasurementChartWidgetFl.singleMeasurement(
|
||||
points,
|
||||
'kg',
|
||||
avgs: points,
|
||||
trend: points,
|
||||
planPeriods: [
|
||||
(
|
||||
range: DateTimeRange(start: DateTime(2025, 12, 20), end: DateTime(2026, 1, 5)),
|
||||
name: 'Prep Sommer 2026',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final data = chartData(tester);
|
||||
// a touch on the first point, which every series has a spot for
|
||||
final touched = [
|
||||
for (final (i, bar) in data.lineBarsData.indexed) LineBarSpot(bar, i, bar.spots.first),
|
||||
];
|
||||
final items = data.lineTouchData.touchTooltipData.getTooltipItems(touched).nonNulls.toList();
|
||||
|
||||
expect(items, hasLength(3));
|
||||
final mentions = [
|
||||
for (final item in items) ...?item.children,
|
||||
].whereType<TextSpan>().where((s) => s.text!.contains('Prep Sommer 2026'));
|
||||
expect(mentions, hasLength(1));
|
||||
expect(items.take(2).every((i) => i.children == null || i.children!.isEmpty), isTrue);
|
||||
});
|
||||
|
||||
testWidgets('no plan name for a point outside every period', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
MeasurementChartWidgetFl.singleMeasurement(
|
||||
points,
|
||||
'kg',
|
||||
planPeriods: [
|
||||
(
|
||||
range: DateTimeRange(start: DateTime(2025, 12, 20), end: DateTime(2026, 1, 5)),
|
||||
name: 'Cut',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final data = chartData(tester);
|
||||
// the second point (january 10th) lies after the period's end
|
||||
final touched = [
|
||||
LineBarSpot(data.lineBarsData.single, 0, data.lineBarsData.single.spots.last),
|
||||
];
|
||||
final items = data.lineTouchData.touchTooltipData.getTooltipItems(touched).nonNulls.toList();
|
||||
|
||||
expect(items.single.children, anyOf(isNull, isEmpty));
|
||||
});
|
||||
});
|
||||
|
||||
group('MeasurementBarChartWidgetFl ranges', () {
|
||||
BarChartData chartData(WidgetTester tester) =>
|
||||
tester.widget<BarChart>(find.byType(BarChart)).data;
|
||||
|
||||
testWidgets('a range entry becomes a bar spanning its bounds', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
MeasurementBarChartWidgetFl([
|
||||
MeasurementChartEntry(100, DateTime(2026, 1, 1), min: 80, max: 120),
|
||||
], 'mmHg'),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final rod = chartData(tester).barGroups.single.barRods.single;
|
||||
expect(rod.fromY, 80);
|
||||
expect(rod.toY, 120);
|
||||
});
|
||||
|
||||
testWidgets('a plain entry still grows from zero', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(MeasurementBarChartWidgetFl([entry(1500, DateTime(2026, 1, 1))], 'steps')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final rod = chartData(tester).barGroups.single.barRods.single;
|
||||
expect(rod.fromY, 0);
|
||||
expect(rod.toY, 1500);
|
||||
});
|
||||
|
||||
testWidgets('bars get thinner the more of them share the width', (tester) async {
|
||||
Future<double> barWidthFor(int count) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
MeasurementBarChartWidgetFl(
|
||||
List.generate(count, (i) => entry(100, DateTime(2026, 1, 1).add(Duration(days: i)))),
|
||||
'steps',
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
return chartData(tester).barGroups.first.barRods.single.width;
|
||||
}
|
||||
|
||||
// a handful of bars stay comfortably wide, a season of readings must not
|
||||
// overflow into a solid block
|
||||
expect(await barWidthFor(5), 12.0);
|
||||
expect(await barWidthFor(120), lessThan(4));
|
||||
expect(await barWidthFor(120), greaterThanOrEqualTo(1));
|
||||
});
|
||||
});
|
||||
|
||||
group('MeasurementChartWidgetFl dot size', () {
|
||||
double dotRadius(WidgetTester tester) {
|
||||
final data = tester.widget<LineChart>(find.byType(LineChart)).data;
|
||||
final painter = data.lineBarsData.first.dotData.getDotPainter(
|
||||
FlSpot.zero,
|
||||
0,
|
||||
data.lineBarsData.first,
|
||||
0,
|
||||
);
|
||||
return (painter as FlDotCirclePainter).radius;
|
||||
}
|
||||
|
||||
Future<double> radiusFor(WidgetTester tester, int count) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
MeasurementChartWidgetFl.singleMeasurement(
|
||||
List.generate(count, (i) => entry(60, DateTime(2026, 1, 1).add(Duration(days: i)))),
|
||||
'kg',
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
return dotRadius(tester);
|
||||
}
|
||||
|
||||
testWidgets('dots shrink as the points get denser', (tester) async {
|
||||
expect(await radiusFor(tester, 5), 4.0);
|
||||
expect(await radiusFor(tester, 300), lessThan(1.5));
|
||||
// but never vanish
|
||||
expect(await radiusFor(tester, 5000), greaterThanOrEqualTo(0.5));
|
||||
});
|
||||
});
|
||||
|
||||
group('MeasurementBarChartWidgetFl changes', () {
|
||||
BarChartData chartData(WidgetTester tester) =>
|
||||
tester.widget<BarChart>(find.byType(BarChart)).data;
|
||||
|
||||
Future<BarChartData> pumpSigned(
|
||||
WidgetTester tester,
|
||||
List<MeasurementChartEntry> entries,
|
||||
) async {
|
||||
await tester.pumpWidget(_wrap(MeasurementBarChartWidgetFl(entries, 'kg', signed: true)));
|
||||
await tester.pumpAndSettle();
|
||||
return chartData(tester);
|
||||
}
|
||||
|
||||
testWidgets('a decrease hangs below the zero line, an increase above it', (tester) async {
|
||||
final data = await pumpSigned(tester, [
|
||||
entry(-1.5, DateTime(2026, 1, 5)),
|
||||
entry(0.5, DateTime(2026, 1, 12)),
|
||||
]);
|
||||
|
||||
expect(data.barGroups.map((g) => g.barRods.single.fromY), [0, 0]);
|
||||
expect(data.barGroups.map((g) => g.barRods.single.toY), [-1.5, 0.5]);
|
||||
// the rounded end is the one away from the baseline
|
||||
expect(data.barGroups.first.barRods.single.borderRadius?.bottomLeft, isNot(Radius.zero));
|
||||
expect(data.barGroups.last.barRods.single.borderRadius?.topLeft, isNot(Radius.zero));
|
||||
});
|
||||
|
||||
testWidgets('the two directions are told apart by colour', (tester) async {
|
||||
final data = await pumpSigned(tester, [
|
||||
entry(-1.5, DateTime(2026, 1, 5)),
|
||||
entry(0.5, DateTime(2026, 1, 12)),
|
||||
]);
|
||||
|
||||
final colors = data.barGroups.map((g) => g.barRods.single.color).toList();
|
||||
expect(colors.first, isNot(colors.last));
|
||||
});
|
||||
|
||||
testWidgets('the zero line is drawn, so a chart of only decreases reads right', (
|
||||
tester,
|
||||
) async {
|
||||
final data = await pumpSigned(tester, [entry(-1.5, DateTime(2026, 1, 5))]);
|
||||
|
||||
expect(data.extraLinesData.horizontalLines.single.y, 0);
|
||||
});
|
||||
|
||||
testWidgets('an amount chart has no zero line', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(MeasurementBarChartWidgetFl([entry(1500, DateTime(2026, 1, 5))], 'steps')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(chartData(tester).extraLinesData.horizontalLines, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('the tooltip quotes a change with its sign', (tester) async {
|
||||
await pumpSigned(tester, [entry(0.5, DateTime(2026, 1, 12))]);
|
||||
|
||||
final data = chartData(tester);
|
||||
final rod = data.barGroups.single.barRods.single;
|
||||
final item = data.barTouchData.touchTooltipData.getTooltipItem(
|
||||
data.barGroups.single,
|
||||
0,
|
||||
rod,
|
||||
0,
|
||||
);
|
||||
|
||||
expect(item!.text, contains('+0.5'));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:wger/features/measurements/widgets/charts/distribution_chart.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
Widget _wrap(Widget child) => MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SizedBox(width: 400, height: 300, child: child),
|
||||
),
|
||||
);
|
||||
|
||||
void main() {
|
||||
group('niceBinWidth', () {
|
||||
test('rounds the span split into ~20 bins up to 1, 2 or 5 times a power of ten', () {
|
||||
// span 14.6 / 20 = 0.73 -> 1, not an edge like 59.3-61.3
|
||||
expect(niceBinWidth(59.3, 73.9), 1);
|
||||
// span 30000 / 20 = 1500 -> 2000
|
||||
expect(niceBinWidth(0, 30000), 2000);
|
||||
// span 9 / 20 = 0.45 -> 0.5
|
||||
expect(niceBinWidth(1, 10), 0.5);
|
||||
});
|
||||
|
||||
test('a span of nothing still has a width', () {
|
||||
expect(niceBinWidth(80, 80), 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('buildWeightedHistogram', () {
|
||||
test('counts a value as often as it occurred', () {
|
||||
// What the aggregated query hands over: a year of readings arrives as
|
||||
// the distinct values it covers, with their counts
|
||||
final result = buildWeightedHistogram(
|
||||
[(value: 60, count: 30), (value: 61, count: 5)],
|
||||
latest: 61,
|
||||
binWidth: 1,
|
||||
);
|
||||
|
||||
expect(result.counts, [30, 5]);
|
||||
});
|
||||
|
||||
test('the median weighs the counts, not the distinct values', () {
|
||||
// Thirty readings at 60 and one at 90: the middle reading is a 60, which
|
||||
// an unweighted median over the two values would miss
|
||||
final result = buildWeightedHistogram(
|
||||
[(value: 60, count: 30), (value: 90, count: 1)],
|
||||
latest: 90,
|
||||
binWidth: 10,
|
||||
);
|
||||
|
||||
expect(result.median, 60);
|
||||
});
|
||||
|
||||
test('an even number of readings averages the two in the middle', () {
|
||||
final result = buildWeightedHistogram(
|
||||
[(value: 60, count: 1), (value: 70, count: 1)],
|
||||
latest: 70,
|
||||
binWidth: 10,
|
||||
);
|
||||
|
||||
expect(result.median, 65);
|
||||
});
|
||||
});
|
||||
|
||||
group('buildWeightedHistogram bins', () {
|
||||
test('aligns the bin edges to round multiples of the width', () {
|
||||
final result = buildWeightedHistogram(
|
||||
[
|
||||
(value: 79.7, count: 1),
|
||||
(value: 82.3, count: 1),
|
||||
],
|
||||
latest: 0,
|
||||
binWidth: 0.5,
|
||||
);
|
||||
|
||||
expect(result.firstEdge, 79.5);
|
||||
expect(result.lowerEdgeOf(1), 80);
|
||||
expect(result.upperEdgeOf(result.counts.length - 1), 82.5);
|
||||
});
|
||||
|
||||
test('keeps empty bins between the occupied ones, a gap is information', () {
|
||||
final result = buildWeightedHistogram(
|
||||
[
|
||||
(value: 60, count: 1),
|
||||
(value: 61, count: 1),
|
||||
(value: 65, count: 1),
|
||||
],
|
||||
latest: 0,
|
||||
binWidth: 2,
|
||||
);
|
||||
|
||||
expect(result.counts, [2, 0, 1]);
|
||||
});
|
||||
|
||||
test('takes the median of the values, odd and even', () {
|
||||
final odd = buildWeightedHistogram(
|
||||
[
|
||||
(value: 60, count: 1),
|
||||
(value: 62, count: 1),
|
||||
(value: 70, count: 1),
|
||||
],
|
||||
latest: 0,
|
||||
binWidth: 2,
|
||||
);
|
||||
expect(odd.median, 62);
|
||||
|
||||
final even = buildWeightedHistogram(
|
||||
[
|
||||
(value: 60, count: 1),
|
||||
(value: 63, count: 1),
|
||||
(value: 65, count: 1),
|
||||
(value: 70, count: 1),
|
||||
],
|
||||
latest: 0,
|
||||
binWidth: 2,
|
||||
);
|
||||
expect(even.median, 64);
|
||||
});
|
||||
|
||||
test('derives a width from the span when the type brings none', () {
|
||||
final result = buildWeightedHistogram([
|
||||
(value: 59.3, count: 1),
|
||||
(value: 73.9, count: 1),
|
||||
], latest: 0);
|
||||
|
||||
expect(result.binWidth, 1);
|
||||
});
|
||||
|
||||
test('doubles the width until an outlier no longer stretches it into hundreds of bins', () {
|
||||
// 20 to 350 at 0.5 kg would be 661 bins; doubling keeps the edges round
|
||||
final result = buildWeightedHistogram(
|
||||
[
|
||||
(value: 20, count: 1),
|
||||
(value: 80, count: 1),
|
||||
(value: 350, count: 1),
|
||||
],
|
||||
latest: 0,
|
||||
binWidth: 0.5,
|
||||
);
|
||||
|
||||
expect(result.binWidth, 4);
|
||||
expect(result.counts.length, lessThanOrEqualTo(100));
|
||||
expect(result.counts.sum, 3);
|
||||
});
|
||||
});
|
||||
|
||||
group('MeasurementDistributionWidgetFl', () {
|
||||
const counted = <ValueCount>[
|
||||
(value: 60, count: 1),
|
||||
(value: 61, count: 1),
|
||||
(value: 65, count: 1),
|
||||
];
|
||||
|
||||
testWidgets('renders nothing for no values instead of crashing', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(const MeasurementDistributionWidgetFl([], latest: 0, unit: 'kg')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('reads out the median and the newest value, which the lines only place', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(const MeasurementDistributionWidgetFl(counted, latest: 65, unit: 'kg', binWidth: 2)),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('Median: 61 kg', findRichText: true), findsOneWidget);
|
||||
expect(find.textContaining('Latest: 65 kg', findRichText: true), findsOneWidget);
|
||||
});
|
||||
|
||||
// Mirrors the widget's own layout: the read-out line on top, the count
|
||||
// labels to the left, the bins sharing the rest of the width
|
||||
Offset firstBinCenter(WidgetTester tester, {required int bins}) {
|
||||
const readoutHeight = 20.0;
|
||||
const countLabelWidth = 30.0;
|
||||
final box = tester.getRect(find.byType(MeasurementDistributionWidgetFl));
|
||||
final step = (box.width - countLabelWidth) / bins;
|
||||
return Offset(box.left + countLabelWidth + step / 2, box.top + readoutHeight + 100);
|
||||
}
|
||||
|
||||
testWidgets('a tapped bin reads out as its range and count', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(const MeasurementDistributionWidgetFl(counted, latest: 65, unit: 'kg', binWidth: 2)),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Bins are [60-62): 2, [62-64): 0, [64-66): 1
|
||||
await tester.tapAt(firstBinCenter(tester, bins: 3));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('60-62 kg: 2 entries'), findsOneWidget);
|
||||
|
||||
// Tapping the bin again clears the selection
|
||||
await tester.tapAt(firstBinCenter(tester, bins: 3));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('Median:', findRichText: true), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('counts read as days for a metric summed per day', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
const MeasurementDistributionWidgetFl(
|
||||
counted,
|
||||
latest: 65,
|
||||
unit: 'kg',
|
||||
binWidth: 2,
|
||||
countsAreDays: true,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tapAt(firstBinCenter(tester, bins: 3));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('60-62 kg: 2 days'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2026 wger Team
|
||||
*
|
||||
* wger Workout Manager is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:wger/features/measurements/widgets/charts/chart_series.dart';
|
||||
import 'package:wger/features/measurements/widgets/charts/heatmap_chart.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
Widget _wrap(Widget child) => MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SizedBox(width: 400, height: 300, child: child),
|
||||
),
|
||||
);
|
||||
|
||||
void main() {
|
||||
MeasurementChartEntry entry(num value, DateTime date) => MeasurementChartEntry(value, date);
|
||||
|
||||
group('buildHeatmapGrid', () {
|
||||
// 2 March 2026 is a Monday, 18 March a Wednesday
|
||||
final monday = DateTime(2026, 3, 2);
|
||||
final wednesday = DateTime(2026, 3, 18);
|
||||
|
||||
test('starts on the Monday of the oldest week and ends with today', () {
|
||||
final grid = buildHeatmapGrid(
|
||||
[entry(10, monday), entry(20, wednesday)],
|
||||
today: wednesday,
|
||||
);
|
||||
|
||||
expect(grid.start, monday);
|
||||
expect(grid.weeks, 3);
|
||||
expect(grid.dayAt(0, 0), monday);
|
||||
expect(grid.dayAt(2, 2), wednesday);
|
||||
});
|
||||
|
||||
test('leaves days without a measurement empty rather than zero', () {
|
||||
final grid = buildHeatmapGrid([entry(10, monday)], today: monday);
|
||||
|
||||
expect(grid.valueAt(0, 0), 10);
|
||||
expect(grid.valueAt(0, 1), isNull);
|
||||
});
|
||||
|
||||
test('runs up to today, so a stretch without measurements stays visible', () {
|
||||
final grid = buildHeatmapGrid([entry(10, monday)], today: wednesday);
|
||||
|
||||
expect(grid.weeks, 3);
|
||||
expect(grid.valueAt(2, 2), isNull);
|
||||
});
|
||||
|
||||
test('caps a long history at a year of week columns', () {
|
||||
final grid = buildHeatmapGrid(
|
||||
[entry(10, DateTime(2020, 1, 1)), entry(20, wednesday)],
|
||||
today: wednesday,
|
||||
);
|
||||
|
||||
expect(grid.weeks, heatmapMaxWeeks);
|
||||
expect(grid.dayAt(grid.weeks - 1, 2), wednesday);
|
||||
});
|
||||
|
||||
test('anchors on the last measurement when the history ended long ago', () {
|
||||
// Anchoring on today would put the whole history outside the grid and
|
||||
// draw an empty one
|
||||
final grid = buildHeatmapGrid(
|
||||
[entry(10, monday), entry(20, wednesday)],
|
||||
today: DateTime(2028, 1, 1),
|
||||
);
|
||||
|
||||
expect(grid.dayAt(grid.weeks - 1, 2), wednesday);
|
||||
expect(grid.valueAt(grid.weeks - 1, 2), 20);
|
||||
});
|
||||
|
||||
test('takes the top of the colour scale only from the days it shows', () {
|
||||
// A spike outside the window would scale the colours of every visible
|
||||
// cell without being visible itself, washing out the whole grid
|
||||
final grid = buildHeatmapGrid(
|
||||
[entry(45000, DateTime(2024, 1, 3)), entry(8000, wednesday)],
|
||||
today: wednesday,
|
||||
);
|
||||
|
||||
expect(grid.maxValue, 8000);
|
||||
expect(grid.values.containsKey(DateTime(2024, 1, 3)), isFalse);
|
||||
});
|
||||
|
||||
test('takes the top of the colour scale from the largest value', () {
|
||||
final grid = buildHeatmapGrid(
|
||||
[entry(10, monday), entry(8000, wednesday)],
|
||||
today: wednesday,
|
||||
);
|
||||
|
||||
expect(grid.maxValue, 8000);
|
||||
});
|
||||
|
||||
test('is a full grid of the last year when there is nothing to show', () {
|
||||
final grid = buildHeatmapGrid([]);
|
||||
|
||||
expect(grid.weeks, heatmapMaxWeeks);
|
||||
expect(grid.maxValue, 0);
|
||||
expect(grid.valueAt(0, 0), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
group('MeasurementHeatmapWidgetFl', () {
|
||||
testWidgets('renders without error for empty entries', (tester) async {
|
||||
await tester.pumpWidget(_wrap(const MeasurementHeatmapWidgetFl([], 'steps')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('reads out the day that was tapped', (tester) async {
|
||||
final today = DateTime.now();
|
||||
final day = DateTime(today.year, today.month, today.day);
|
||||
await tester.pumpWidget(_wrap(MeasurementHeatmapWidgetFl([entry(500, day)], 'steps')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// A single day is a one-column grid, so its cell sits in the row of its
|
||||
// weekday. The read-out is what the tooltip is on the other charts.
|
||||
expect(buildHeatmapGrid([entry(500, day)]).weeks, 1);
|
||||
|
||||
// Mirrors the widget's own layout: the read-out line above the grid, the
|
||||
// weekday labels to its left, the month labels on top, and the square
|
||||
// cells centred in what is left
|
||||
const readoutHeight = 20.0;
|
||||
const labelWidth = 22.0;
|
||||
const labelHeight = 12.0;
|
||||
final box = tester.getRect(find.byType(MeasurementHeatmapWidgetFl));
|
||||
final gridHeight = box.height - readoutHeight - labelHeight;
|
||||
final step = min(box.width - labelWidth, gridHeight / DateTime.daysPerWeek);
|
||||
final top =
|
||||
box.top + readoutHeight + labelHeight + (gridHeight - step * DateTime.daysPerWeek) / 2;
|
||||
|
||||
await tester.tapAt(
|
||||
Offset(box.left + labelWidth + step / 2, top + step * (day.weekday - 1) + step / 2),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('500'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user