diff --git a/lib/helpers/measurements.dart b/lib/helpers/measurements.dart new file mode 100644 index 000000000..5b87ec479 --- /dev/null +++ b/lib/helpers/measurements.dart @@ -0,0 +1,105 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (C) 2020, 2021 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 . + */ + +import 'package:wger/helpers/misc.dart'; +import 'package:wger/widgets/measurements/charts.dart'; + +extension MeasurementChartEntryListExtensions on List { + List whereDate(DateTime start, DateTime? end) { + return where((e) => e.date.isAfter(start) && (end == null || e.date.isBefore(end))).toList(); + } + +// assures values on the start (and optionally end) dates exist, by interpolating if needed +// this is used for when you are looking at a specific time frame (e.g. for a nutrition plan) +// while gaps in the middle of a chart can be "visually interpolated", it's good to have a clearer +// explicit interpolation for the start and end dates (if needed) +// this also helps with computing delta's across the entire window + List whereDateWithInterpolation(DateTime start, DateTime? end) { + // Make sure our list is sorted by date + sort((a, b) => a.date.compareTo(b.date)); + + // Initialize result list + final List result = []; + + // Check if we have any entries on the same day as start/end + bool hasEntryOnStartDay = false; + bool hasEntryOnEndDay = false; + + // Track entries for potential interpolation + MeasurementChartEntry? lastBeforeStart; + MeasurementChartEntry? lastBeforeEnd; + + // Single pass through the data + for (final entry in this) { + if (entry.date.isSameDayAs(start)) { + hasEntryOnStartDay = true; + } + if (end != null && entry.date.isSameDayAs(end)) { + hasEntryOnEndDay = true; + } + + if (end != null && entry.date.isBefore(end)) { + lastBeforeEnd = entry; + } + + if (entry.date.isBefore(start)) { + lastBeforeStart = entry; + } else { + // insert interpolated start value if needed + if (!hasEntryOnStartDay && lastBeforeStart != null) { + result.insert(0, interpolateBetween(lastBeforeStart, entry, start)); + hasEntryOnStartDay = true; + } + + if (end == null || entry.date.isBefore(end)) { + result.add(entry); + } + if (end != null && entry.date.isAfter(end)) { + // insert interpolated end value if needed + // note: we only interpolate end if we have data going beyond end + // if let's say your plan ends in a week from now, we wouldn't want to fake data until next week. + if (!hasEntryOnEndDay && lastBeforeEnd != null) { + result.add(interpolateBetween(lastBeforeEnd, entry, end)); + hasEntryOnEndDay = true; + } + // we added all our values and did all interpolations + // surely all input values from here on are irrelevant. + return result; + } + } + } + return result; + } +} + +// caller needs to make sure that before.date < date < after.date +MeasurementChartEntry interpolateBetween( + MeasurementChartEntry before, MeasurementChartEntry after, DateTime date) { + final totalDuration = after.date.difference(before.date).inMilliseconds; + final startDuration = date.difference(before.date).inMilliseconds; + + // Create a special DateTime with milliseconds ending in 123 to mark it as interpolated + // which we leverage in the UI + final markedDate = + DateTime(date.year, date.month, date.day, date.hour, date.minute, date.second, 123); + + return MeasurementChartEntry( + before.value + (after.value - before.value) * (startDuration / totalDuration), + markedDate, + ); +} diff --git a/lib/widgets/measurements/charts.dart b/lib/widgets/measurements/charts.dart index 62ee1d4a4..ddcf69c57 100644 --- a/lib/widgets/measurements/charts.dart +++ b/lib/widgets/measurements/charts.dart @@ -79,12 +79,17 @@ class _MeasurementChartWidgetFlState extends State { getTooltipColor: (touchedSpot) => Theme.of(context).colorScheme.primaryContainer, getTooltipItems: (touchedSpots) { return touchedSpots.map((touchedSpot) { - final DateTime date = DateTime.fromMillisecondsSinceEpoch(touchedSpot.x.toInt()); + final msSinceEpoch = touchedSpot.x.toInt(); + final DateTime date = DateTime.fromMillisecondsSinceEpoch(msSinceEpoch); 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 == 123; + final String interpolatedMarker = isInterpolated ? ' (interpolated)' : ''; + return LineTooltipItem( - '$dateStr: ${touchedSpot.y.toStringAsFixed(1)} ${widget._unit}', + '$dateStr: ${touchedSpot.y.toStringAsFixed(1)} ${widget._unit}$interpolatedMarker', TextStyle(color: touchedSpot.bar.color), ); }).toList(); diff --git a/lib/widgets/measurements/helpers.dart b/lib/widgets/measurements/helpers.dart index 087a9fe71..4a6f05af6 100644 --- a/lib/widgets/measurements/helpers.dart +++ b/lib/widgets/measurements/helpers.dart @@ -36,10 +36,6 @@ List getOverviewWidgets( ]; } -// TODO(dieter): i'm not sure if this handles well the case where weights were not logged consistently -// e.g. if the plan runs for a month, but the first point is after 3 weeks. -// and the last (non-included) point was *right* before the startDate. -// wouldn't it be better to interpolate the missing points? List getOverviewWidgetsSeries( String name, List entriesAll, @@ -61,8 +57,8 @@ List getOverviewWidgetsSeries( for (final plan in plans) ...getOverviewWidgets( AppLocalizations.of(context).chartDuringPlanTitle(name, plan.description), - entriesAll.whereDate(plan.startDate, plan.endDate), - entries7dAvg.whereDate(plan.startDate, plan.endDate), + entriesAll.whereDateWithInterpolation(plan.startDate, plan.endDate), + entries7dAvg.whereDateWithInterpolation(plan.startDate, plan.endDate), unit, context, ), @@ -74,8 +70,8 @@ List getOverviewWidgetsSeries( entriesAll.any((e) => e.date.isAfter(monthAgo))) ...getOverviewWidgets( AppLocalizations.of(context).chart30DaysTitle(name), - entriesAll.whereDate(monthAgo, null), - entries7dAvg.whereDate(monthAgo, null), + entriesAll.whereDateWithInterpolation(monthAgo, null), + entries7dAvg.whereDateWithInterpolation(monthAgo, null), unit, context, ), diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index fa6d49784..9f45149d2 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -19,6 +19,7 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; +import 'package:wger/helpers/measurements.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/body_weight.dart'; import 'package:wger/providers/nutrition.dart'; @@ -34,25 +35,17 @@ class NutritionalPlansList extends StatelessWidget { /// Builds the weight change information for a nutritional plan period Widget _buildWeightChangeInfo(BuildContext context, DateTime startDate, DateTime? endDate) { - final _provider = Provider.of(context, listen: false); + final provider = Provider.of(context, listen: false); - final entriesAll = _provider.items.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(); - final entries7dAvg = moving7dAverage(entriesAll); - // Filter weight entries within the plan period - final DateTime planEndDate = endDate ?? DateTime.now(); - final List entriesInPeriod = entries7dAvg - .where((entry) => entry.date.isAfter(startDate) && entry.date.isBefore(planEndDate)) - .toList(); - if (entriesInPeriod.length < 2) { + final entriesAll = provider.items.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(); + final entries7dAvg = moving7dAverage(entriesAll).whereDateWithInterpolation(startDate, endDate); + if (entries7dAvg.length < 2) { return const SizedBox.shrink(); } - // Sort entries by date - entriesInPeriod.sort((a, b) => a.date.compareTo(b.date)); - // Calculate weight change - final firstWeight = entriesInPeriod.first; - final lastWeight = entriesInPeriod.last; + final firstWeight = entries7dAvg.first; + final lastWeight = entries7dAvg.last; final weightDifference = lastWeight.value - firstWeight.value; // Format the weight change text and determine color @@ -62,8 +55,6 @@ class NutritionalPlansList extends StatelessWidget { final unit = weightUnit(profile!.isMetric, context); -// TODO: only proceed if it's "representative" (if we covered the plan timespan well enough), or actually, -// we could also interpolate the missing values if (weightDifference > 0) { weightChangeText = '+${weightDifference.toStringAsFixed(1)} $unit'; weightChangeColor = Colors.red; @@ -80,7 +71,7 @@ class NutritionalPlansList extends StatelessWidget { child: Row( children: [ Text( - AppLocalizations.of(context).weight + ' change: ', + '${AppLocalizations.of(context).weight} change: ', style: Theme.of(context).textTheme.bodySmall, ), Text(