Add a weekly change (delta) chart type

This commit is contained in:
Roland Geider
2026-08-05 18:10:54 +02:00
parent cecdd1c317
commit ed3d30a226
10 changed files with 356 additions and 26 deletions

View File

@@ -77,7 +77,8 @@ enum ChartType {
auto(null),
line('line'),
bar('bar'),
heatmap('heatmap');
heatmap('heatmap'),
delta('delta');
final String? wireValue;
const ChartType(this.wireValue);
@@ -101,6 +102,7 @@ extension MeasurementChartTypeL10n on ChartType {
ChartType.line => l10n.chartTypeLine,
ChartType.bar => l10n.chartTypeBar,
ChartType.heatmap => l10n.chartTypeHeatmap,
ChartType.delta => l10n.chartTypeDelta,
};
}
}
@@ -163,12 +165,13 @@ enum MetricType {
/// The chart types a category of this type may be drawn as, i.e. what the
/// picker offers on top of [ChartType.auto].
///
/// The heatmap is the one alternative that fits every leaf type: it answers
/// how regularly rather than how much, and it is the only chart of the set
/// where a missing day is visible instead of being spanned by a line. A
/// group is left out, its chart is structural rather than a preference.
/// The two alternatives fit every leaf type: the heatmap answers how
/// regularly rather than how much, and is the only chart of the set where a
/// missing day is visible instead of being spanned by a line; the delta chart
/// answers which way it is going, which a line only implies. A group is left
/// out, its chart is structural rather than a preference.
List<ChartType> get availableChartTypes =>
isGroup ? const [] : [defaultChartType, ChartType.heatmap];
isGroup ? const [] : [defaultChartType, ChartType.heatmap, ChartType.delta];
/// The chart a category of this type is drawn as, given what the user picked.
///

View File

@@ -1,13 +1,13 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020, 2021 wger Team
* 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.
*
* wger Workout Manager is distributed in the hope that it will be useful,
* 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.
@@ -569,10 +569,14 @@ List<MeasurementChartEntry> moving7dAverage(List<MeasurementChartEntry> vals) {
final _bucketUnits = <DateTime Function(DateTime)>[
(d) => DateTime(d.year, d.month, d.day, d.hour),
(d) => DateTime(d.year, d.month, d.day),
(d) => DateTime(d.year, d.month, d.day).subtract(Duration(days: d.weekday - 1)),
weekStart,
(d) => DateTime(d.year, d.month),
];
/// 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));
/// Reduces a dense series to at most [maxPoints], keeping its shape.
///
/// Plotting more points than the chart has pixels only overdraws: a season of
@@ -658,6 +662,41 @@ List<MeasurementChartEntry> averagePerDay(List<MeasurementChartEntry> vals) {
];
}
/// 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,
),
];
}
/// 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;
/// Bar chart for entries that are discrete events rather than a continuous
/// series: daily totals, and the readings of a multi-value group.
///
@@ -669,7 +708,12 @@ class MeasurementBarChartWidgetFl extends StatefulWidget {
final List<MeasurementChartEntry> _entries;
final String _unit;
const MeasurementBarChartWidgetFl(this._entries, this._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})
: _signed = signed;
@override
State<MeasurementBarChartWidgetFl> createState() => _MeasurementBarChartWidgetFlState();
@@ -711,11 +755,13 @@ class _MeasurementBarChartWidgetFlState extends State<MeasurementBarChartWidgetF
Localizations.localeOf(context).languageCode,
).format(entry.date);
// A range is quoted as high over low, the way a blood pressure
// reading is written
// 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!, widget._unit)}'
'/${measurementValue(context, entry.min!, widget._unit)}'
: measurementValue(context, rod.toY, widget._unit);
: '${widget._signed && rod.toY > 0 ? '+' : ''}'
'${measurementValue(context, rod.toY, widget._unit)}';
return BarTooltipItem(
'$dateStr: $value ${measurementUnit(widget._unit)}',
@@ -806,6 +852,14 @@ class _MeasurementBarChartWidgetFlState extends State<MeasurementBarChartWidgetF
show: true,
border: Border.all(color: Theme.of(context).colorScheme.primaryContainer),
),
// 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 (widget._signed)
HorizontalLine(y: 0, color: Theme.of(context).colorScheme.outline, strokeWidth: 1),
],
),
barGroups: widget._entries
.asMap()
.entries
@@ -817,11 +871,18 @@ class _MeasurementBarChartWidgetFlState extends State<MeasurementBarChartWidgetF
// 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: Theme.of(context).colorScheme.primary,
color: widget._signed
? deltaColor(context, e.value.value)
: Theme.of(context).colorScheme.primary,
width: barWidth,
borderRadius: e.value.hasRange
? BorderRadius.circular(2)
: const BorderRadius.vertical(top: Radius.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,
),
),
],
),

