Let the user pick the chart range for measurements too

This commit is contained in:
Roland Geider
2026-07-31 19:57:13 +02:00
parent f21731735d
commit ed67ff7ea7
8 changed files with 216 additions and 101 deletions

View File

@@ -21,13 +21,24 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/core/widgets/async_value_widget.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'categories_card.dart';
class CategoriesList extends ConsumerWidget {
class CategoriesList extends ConsumerStatefulWidget {
const CategoriesList();
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<CategoriesList> createState() => _CategoriesListState();
}
class _CategoriesListState extends ConsumerState<CategoriesList> {
// One range for all cards: picking it per card would put three buttons on
// every entry of the list
ChartRange _range = ChartRange.last3Months;
@override
Widget build(BuildContext context) {
return AsyncValueWidget<List<MeasurementCategory>>(
value: ref.watch(measurementProvider),
loggerName: 'CategoriesList',
@@ -38,10 +49,21 @@ class CategoriesList extends ConsumerWidget {
.where((c) => c.parentId == null && !c.isOfficialBodyWeight)
.toList();
return ListView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: topLevel.length,
itemBuilder: (context, index) => CategoriesCard(topLevel[index]),
return Column(
children: [
const SizedBox(height: 10),
ChartRangeSelector(
value: _range,
onChanged: (range) => setState(() => _range = range),
),
Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: topLevel.length,
itemBuilder: (context, index) => CategoriesCard(topLevel[index], range: _range),
),
),
],
);
},
);

View File

@@ -20,9 +20,11 @@ import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:wger/core/form_screen.dart';
import 'package:wger/core/formatting/formatting.dart';
import 'package:wger/features/measurements/measurements.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/models/unit_conversion.dart';
import 'package:wger/features/measurements/screens/measurement_entries_screen.dart';
import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'package:wger/features/measurements/widgets/helpers.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
@@ -32,8 +34,13 @@ import 'forms.dart';
class CategoriesCard extends StatelessWidget {
final MeasurementCategory currentCategory;
final double? elevation;
final ChartRange range;
const CategoriesCard(this.currentCategory, {this.elevation});
const CategoriesCard(
this.currentCategory, {
this.elevation,
this.range = ChartRange.last3Months,
});
@override
Widget build(BuildContext context) {
@@ -41,14 +48,18 @@ class CategoriesCard extends StatelessWidget {
return _buildGroupCard(context);
}
// sensibleRange() operates on raw (pre-aggregation) entries
final (entriesAll, entries7dAvg) = sensibleRange(
chartEntriesFor(
currentCategory.entries,
targetUnit: currentCategory.unit,
categoryUnit: currentCategory.unit,
),
final cutoff = range.cutoff;
final allEntries = chartEntriesFor(
currentCategory.entries,
targetUnit: currentCategory.unit,
categoryUnit: currentCategory.unit,
);
// The average is computed over the full history and only then cut, so the
// first points of the range average the days before it instead of starting
// over at the cutoff
final allAvg = moving7dAverage(allEntries);
final entriesAll = cutoff == null ? allEntries : allEntries.whereDate(cutoff, null);
final entries7dAvg = cutoff == null ? allAvg : allAvg.whereDate(cutoff, null);
return Card(
elevation: elevation,
@@ -136,13 +147,14 @@ class CategoriesCard extends StatelessWidget {
// more than two components cannot be a range, and neither can readings
// that are not paired, which happens once the date of one half is edited
// apart from the other.
final cutoff = range.cutoff;
final ranges = currentCategory.children.length == 2
? groupRangeEntries(currentCategory)
? groupRangeEntries(currentCategory, cutoff: cutoff)
: const <MeasurementChartEntry>[];
final asRange = ranges.isNotEmpty;
final series = asRange
? const <MeasurementChartSeries>[]
: groupComponentSeries(currentCategory);
: groupComponentSeries(currentCategory, cutoff: cutoff);
final hasData = asRange || series.any((s) => s.entries.isNotEmpty);
return Card(

View File

@@ -0,0 +1,79 @@
/*
* 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:wger/l10n/generated/app_localizations.dart';
/// Time range the user can pick to limit how far back the charts go.
///
/// The default is the shortest one: a chart is only readable if the span it
/// covers is, and the recent values are what tracking progress is about.
enum ChartRange {
all(null),
lastYear(365),
last3Months(90);
const ChartRange(this._days);
final int? _days;
/// Oldest date still shown, null for the full history.
DateTime? get cutoff => _days == null ? null : DateTime.now().subtract(Duration(days: _days));
String label(AppLocalizations i18n) => switch (this) {
ChartRange.all => i18n.chartRangeAll,
ChartRange.lastYear => i18n.chartRangeLastYear,
ChartRange.last3Months => i18n.chartRangeLast3Months,
};
/// Title for a chart of [name] over this range.
String chartTitle(AppLocalizations i18n, String name) => switch (this) {
ChartRange.all => i18n.chartAllTimeTitle(name),
ChartRange.lastYear => i18n.chartLastYearTitle(name),
ChartRange.last3Months => i18n.chartLast3MonthsTitle(name),
};
}
/// Segmented buttons to pick the [ChartRange] the charts below cover.
class ChartRangeSelector extends StatelessWidget {
final ChartRange value;
final ValueChanged<ChartRange> onChanged;
const ChartRangeSelector({required this.value, required this.onChanged, super.key});
@override
Widget build(BuildContext context) {
final i18n = AppLocalizations.of(context);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SegmentedButton<ChartRange>(
showSelectedIcon: false,
segments: [
for (final range in ChartRange.values)
ButtonSegment(value: range, label: Text(range.label(i18n))),
],
selected: {value},
onSelectionChanged: (selection) => onChanged(selection.first),
),
),
);
}
}

View File

@@ -21,9 +21,11 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/core/form_screen.dart';
import 'package:wger/core/formatting/formatting.dart';
import 'package:wger/core/snackbar.dart';
import 'package:wger/features/measurements/measurements.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/models/unit_conversion.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'package:wger/features/measurements/widgets/charts.dart';
import 'package:wger/features/measurements/widgets/helpers.dart';
import 'package:wger/features/nutrition/models/nutritional_plan.dart';
@@ -32,17 +34,27 @@ import 'package:wger/l10n/generated/app_localizations.dart';
import 'forms.dart';
class EntriesList extends ConsumerWidget {
final MeasurementCategory _category;
class EntriesList extends ConsumerStatefulWidget {
final MeasurementCategory category;
const EntriesList(this._category);
const EntriesList(this.category);
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<EntriesList> createState() => _EntriesListState();
}
class _EntriesListState extends ConsumerState<EntriesList> {
ChartRange _range = ChartRange.last3Months;
@override
Widget build(BuildContext context) {
final i18n = AppLocalizations.of(context);
final category = widget.category;
// Plan periods only matter where a nutrition plan can plausibly move the
// metric; other categories skip the watch, so nutrition edits don't
// rebuild them
final planPeriods = _category.metricType.correlatesWithNutrition
final planPeriods = category.metricType.correlatesWithNutrition
? [
for (final plan
in ref.watch(nutritionProvider).value?.plans ?? const <NutritionalPlan>[])
@@ -57,38 +69,49 @@ class EntriesList extends ConsumerWidget {
// Values are read through the unit helper; for plain categories without
// per-entry units this is a pass-through to the category unit
final entriesAll = chartEntriesFor(
_category.entries,
targetUnit: _category.unit,
categoryUnit: _category.unit,
final allEntries = chartEntriesFor(
category.entries,
targetUnit: category.unit,
categoryUnit: category.unit,
);
final entries7dAvg = moving7dAverage(entriesAll);
// The average is computed over the full history and only then cut, so the
// first points of the range average the days before it instead of starting
// over at the cutoff
final allAvg = moving7dAverage(allEntries);
final cutoff = _range.cutoff;
final entriesAll = cutoff == null ? allEntries : allEntries.whereDate(cutoff, null);
final entries7dAvg = cutoff == null ? allAvg : allAvg.whereDate(cutoff, null);
final datetimeFormat = localizedDate(context);
return Column(
children: [
ChartRangeSelector(
value: _range,
onChanged: (range) => setState(() => _range = range),
),
...getOverviewWidgetsSeries(
_category.name,
category.name,
entriesAll,
entries7dAvg,
planPeriods,
_category.unit,
category.unit,
context,
metricType: _category.metricType,
metricType: category.metricType,
mainChartTitle: _range.chartTitle(i18n, category.name),
),
SizedBox(
height: 300,
child: ListView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: _category.entries.length,
itemCount: category.entries.length,
itemBuilder: (context, index) {
final currentEntry = _category.entries[index];
final currentEntry = category.entries[index];
return Card(
child: ListTile(
title: Text(
'${numberFormat.format(currentEntry.valueIn(_category.unit, categoryUnit: _category.unit))} ${_category.unit}',
'${numberFormat.format(currentEntry.valueIn(category.unit, categoryUnit: category.unit))} ${category.unit}',
),
subtitle: Text(datetimeFormat.format(currentEntry.date)),
// Imported entries are read-only; changes belong in the
@@ -109,7 +132,7 @@ class EntriesList extends ConsumerWidget {
arguments: FormScreenArguments(
AppLocalizations.of(context).edit,
MeasurementEntryForm(
_category.id!,
category.id!,
currentEntry,
),
),

View File

@@ -193,7 +193,9 @@ List<MeasurementChartEntry> chartEntriesFor(
/// nothing was measured between two readings. Components are paired by their
/// shared timestamp, which is how both the importer and the group form write
/// them; an unpaired half-reading is skipped, it has no range.
List<MeasurementChartEntry> groupRangeEntries(MeasurementCategory group) {
///
/// Only readings from [cutoff] on are returned; null covers the full history.
List<MeasurementChartEntry> groupRangeEntries(MeasurementCategory group, {DateTime? cutoff}) {
final byDate = <DateTime, List<num>>{};
for (final child in group.children) {
for (final entry in child.entries) {
@@ -214,24 +216,23 @@ List<MeasurementChartEntry> groupRangeEntries(MeasurementCategory group) {
),
]..sort((a, b) => a.date.compareTo(b.date));
final start = sensibleRangeStart(ranges);
return start == null ? ranges : ranges.whereDate(start, null);
return cutoff == null ? ranges : ranges.whereDate(cutoff, null);
}
/// One line per component of a multi-value group, in the children's in-group
/// order and named after them.
///
/// All components share the same range, so their lines cover the same span
/// even when one of them has fewer readings.
List<MeasurementChartSeries> groupComponentSeries(MeasurementCategory group) {
/// even when one of them has fewer readings. Only readings from [cutoff] on
/// are returned; null covers the full history.
List<MeasurementChartSeries> groupComponentSeries(MeasurementCategory group, {DateTime? cutoff}) {
List<MeasurementChartEntry> pointsOf(MeasurementCategory child) =>
chartEntriesFor(child.entries, targetUnit: child.unit, categoryUnit: child.unit);
final start = sensibleRangeStart(group.children.expand(pointsOf).toList());
return group.children
.map(
(child) => MeasurementChartSeries(
start == null ? pointsOf(child) : pointsOf(child).whereDate(start, null),
cutoff == null ? pointsOf(child) : pointsOf(child).whereDate(cutoff, null),
MeasurementSeriesRole.component,
label: child.name,
),

View File

@@ -28,6 +28,7 @@ import 'package:wger/features/measurements/measurements.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/models/unit_conversion.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'package:wger/features/measurements/widgets/charts.dart';
import 'package:wger/features/measurements/widgets/helpers.dart';
import 'package:wger/features/nutrition/models/nutritional_plan.dart';
@@ -36,9 +37,6 @@ import 'package:wger/features/weight/providers/body_weight_provider.dart';
import 'package:wger/features/weight/widgets/forms.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
/// Time range the user can pick to limit how far back the weight chart goes.
enum WeightChartRange { all, lastYear, last3Months }
class WeightOverview extends riverpod.ConsumerStatefulWidget {
const WeightOverview();
@@ -47,7 +45,7 @@ class WeightOverview extends riverpod.ConsumerStatefulWidget {
}
class _WeightOverviewState extends riverpod.ConsumerState<WeightOverview> {
WeightChartRange _range = WeightChartRange.all;
ChartRange _range = ChartRange.last3Months;
@override
Widget build(BuildContext context) {
@@ -89,17 +87,7 @@ class _WeightOverviewState extends riverpod.ConsumerState<WeightOverview> {
// Restrict the data to the selected range. The average is computed over
// the full history first and only filtered afterwards, matching how the
// per-plan and 30-day sub-charts are built.
final (DateTime? cutoff, String? mainChartTitle) = switch (_range) {
WeightChartRange.all => (null, null),
WeightChartRange.lastYear => (
DateTime.now().subtract(const Duration(days: 365)),
i18n.chartLastYearTitle(i18n.weight),
),
WeightChartRange.last3Months => (
DateTime.now().subtract(const Duration(days: 90)),
i18n.chartLast3MonthsTitle(i18n.weight),
),
};
final cutoff = _range.cutoff;
final entriesRange = cutoff == null ? entriesAll : entriesAll.whereDate(cutoff, null);
final entries7dAvgRange = cutoff == null
? entries7dAvg
@@ -109,31 +97,9 @@ class _WeightOverviewState extends riverpod.ConsumerState<WeightOverview> {
return Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SegmentedButton<WeightChartRange>(
key: const ValueKey('weightChartRangeSelector'),
showSelectedIcon: false,
segments: [
ButtonSegment(
value: WeightChartRange.all,
label: Text(i18n.chartRangeAll),
),
ButtonSegment(
value: WeightChartRange.lastYear,
label: Text(i18n.chartRangeLastYear),
),
ButtonSegment(
value: WeightChartRange.last3Months,
label: Text(i18n.chartRangeLast3Months),
),
],
selected: {_range},
onSelectionChanged: (selection) => setState(() => _range = selection.first),
),
),
ChartRangeSelector(
value: _range,
onChanged: (range) => setState(() => _range = range),
),
...getOverviewWidgetsSeries(
i18n.weight,
@@ -142,7 +108,7 @@ class _WeightOverviewState extends riverpod.ConsumerState<WeightOverview> {
planPeriods,
unit,
context,
mainChartTitle: mainChartTitle,
mainChartTitle: _range.chartTitle(i18n, i18n.weight),
),
TextButton(
onPressed: () => Navigator.pushNamed(

View File

@@ -22,6 +22,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/models/measurement_entry.dart';
import 'package:wger/features/measurements/widgets/categories_card.dart';
import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import '../../../../test_data/measurements.dart';
@@ -32,6 +33,11 @@ Widget _wrap(Widget child) => MaterialApp(
home: Scaffold(body: child),
);
/// The fixtures have fixed dates, so the card charts the full history instead
/// of the range it defaults to
Widget _card(MeasurementCategory category) =>
_wrap(CategoriesCard(category, range: ChartRange.all));
MeasurementCategory _bpGroup({bool withEntries = false}) {
final sysEntries = withEntries ? [testNeasurementEntry9] : <MeasurementEntry>[];
final diaEntries = withEntries ? [testNeasurementEntry10] : <MeasurementEntry>[];
@@ -68,7 +74,7 @@ MeasurementCategory _tripleGroup() {
void main() {
group('CategoriesCard group card', () {
testWidgets('shows one ListTile per child with latest reading', (tester) async {
await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: true))));
await tester.pumpWidget(_card(_bpGroup(withEntries: true)));
await tester.pumpAndSettle();
expect(find.byType(ListTile), findsNWidgets(2));
@@ -77,7 +83,7 @@ void main() {
});
testWidgets('shows dash when child has no entries', (tester) async {
await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: false))));
await tester.pumpWidget(_card(_bpGroup(withEntries: false)));
await tester.pumpAndSettle();
// Text('—') should appear for both children
@@ -85,7 +91,7 @@ void main() {
});
testWidgets('draws a reading as one bar spanning its components', (tester) async {
await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: true))));
await tester.pumpWidget(_card(_bpGroup(withEntries: true)));
await tester.pumpAndSettle();
// One event, one bar: no line claiming values between two readings
@@ -99,7 +105,7 @@ void main() {
});
testWidgets('a range needs no per-component colour dots', (tester) async {
await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: true))));
await tester.pumpWidget(_card(_bpGroup(withEntries: true)));
await tester.pumpAndSettle();
// The ends of the bar say which is which
@@ -123,7 +129,7 @@ void main() {
);
final group = testMeasurementCategoryBloodPressure.copyWith(children: [sys, dia]);
await tester.pumpWidget(_wrap(CategoriesCard(group)));
await tester.pumpWidget(_card(group));
await tester.pumpAndSettle();
expect(find.byType(BarChart), findsNothing);
@@ -132,7 +138,7 @@ void main() {
});
testWidgets('renders no chart while no component has readings', (tester) async {
await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup(withEntries: false))));
await tester.pumpWidget(_card(_bpGroup(withEntries: false)));
await tester.pumpAndSettle();
expect(find.byType(BarChart), findsNothing);
@@ -141,7 +147,7 @@ void main() {
testWidgets('a group of three keeps one line per component', (tester) async {
// Only two components form a low/high range; more stay separate lines
await tester.pumpWidget(_wrap(CategoriesCard(_tripleGroup())));
await tester.pumpWidget(_card(_tripleGroup()));
await tester.pumpAndSettle();
final data = tester.widget<LineChart>(find.byType(LineChart)).data;
@@ -156,7 +162,7 @@ void main() {
});
testWidgets('add icon button is present on group card', (tester) async {
await tester.pumpWidget(_wrap(CategoriesCard(_bpGroup())));
await tester.pumpWidget(_card(_bpGroup()));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.add), findsOneWidget);
@@ -186,7 +192,7 @@ void main() {
);
testWidgets('draws the summarised range as a band around the line', (tester) async {
await tester.pumpWidget(_wrap(CategoriesCard(heartRate())));
await tester.pumpWidget(_card(heartRate()));
await tester.pumpAndSettle();
final data = tester.widget<LineChart>(find.byType(LineChart)).data;
@@ -199,7 +205,7 @@ void main() {
});
testWidgets('plain entries get no band', (tester) async {
await tester.pumpWidget(_wrap(CategoriesCard(heartRate(withRange: false))));
await tester.pumpWidget(_card(heartRate(withRange: false)));
await tester.pumpAndSettle();
expect(tester.widget<LineChart>(find.byType(LineChart)).data.betweenBarsData, isEmpty);

View File

@@ -25,6 +25,7 @@ import 'package:wger/core/form_screen.dart';
import 'package:wger/features/account/providers/user_profile_repository.dart';
import 'package:wger/features/measurements/models/measurement_entry.dart';
import 'package:wger/features/measurements/providers/measurement_repository.dart';
import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'package:wger/features/measurements/widgets/charts.dart';
import 'package:wger/features/nutrition/providers/ingredient_repository.dart';
import 'package:wger/features/nutrition/providers/nutrition_repository.dart';
@@ -90,9 +91,14 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('Weight'), findsOneWidget);
expect(find.byType(MeasurementChartWidgetFl), findsOneWidget);
expect(find.byType(Card), findsNWidgets(2));
expect(find.byType(ListTile), findsNWidgets(2));
// The seeded entries are from 2021, so they only show in the full history
await tester.ensureVisible(find.text('All'));
await tester.tap(find.text('All'));
await tester.pumpAndSettle();
expect(find.byType(MeasurementChartWidgetFl), findsOneWidget);
});
testWidgets('Weight chart range selector filters the data', (WidgetTester tester) async {
@@ -100,26 +106,26 @@ void main() {
await tester.pumpAndSettle();
// The range selector is shown with the three options
expect(find.byKey(const ValueKey('weightChartRangeSelector')), findsOneWidget);
expect(find.byType(ChartRangeSelector), findsOneWidget);
expect(find.text('All'), findsOneWidget);
expect(find.text('Last year'), findsOneWidget);
expect(find.text('Last 3 months'), findsOneWidget);
// By default (all time) the chart is shown for the seeded entries
expect(find.byType(MeasurementChartWidgetFl), findsOneWidget);
// Restricting to the last 3 months excludes the (old) seeded data
await tester.ensureVisible(find.text('Last 3 months'));
await tester.tap(find.text('Last 3 months'));
await tester.pumpAndSettle();
// The default range excludes the (old) seeded data
expect(find.byType(MeasurementChartWidgetFl), findsNothing);
expect(find.text('No data available'), findsOneWidget);
// Switching back to all time restores the chart
// Switching to all time shows the chart
await tester.ensureVisible(find.text('All'));
await tester.tap(find.text('All'));
await tester.pumpAndSettle();
expect(find.byType(MeasurementChartWidgetFl), findsOneWidget);
// and back again
await tester.ensureVisible(find.text('Last 3 months'));
await tester.tap(find.text('Last 3 months'));
await tester.pumpAndSettle();
expect(find.byType(MeasurementChartWidgetFl), findsNothing);
});
testWidgets('Test deleting an item using the Delete button', (WidgetTester tester) async {