diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index 9b3a27965..b1a922ea6 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -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 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. /// diff --git a/lib/features/measurements/widgets/charts.dart b/lib/features/measurements/widgets/charts.dart index fc4fb5234..c2247b3b0 100644 --- a/lib/features/measurements/widgets/charts.dart +++ b/lib/features/measurements/widgets/charts.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * 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 moving7dAverage(List vals) { final _bucketUnits = [ (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 averagePerDay(List 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 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 weeklyDeltas( + List 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 _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 createState() => _MeasurementBarChartWidgetFlState(); @@ -711,11 +755,13 @@ class _MeasurementBarChartWidgetFlState extends State 0 ? '+' : ''}' + '${measurementValue(context, rod.toY, widget._unit)}'; return BarTooltipItem( '$dateStr: $value ${measurementUnit(widget._unit)}', @@ -806,6 +852,14 @@ class _MeasurementBarChartWidgetFlState extends State 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 diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 5b672b227..d0c88c059 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -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 …", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index d1dc8781f..3f6b13a6b 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -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", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 0cb442e1b..3da75427f 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -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…", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index ea3dae5e3..24071ff92 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -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é…", diff --git a/test/features/measurements/models/measurement_category_test.dart b/test/features/measurements/models/measurement_category_test.dart index 0abbbc316..2749fe06a 100644 --- a/test/features/measurements/models/measurement_category_test.dart +++ b/test/features/measurements/models/measurement_category_test.dart @@ -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); }); }); diff --git a/test/features/measurements/widgets/charts_test.dart b/test/features/measurements/widgets/charts_test.dart index 6e9f9a52b..35a9e9c43 100644 --- a/test/features/measurements/widgets/charts_test.dart +++ b/test/features/measurements/widgets/charts_test.dart @@ -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(find.byType(BarChart)).data; + + Future pumpSigned( + WidgetTester tester, + List 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); diff --git a/test/features/measurements/widgets/helpers_test.dart b/test/features/measurements/widgets/helpers_test.dart index c83966a29..a5a5dff2a 100644 --- a/test/features/measurements/widgets/helpers_test.dart +++ b/test/features/measurements/widgets/helpers_test.dart @@ -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(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 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