View File

@@ -64,17 +64,24 @@ List<Widget> getOverviewWidgetsSeries(
}) {
final title = mainChartTitle ?? AppLocalizations.of(context).chartAllTimeTitle(name);
// A heatmap is one grid over the whole range and needs its points per day,
// so none of what follows applies to it: condensing would collapse days into
// weeks, the extra 30-day chart is a window the grid already shows, and the
// legend names lines it does not draw
if (metricType.resolveChartType(chartType) == ChartType.heatmap) {
final resolved = metricType.resolveChartType(chartType);
// Neither the heatmap nor the change chart is a line over the range, and both
// bucket the points themselves: condensing would collapse the days they are
// built from, the extra 30-day chart is a window they already show, and the
// legend names lines they do not draw
if (resolved == ChartType.heatmap || resolved == ChartType.delta) {
return getOverviewWidgets(
title,
// The selector right above names the range, so the title says what the
// bars are instead
resolved == ChartType.delta
? AppLocalizations.of(context).chartWeeklyChangeTitle(name)
: title,
entriesAll,
// No overall change either: it is the distance between two points of a
// line, which is not what the grid is about
const [],
// The overall change is the one-number version of the change chart. Over
// a grid it measures a line that is not drawn, and a summed metric has no
// level to change.
resolved == ChartType.delta && !metricType.isSummedPerDay ? entries7dAvg : const [],
unit,
context,
metricType: metricType,
@@ -387,7 +394,15 @@ Widget buildChartForMetricType(
// A pick that does not fit the metric type falls back to the derived chart,
// which is also what a category configured on a newer client gets here
if (metricType.resolveChartType(chartType) == ChartType.heatmap) {
final resolved = metricType.resolveChartType(chartType);
if (resolved == ChartType.delta) {
// Not condensed: a week is already the bucket, and the deltas are what the
// chart draws rather than the values they were derived from
return MeasurementBarChartWidgetFl(weeklyDeltas(raw, summed: summed), unit, signed: true);
}
if (resolved == ChartType.heatmap) {
// The cells are days, so how a day's readings become one value has to be
// decided here: the summed types are a daily total, the sample types are
// repeated readings of the same thing and average

View File

@@ -1181,6 +1181,8 @@
"chartTypeLine": "Linie",
"chartTypeBar": "Balken",
"chartTypeHeatmap": "Heatmap",
"chartTypeDelta": "Veränderung",
"chartWeeklyChangeTitle": "{name}, Veränderung pro Woche",
"healthSyncNoData": "Es wurden keine Gesundheitsdaten gefunden. Prüfe in {platform}, ob wger deine Daten lesen darf.",
"healthSyncStatus": "{count, plural, =0{Letzter Abgleich: {time}, keine neuen Einträge} one{Letzter Abgleich: {time}, 1 neuer Eintrag} other{Letzter Abgleich: {time}, {count} neue Einträge}}",
"healthSyncSyncing": "Gesundheitsdaten werden synchronisiert …",

View File

@@ -601,6 +601,20 @@
"@chartTypeHeatmap": {
"description": "Chart type option: a calendar grid with one coloured cell per day"
},
"chartTypeDelta": "Change",
"@chartTypeDelta": {
"description": "Chart type option: one bar per week, showing how much the value changed"
},
"chartWeeklyChangeTitle": "{name}, change per week",
"@chartWeeklyChangeTitle": {
"description": "Title of the chart showing the weekly change of 'name' (e.g. 'weight', 'body fat' etc.)",
"type": "text",
"placeholders": {
"name": {
"type": "String"
}
}
},
"measurement": "Measurement",
"@measurement": {},
"measurements": "Measurements",

View File

@@ -1220,6 +1220,8 @@
"chartTypeLine": "Línea",
"chartTypeBar": "Barras",
"chartTypeHeatmap": "Mapa de calor",
"chartTypeDelta": "Variación",
"chartWeeklyChangeTitle": "{name}, variación por semana",
"healthSyncNoData": "No se han encontrado datos de salud. Comprueba en {platform} que wger puede leer tus datos.",
"healthSyncStatus": "{count, plural, =0{Última sincronización: {time}, sin entradas nuevas} one{Última sincronización: {time}, 1 entrada nueva} other{Última sincronización: {time}, {count} entradas nuevas}}",
"healthSyncSyncing": "Sincronizando datos de salud…",

View File

@@ -1191,6 +1191,8 @@
"chartTypeLine": "Ligne",
"chartTypeBar": "Barres",
"chartTypeHeatmap": "Carte thermique",
"chartTypeDelta": "Variation",
"chartWeeklyChangeTitle": "{name}, variation par semaine",
"healthSyncNoData": "Aucune donnée de santé n'a été trouvée. Vérifiez dans {platform} que wger peut lire vos données.",
"healthSyncStatus": "{count, plural, =0{Dernière synchronisation : {time}, aucune nouvelle entrée} one{Dernière synchronisation : {time}, 1 nouvelle entrée} other{Dernière synchronisation : {time}, {count} nouvelles entrées}}",
"healthSyncSyncing": "Synchronisation des données de santé…",

View File

@@ -78,8 +78,16 @@ void main() {
});
test('the offered types follow the metric type', () {
expect(MetricType.steps.availableChartTypes, [ChartType.bar, ChartType.heatmap]);
expect(MetricType.custom.availableChartTypes, [ChartType.line, ChartType.heatmap]);
expect(MetricType.steps.availableChartTypes, [
ChartType.bar,
ChartType.heatmap,
ChartType.delta,
]);
expect(MetricType.custom.availableChartTypes, [
ChartType.line,
ChartType.heatmap,
ChartType.delta,
]);
// a group is drawn by what its components are to each other
expect(MetricType.bloodPressure.availableChartTypes, isEmpty);
@@ -94,6 +102,7 @@ void main() {
test('a type that fits is kept', () {
expect(MetricType.custom.resolveChartType(ChartType.heatmap), ChartType.heatmap);
expect(MetricType.steps.resolveChartType(ChartType.bar), ChartType.bar);
expect(MetricType.bodyWeight.resolveChartType(ChartType.delta), ChartType.delta);
});
});

View File

@@ -631,6 +631,160 @@ void main() {
});
});
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('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'));
});
});
group('buildHeatmapGrid', () {
// 2 March 2026 is a Monday, 18 March a Wednesday
final monday = DateTime(2026, 3, 2);

View File

@@ -184,6 +184,33 @@ void main() {
expect(find.byType(MeasurementChartWidgetFl), findsOneWidget);
});
testWidgets('a delta override draws the weekly changes as signed bars', (tester) async {
// 5 January 2026 is a Monday
final weekly = [
MeasurementChartEntry(80, DateTime(2026, 1, 5)),
MeasurementChartEntry(79, DateTime(2026, 1, 12)),
MeasurementChartEntry(79.5, DateTime(2026, 1, 19)),
];
final widget = buildChartForMetricType(
MetricType.bodyWeight,
weekly,
[],
'kg',
chartType: ChartType.delta,
);
await tester.pumpWidget(_wrapChart(widget));
await tester.pumpAndSettle();
expect(find.byType(MeasurementChartWidgetFl), findsNothing);
final rods = tester
.widget<BarChart>(find.byType(BarChart))
.data
.barGroups
.map((g) => g.barRods.single);
expect(rods.map((r) => r.toY), [-1, 0.5]);
expect(rods.first.color, isNot(rods.last.color));
});
testWidgets('a heatmap keeps one point per day instead of condensing', (tester) async {
// Past ~200 points the line chart condenses into calendar buckets, which
// for a grid of days would collapse whole weeks into a single cell
@@ -438,6 +465,47 @@ void main() {
});
});
group('getOverviewWidgetsSeries change chart', () {
final history = [
for (var i = 0; i < 100; i++)
MeasurementChartEntry(60 + (i % 5), DateTime.now().subtract(Duration(days: 99 - i))),
];
Future<void> pumpDelta(WidgetTester tester) => _pumpWidgetList(
tester,
(ctx) => getOverviewWidgetsSeries(
'Weight',
history,
moving7dAverage(history),
[],
'kg',
ctx,
metricType: MetricType.bodyWeight,
chartType: ChartType.delta,
),
);
testWidgets('one chart, without the legend of lines it does not draw', (tester) async {
await pumpDelta(tester);
expect(find.byType(BarChart), findsOneWidget);
expect(find.byType(LineChart), findsNothing);
expect(find.byType(Indicator), findsNothing);
});
testWidgets('the title says the bars are changes, not values', (tester) async {
await pumpDelta(tester);
expect(find.text('Weight, change per week'), findsOneWidget);
});
testWidgets('keeps the overall change, the one-number version of it', (tester) async {
await pumpDelta(tester);
expect(find.byType(MeasurementOverallChangeWidget), findsOneWidget);
});
});
group('getOverviewWidgetsSeries 30-day chart', () {
testWidgets('trend is the tail of the full-history trend', (tester) async {
// A history long enough to trigger the extra 30-day chart. Its trend