diff --git a/lib/core/widgets/dashboard/widgets/weight.dart b/lib/core/widgets/dashboard/widgets/weight.dart index 0f8f400cb..4562b9c92 100644 --- a/lib/core/widgets/dashboard/widgets/weight.dart +++ b/lib/core/widgets/dashboard/widgets/weight.dart @@ -115,7 +115,7 @@ class DashboardWeightWidget extends ConsumerWidget { // Mixed-unit entries (kg/lb) are normalized to the profile's display unit final displayUnit = weightDisplayUnit(profile.isMetric); - final (entriesAll, entries7dAvg) = sensibleRange( + final (entriesAll, average) = sensibleRange( entriesList .map( (e) => MeasurementChartEntry( @@ -124,6 +124,7 @@ class DashboardWeightWidget extends ConsumerWidget { ), ) .toList(), + averageDays: category.chartSettings.averageWindow, ); return Column( @@ -133,13 +134,13 @@ class DashboardWeightWidget extends ConsumerWidget { child: MeasurementChartWidgetFl.singleMeasurement( entriesAll, weightUnit(profile.isMetric, context), - avgs: entries7dAvg, + avgs: average, ), ), - if (entries7dAvg.isNotEmpty) + if (average.isNotEmpty) MeasurementOverallChangeWidget( - entries7dAvg.first, - entries7dAvg.last, + average.first, + average.last, weightUnit(profile.isMetric, context), ), LayoutBuilder( diff --git a/lib/database/powersync/database.g.dart b/lib/database/powersync/database.g.dart index 612c9093e..20396ba14 100644 --- a/lib/database/powersync/database.g.dart +++ b/lib/database/powersync/database.g.dart @@ -4730,6 +4730,17 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable ).withConverter( $MeasurementCategoryTableTable.$converterchartType, ); + @override + late final GeneratedColumnWithTypeConverter?, String> chartConfig = + GeneratedColumn( + 'chart_config', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ).withConverter?>( + $MeasurementCategoryTableTable.$converterchartConfign, + ); static const VerificationMeta _parentIdMeta = const VerificationMeta( 'parentId', ); @@ -4776,6 +4787,7 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable unit, metricType, chartType, + chartConfig, parentId, order, isOfficial, @@ -4862,6 +4874,12 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable data['${effectivePrefix}chart_type'], ), ), + chartConfig: $MeasurementCategoryTableTable.$converterchartConfign.fromSql( + attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}chart_config'], + ), + ), parentId: attachedDatabase.typeMapping.read( DriftSqlType.string, data['${effectivePrefix}parent_id'], @@ -4886,6 +4904,10 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable const MeasurementMetricTypeConverter(); static TypeConverter $converterchartType = const MeasurementChartTypeConverter(); + static TypeConverter, String> $converterchartConfig = + const JsonMapConverter(); + static TypeConverter?, String?> $converterchartConfign = + NullAwareTypeConverter.wrap($converterchartConfig); } class MeasurementCategoryTableCompanion extends UpdateCompanion { @@ -4894,6 +4916,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion unit; final Value metricType; final Value chartType; + final Value?> chartConfig; final Value parentId; final Value order; final Value isOfficial; @@ -4904,6 +4927,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion? unit, Expression? metricType, Expression? chartType, + Expression? chartConfig, Expression? parentId, Expression? order, Expression? isOfficial, @@ -4939,6 +4965,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion? unit, Value? metricType, Value? chartType, + Value?>? chartConfig, Value? parentId, Value? order, Value? isOfficial, @@ -4963,6 +4991,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion( + $MeasurementCategoryTableTable.$converterchartConfign.toSql( + chartConfig.value, + ), + ); + } if (parentId.present) { map['parent_id'] = Variable(parentId.value); } @@ -5019,6 +5055,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion chartType, + Value?> chartConfig, Value parentId, Value order, Value isOfficial, @@ -16326,6 +16364,7 @@ typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder = Value unit, Value metricType, Value chartType, + Value?> chartConfig, Value parentId, Value order, Value isOfficial, @@ -16421,6 +16460,12 @@ class $$MeasurementCategoryTableTableFilterComposer builder: (column) => ColumnWithTypeConverterFilters(column), ); + ColumnWithTypeConverterFilters?, Map, String> + get chartConfig => $composableBuilder( + column: $table.chartConfig, + builder: (column) => ColumnWithTypeConverterFilters(column), + ); + ColumnFilters get order => $composableBuilder( column: $table.order, builder: (column) => ColumnFilters(column), @@ -16512,6 +16557,11 @@ class $$MeasurementCategoryTableTableOrderingComposer builder: (column) => ColumnOrderings(column), ); + ColumnOrderings get chartConfig => $composableBuilder( + column: $table.chartConfig, + builder: (column) => ColumnOrderings(column), + ); + ColumnOrderings get order => $composableBuilder( column: $table.order, builder: (column) => ColumnOrderings(column), @@ -16571,6 +16621,12 @@ class $$MeasurementCategoryTableTableAnnotationComposer GeneratedColumnWithTypeConverter get chartType => $composableBuilder(column: $table.chartType, builder: (column) => column); + GeneratedColumnWithTypeConverter?, String> get chartConfig => + $composableBuilder( + column: $table.chartConfig, + builder: (column) => column, + ); + GeneratedColumn get order => $composableBuilder(column: $table.order, builder: (column) => column); @@ -16670,6 +16726,7 @@ class $$MeasurementCategoryTableTableTableManager Value unit = const Value.absent(), Value metricType = const Value.absent(), Value chartType = const Value.absent(), + Value?> chartConfig = const Value.absent(), Value parentId = const Value.absent(), Value order = const Value.absent(), Value isOfficial = const Value.absent(), @@ -16680,6 +16737,7 @@ class $$MeasurementCategoryTableTableTableManager unit: unit, metricType: metricType, chartType: chartType, + chartConfig: chartConfig, parentId: parentId, order: order, isOfficial: isOfficial, @@ -16692,6 +16750,7 @@ class $$MeasurementCategoryTableTableTableManager required String unit, required MetricType metricType, Value chartType = const Value.absent(), + Value?> chartConfig = const Value.absent(), Value parentId = const Value.absent(), Value order = const Value.absent(), Value isOfficial = const Value.absent(), @@ -16702,6 +16761,7 @@ class $$MeasurementCategoryTableTableTableManager unit: unit, metricType: metricType, chartType: chartType, + chartConfig: chartConfig, parentId: parentId, order: order, isOfficial: isOfficial, diff --git a/lib/database/powersync/tables/measurements.dart b/lib/database/powersync/tables/measurements.dart index 2797ee257..0f1519639 100644 --- a/lib/database/powersync/tables/measurements.dart +++ b/lib/database/powersync/tables/measurements.dart @@ -41,6 +41,11 @@ class MeasurementCategoryTable extends Table { TextColumn get chartType => text().named('chart_type').nullable().map(const MeasurementChartTypeConverter())(); + /// Taste-level chart settings (server JSONField), e.g. the trend character. + /// A missing key, and a missing object, mean the client default. + TextColumn get chartConfig => + text().named('chart_config').map(const JsonMapConverter()).nullable()(); + /// Multi-value groups: parent category id (max. one level of nesting; only /// leaf categories carry entries). TextColumn get parentId => @@ -61,6 +66,8 @@ const PowersyncMeasurementCategoryTable = ps.Table( ps.Column.text('unit'), ps.Column.text('metric_type'), ps.Column.text('chart_type'), + // JSON object, synced and stored as text + ps.Column.text('chart_config'), ps.Column.text('parent_id'), ps.Column.integer('order'), // Postgres boolean; integer so the view yields 0/1, not the string '0' diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index da0fe9a9a..32f0ac1ad 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -94,6 +94,73 @@ enum ChartType { ); } +/// How closely the trend line follows the values, as the EMA period it maps to. +/// +/// Stored as the character rather than the number, so the periods stay tunable +/// without touching what users configured. +enum TrendCharacter { + reactive('reactive', 5), + balanced('balanced', 10), + sluggish('sluggish', 20); + + final String wireValue; + final int emaPeriod; + const TrendCharacter(this.wireValue, this.emaPeriod); + + /// Falls back to [TrendCharacter.balanced], which is the unconfigured chart. + static TrendCharacter fromWire(Object? value) => TrendCharacter.values.firstWhere( + (e) => e.wireValue == value, + orElse: () => TrendCharacter.balanced, + ); +} + +extension MeasurementTrendCharacterL10n on TrendCharacter { + /// Localized human-readable label for the picker. + String localized(BuildContext context) { + final l10n = AppLocalizations.of(context); + return switch (this) { + TrendCharacter.reactive => l10n.trendReactive, + TrendCharacter.balanced => l10n.trendBalanced, + TrendCharacter.sluggish => l10n.trendSluggish, + }; + } +} + +/// The taste-level chart settings of a category, resolved. +/// +/// One object rather than one parameter per setting: the charts take it as a +/// whole, so a setting added here reaches them without touching a signature. +/// The defaults are what an unconfigured category is drawn with. +class ChartSettings { + /// Windows the moving average may be computed over, in days. + static const averageWindows = [7, 14, 30]; + + final TrendCharacter trend; + + /// Window the moving average covers, in days + final int averageWindow; + + const ChartSettings({ + this.trend = TrendCharacter.balanced, + this.averageWindow = 7, + }); + + /// Reads the settings out of a stored `chart_config`. + /// + /// A value this release does not know, and a missing object, fall back to + /// the default, the same rule an unfitting [ChartType] follows. + factory ChartSettings.fromConfig(Map? config) { + final window = config?['average_window']; + + return ChartSettings( + trend: TrendCharacter.fromWire(config?['trend']), + averageWindow: window is int && averageWindows.contains(window) + ? window + : averageWindows.first, + ); + } +} + extension MeasurementChartTypeL10n on ChartType { /// Localized human-readable label for the picker. String localized(BuildContext context) { @@ -435,6 +502,15 @@ class MeasurementCategory with _$MeasurementCategory { @override final ChartType chartType; + /// Taste-level chart settings, read through [chartSettings]. + /// + /// Null for a category that configured none, which is also what a row synced + /// before the column existed reads. Keys this release does not know are + /// kept: another client may have written them, and a write from here + /// replaces the whole object. + @override + final Map? chartConfig; + /// Multi-value groups (e.g. blood pressure): id of the parent category, one /// child per component. Max. one level of nesting; only leaf categories /// (no children) carry entries. @@ -462,12 +538,21 @@ class MeasurementCategory with _$MeasurementCategory { this.entries = const [], this.metricType = MetricType.custom, this.chartType = ChartType.auto, + this.chartConfig, this.parentId, this.order = 0, this.isOfficial = false, this.children = const [], }); + /// How this category is drawn, beyond the chart type: see [ChartSettings]. + ChartSettings get chartSettings => ChartSettings.fromConfig(chartConfig); + + /// A copy with one chart setting changed, keeping the keys this release does + /// not know: a write replaces the whole object. + MeasurementCategory withChartSetting(String key, Object value) => + copyWith(chartConfig: {...?chartConfig, key: value}); + /// `true` for group parents (blood pressure etc.), which hold no entries of /// their own bool get isGroup => children.isNotEmpty; @@ -499,6 +584,7 @@ class MeasurementCategory with _$MeasurementCategory { unit: Value(unit), metricType: Value(metricType), chartType: Value(chartType), + chartConfig: Value(chartConfig), parentId: Value(parentId), order: Value(order), isOfficial: Value(isOfficial), diff --git a/lib/features/measurements/models/measurement_category.freezed.dart b/lib/features/measurements/models/measurement_category.freezed.dart index 82e13fe19..ff20d3f8f 100644 --- a/lib/features/measurements/models/measurement_category.freezed.dart +++ b/lib/features/measurements/models/measurement_category.freezed.dart @@ -19,7 +19,13 @@ mixin _$MeasurementCategory { /// chart). [MetricType.custom] for plain user-created categories. MetricType get metricType;/// Chart the user picked for this category, [ChartType.auto] (the server's /// null) for the one derived from [metricType]. - ChartType get chartType;/// Multi-value groups (e.g. blood pressure): id of the parent category, one + ChartType get chartType;/// Taste-level chart settings, read through [trend] and [averageWindow]. +/// +/// Null for a category that configured none, which is also what a row synced +/// before the column existed reads. Keys this release does not know are +/// kept: another client may have written them, and a write from here +/// replaces the whole object. + Map? get chartConfig;/// Multi-value groups (e.g. blood pressure): id of the parent category, one /// child per component. Max. one level of nesting; only leaf categories /// (no children) carry entries. String? get parentId;/// Position in the category list; for children, the position within the group @@ -38,16 +44,16 @@ $MeasurementCategoryCopyWith get copyWith => _$MeasurementC @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is MeasurementCategory&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.unit, unit) || other.unit == unit)&&const DeepCollectionEquality().equals(other.entries, entries)&&(identical(other.metricType, metricType) || other.metricType == metricType)&&(identical(other.chartType, chartType) || other.chartType == chartType)&&(identical(other.parentId, parentId) || other.parentId == parentId)&&(identical(other.order, order) || other.order == order)&&(identical(other.isOfficial, isOfficial) || other.isOfficial == isOfficial)&&const DeepCollectionEquality().equals(other.children, children)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is MeasurementCategory&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.unit, unit) || other.unit == unit)&&const DeepCollectionEquality().equals(other.entries, entries)&&(identical(other.metricType, metricType) || other.metricType == metricType)&&(identical(other.chartType, chartType) || other.chartType == chartType)&&const DeepCollectionEquality().equals(other.chartConfig, chartConfig)&&(identical(other.parentId, parentId) || other.parentId == parentId)&&(identical(other.order, order) || other.order == order)&&(identical(other.isOfficial, isOfficial) || other.isOfficial == isOfficial)&&const DeepCollectionEquality().equals(other.children, children)); } @override -int get hashCode => Object.hash(runtimeType,id,name,unit,const DeepCollectionEquality().hash(entries),metricType,chartType,parentId,order,isOfficial,const DeepCollectionEquality().hash(children)); +int get hashCode => Object.hash(runtimeType,id,name,unit,const DeepCollectionEquality().hash(entries),metricType,chartType,const DeepCollectionEquality().hash(chartConfig),parentId,order,isOfficial,const DeepCollectionEquality().hash(children)); @override String toString() { - return 'MeasurementCategory(id: $id, name: $name, unit: $unit, entries: $entries, metricType: $metricType, chartType: $chartType, parentId: $parentId, order: $order, isOfficial: $isOfficial, children: $children)'; + return 'MeasurementCategory(id: $id, name: $name, unit: $unit, entries: $entries, metricType: $metricType, chartType: $chartType, chartConfig: $chartConfig, parentId: $parentId, order: $order, isOfficial: $isOfficial, children: $children)'; } @@ -58,7 +64,7 @@ abstract mixin class $MeasurementCategoryCopyWith<$Res> { factory $MeasurementCategoryCopyWith(MeasurementCategory value, $Res Function(MeasurementCategory) _then) = _$MeasurementCategoryCopyWithImpl; @useResult $Res call({ - String? id, String name, String unit, List entries, MetricType metricType, ChartType chartType, String? parentId, int order, bool isOfficial, List children + String? id, String name, String unit, List entries, MetricType metricType, ChartType chartType, Map? chartConfig, String? parentId, int order, bool isOfficial, List children }); @@ -75,7 +81,7 @@ class _$MeasurementCategoryCopyWithImpl<$Res> /// Create a copy of MeasurementCategory /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? id = freezed,Object? name = null,Object? unit = null,Object? entries = null,Object? metricType = null,Object? chartType = null,Object? parentId = freezed,Object? order = null,Object? isOfficial = null,Object? children = null,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? id = freezed,Object? name = null,Object? unit = null,Object? entries = null,Object? metricType = null,Object? chartType = null,Object? chartConfig = freezed,Object? parentId = freezed,Object? order = null,Object? isOfficial = null,Object? children = null,}) { return _then(MeasurementCategory( id: freezed == id ? _self.id : id // ignore: cast_nullable_to_non_nullable as String?,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable @@ -83,7 +89,8 @@ as String,unit: null == unit ? _self.unit : unit // ignore: cast_nullable_to_non as String,entries: null == entries ? _self.entries : entries // ignore: cast_nullable_to_non_nullable as List,metricType: null == metricType ? _self.metricType : metricType // ignore: cast_nullable_to_non_nullable as MetricType,chartType: null == chartType ? _self.chartType : chartType // ignore: cast_nullable_to_non_nullable -as ChartType,parentId: freezed == parentId ? _self.parentId : parentId // ignore: cast_nullable_to_non_nullable +as ChartType,chartConfig: freezed == chartConfig ? _self.chartConfig : chartConfig // ignore: cast_nullable_to_non_nullable +as Map?,parentId: freezed == parentId ? _self.parentId : parentId // ignore: cast_nullable_to_non_nullable as String?,order: null == order ? _self.order : order // ignore: cast_nullable_to_non_nullable as int,isOfficial: null == isOfficial ? _self.isOfficial : isOfficial // ignore: cast_nullable_to_non_nullable as bool,children: null == children ? _self.children : children // ignore: cast_nullable_to_non_nullable diff --git a/lib/features/measurements/providers/body_weight_provider.g.dart b/lib/features/measurements/providers/body_weight_provider.g.dart index fe35f8ef2..49c97fccf 100644 --- a/lib/features/measurements/providers/body_weight_provider.g.dart +++ b/lib/features/measurements/providers/body_weight_provider.g.dart @@ -12,7 +12,7 @@ part of 'body_weight_provider.dart'; /// /// The category is created by the server (registration / data migration) and /// only arrives via sync; a `null` value means the initial sync has not -/// delivered it yet. Mutations go through [measurementProvider]'s notifier. +/// delivered it yet. Mutations go through `measurementProvider`'s notifier. /// /// Unbounded, for the consumers that need the latest entry whatever its age /// (the dashboard card, the nutrition widgets). A screen that shows a range @@ -25,7 +25,7 @@ final bodyWeightCategoryProvider = BodyWeightCategoryProvider._(); /// /// The category is created by the server (registration / data migration) and /// only arrives via sync; a `null` value means the initial sync has not -/// delivered it yet. Mutations go through [measurementProvider]'s notifier. +/// delivered it yet. Mutations go through `measurementProvider`'s notifier. /// /// Unbounded, for the consumers that need the latest entry whatever its age /// (the dashboard card, the nutrition widgets). A screen that shows a range @@ -43,7 +43,7 @@ final class BodyWeightCategoryProvider /// /// The category is created by the server (registration / data migration) and /// only arrives via sync; a `null` value means the initial sync has not - /// delivered it yet. Mutations go through [measurementProvider]'s notifier. + /// delivered it yet. Mutations go through `measurementProvider`'s notifier. /// /// Unbounded, for the consumers that need the latest entry whatever its age /// (the dashboard card, the nutrition widgets). A screen that shows a range diff --git a/lib/features/measurements/widgets/categories_card.dart b/lib/features/measurements/widgets/categories_card.dart index 570c9f914..d4df527b0 100644 --- a/lib/features/measurements/widgets/categories_card.dart +++ b/lib/features/measurements/widgets/categories_card.dart @@ -57,9 +57,10 @@ class CategoriesCard extends StatelessWidget { // 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 settings = currentCategory.chartSettings; + final allAverage = movingAverage(allEntries, days: settings.averageWindow); final entriesAll = cutoff == null ? allEntries : allEntries.whereDate(cutoff, null); - final entries7dAvg = cutoff == null ? allAvg : allAvg.whereDate(cutoff, null); + final average = cutoff == null ? allAverage : allAverage.whereDate(cutoff, null); return Card( elevation: elevation, @@ -83,15 +84,16 @@ class CategoriesCard extends StatelessWidget { child: buildChartForMetricType( currentCategory.metricType, entriesAll, - entries7dAvg, + average, currentCategory.unit, chartType: currentCategory.chartType, + settings: settings, ), ), - if (entries7dAvg.isNotEmpty && !currentCategory.metricType.isSummedPerDay) + if (average.isNotEmpty && !currentCategory.metricType.isSummedPerDay) MeasurementOverallChangeWidget( - entries7dAvg.first, - entries7dAvg.last, + average.first, + average.last, currentCategory.unit, ), const Divider(), diff --git a/lib/features/measurements/widgets/chart_range_selector.dart b/lib/features/measurements/widgets/chart_range_selector.dart index 4522afb42..8ae36a1bd 100644 --- a/lib/features/measurements/widgets/chart_range_selector.dart +++ b/lib/features/measurements/widgets/chart_range_selector.dart @@ -16,7 +16,9 @@ * along with this program. If not, see . */ +import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; /// Time range the user can pick to limit how far back the charts go. @@ -37,8 +39,9 @@ enum ChartRange { /// Days read beyond [cutoff], so the moving average of the first days in /// range averages the days before them instead of starting over at the - /// cutoff. - static const _averageLeadDays = 7; + /// cutoff. The largest window a category can be set to, rather than its own, + /// so changing that setting does not invalidate the provider. + static final _averageLeadDays = ChartSettings.averageWindows.max; /// Oldest entry to read from the database, null for the full history. /// @@ -51,7 +54,7 @@ enum ChartRange { return null; } - final lead = from.subtract(const Duration(days: _averageLeadDays)); + final lead = from.subtract(Duration(days: _averageLeadDays)); return DateTime(lead.year, lead.month, lead.day); } diff --git a/lib/features/measurements/widgets/charts.dart b/lib/features/measurements/widgets/charts.dart index 996ca9fa8..91c8edbc1 100644 --- a/lib/features/measurements/widgets/charts.dart +++ b/lib/features/measurements/widgets/charts.dart @@ -525,8 +525,8 @@ class MeasurementChartSeries { final String? label; } -// for each point, return the average of all the points in the 7 days preceding it -List moving7dAverage(List vals) { +/// For each point, the average of all the points in the [days] preceding it. +List movingAverage(List vals, {int days = 7}) { var start = 0; var end = 0; final List out = []; @@ -546,7 +546,7 @@ List moving7dAverage(List vals) { // 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 = vals[end].date.subtract(const Duration(days: 7)); + final intervalStart = vals[end].date.subtract(Duration(days: days)); while (start < end && vals[start].date.isBefore(intervalStart)) { sum -= vals[start].value; start++; diff --git a/lib/features/measurements/widgets/entries.dart b/lib/features/measurements/widgets/entries.dart index ab6b446bc..568046358 100644 --- a/lib/features/measurements/widgets/entries.dart +++ b/lib/features/measurements/widgets/entries.dart @@ -111,10 +111,11 @@ class EntriesList extends ConsumerWidget { // 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 settings = category.chartSettings; + final allAverage = movingAverage(allEntries, days: settings.averageWindow); final cutoff = range.cutoff; final entriesAll = cutoff == null ? allEntries : allEntries.whereDate(cutoff, null); - final entries7dAvg = cutoff == null ? allAvg : allAvg.whereDate(cutoff, null); + final average = cutoff == null ? allAverage : allAverage.whereDate(cutoff, null); final datetimeFormat = localizedDate(context); @@ -127,13 +128,14 @@ class EntriesList extends ConsumerWidget { ...getOverviewWidgetsSeries( name, entriesAll, - entries7dAvg, + average, planPeriods, unitLabel, context, metricType: category.metricType, mainChartTitle: range.chartTitle(i18n, name), chartType: category.chartType, + settings: settings, ), SizedBox( height: 300, diff --git a/lib/features/measurements/widgets/forms.dart b/lib/features/measurements/widgets/forms.dart index dd4d8e4cc..b4b9f0c48 100644 --- a/lib/features/measurements/widgets/forms.dart +++ b/lib/features/measurements/widgets/forms.dart @@ -67,6 +67,15 @@ class _MeasurementCategoryFormState extends ConsumerState( + initialValue: settings.trend, + decoration: InputDecoration(labelText: AppLocalizations.of(context).chartTrend), + items: TrendCharacter.values + .map((t) => DropdownMenuItem(value: t, child: Text(t.localized(context)))) + .toList(), + onChanged: drawsLine + ? (value) { + if (value != null) { + setState(() { + _draft = _draft.withChartSetting('trend', value.wireValue); + }); + } + } + : null, + ), + DropdownButtonFormField( + initialValue: settings.averageWindow, + decoration: InputDecoration( + labelText: AppLocalizations.of(context).chartAverageWindow, + ), + items: ChartSettings.averageWindows + .map( + (days) => DropdownMenuItem( + value: days, + child: Text(AppLocalizations.of(context).chartAverageWindowDays(days)), + ), + ) + .toList(), + onChanged: drawsLine + ? (value) { + if (value != null) { + setState(() { + _draft = _draft.withChartSetting('average_window', value); + }); + } + } + : null, + ), + ], + // Parent group (multi-value measurements, e.g. blood pressure). // Mirrors the server rules: only top-level, entry-free categories // can be parents, a category with children cannot be nested, a typed diff --git a/lib/features/measurements/widgets/helpers.dart b/lib/features/measurements/widgets/helpers.dart index bd27505e0..de4a11347 100644 --- a/lib/features/measurements/widgets/helpers.dart +++ b/lib/features/measurements/widgets/helpers.dart @@ -17,6 +17,7 @@ List getOverviewWidgets( List planPeriods = const [], List? trend, ChartType chartType = ChartType.auto, + ChartSettings settings = const ChartSettings(), }) { return [ Text( @@ -44,6 +45,7 @@ List getOverviewWidgets( planPeriods: planPeriods, trend: trend, chartType: chartType, + settings: settings, ), ), if (avg.isNotEmpty) MeasurementOverallChangeWidget(avg.first, avg.last, unit), @@ -54,13 +56,14 @@ List getOverviewWidgets( List getOverviewWidgetsSeries( String name, List entriesAll, - List entries7dAvg, + List average, List planPeriods, String unit, BuildContext context, { MetricType metricType = MetricType.custom, String? mainChartTitle, ChartType chartType = ChartType.auto, + ChartSettings settings = const ChartSettings(), }) { final title = mainChartTitle ?? AppLocalizations.of(context).chartAllTimeTitle(name); @@ -86,11 +89,12 @@ List getOverviewWidgetsSeries( // 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 [], + resolved == ChartType.delta && !metricType.isSummedPerDay ? average : const [], unit, context, metricType: metricType, chartType: chartType, + settings: settings, ); } @@ -100,17 +104,18 @@ List getOverviewWidgetsSeries( // trend. With dense metrics the full-series passes dominate the build. final summed = metricType.isSummedPerDay; final points = summed ? entriesAll : downsample(entriesAll); - final trendAll = summed ? null : smoothedTrendline(points); + final trendAll = summed ? null : smoothedTrendline(points, period: settings.trend.emaPeriod); return [ ...getOverviewWidgets( title, points, - entries7dAvg, + average, unit, context, metricType: metricType, planPeriods: planPeriods, trend: trendAll, + settings: settings, ), // if all time is significantly longer than 30 days (let's say > 75 days) // then let's show a separate chart just focusing on the last 30 days, @@ -124,7 +129,7 @@ List getOverviewWidgetsSeries( // condensed on its own so it keeps the finer resolution its shorter // span allows entriesAll.whereDateWithInterpolation(monthAgo, null), - entries7dAvg.whereDateWithInterpolation(monthAgo, null), + average.whereDateWithInterpolation(monthAgo, null), unit, context, metricType: metricType, @@ -133,6 +138,7 @@ List getOverviewWidgetsSeries( // window would seed the EMA from the window's (possibly interpolated) // first point and bend it across half the chart trend: trendAll?.whereDate(monthAgo, null), + settings: settings, ), // legend Row( @@ -183,17 +189,19 @@ DateTime? sensibleRangeStart(List entriesAll) { } // return the raw and average measurements for a "sensible range", see -// sensibleRangeStart +// sensibleRangeStart. [averageDays] is the window of the moving average, which +// the category can configure. (List, List) sensibleRange( - List entriesAll, -) { - final entries7dAvg = moving7dAverage(entriesAll); + List entriesAll, { + int averageDays = 7, +}) { + final average = movingAverage(entriesAll, days: averageDays); final start = sensibleRangeStart(entriesAll); if (start == null) { - return (entriesAll, entries7dAvg); + return (entriesAll, average); } - return (entriesAll.whereDate(start, null), entries7dAvg.whereDate(start, null)); + return (entriesAll.whereDate(start, null), average.whereDate(start, null)); } /// Turns stored entries into chart points, converting the value to [targetUnit]. @@ -417,6 +425,7 @@ Widget buildChartForMetricType( List planPeriods = const [], List? trend, ChartType chartType = ChartType.auto, + ChartSettings settings = const ChartSettings(), }) { final summed = metricType.isSummedPerDay; @@ -463,7 +472,7 @@ Widget buildChartForMetricType( points, unit, avgs: downsample(avg), - trend: trend ?? smoothedTrendline(points), + trend: trend ?? smoothedTrendline(points, period: settings.trend.emaPeriod), planPeriods: planPeriods, ); } diff --git a/lib/features/nutrition/widgets/nutritional_plans_list.dart b/lib/features/nutrition/widgets/nutritional_plans_list.dart index 3f732d4af..be9a233cf 100644 --- a/lib/features/nutrition/widgets/nutritional_plans_list.dart +++ b/lib/features/nutrition/widgets/nutritional_plans_list.dart @@ -57,14 +57,17 @@ class NutritionalPlansList extends riverpod.ConsumerWidget { targetUnit: displayUnit, categoryUnit: category.unit, ); - final entries7dAvg = moving7dAverage(entriesAll).whereDateWithInterpolation(startDate, endDate); - if (entries7dAvg.length < 2) { + final average = movingAverage( + entriesAll, + days: category.chartSettings.averageWindow, + ).whereDateWithInterpolation(startDate, endDate); + if (average.length < 2) { return const SizedBox.shrink(); } // Calculate weight change - final firstWeight = entries7dAvg.first; - final lastWeight = entries7dAvg.last; + final firstWeight = average.first; + final lastWeight = average.last; final weightDifference = lastWeight.value - firstWeight.value; // Format the weight change text and determine color diff --git a/lib/features/nutrition/widgets/plan_weight_chart.dart b/lib/features/nutrition/widgets/plan_weight_chart.dart index ec04ddb65..cfc11e421 100644 --- a/lib/features/nutrition/widgets/plan_weight_chart.dart +++ b/lib/features/nutrition/widgets/plan_weight_chart.dart @@ -63,7 +63,8 @@ class PlanWeightChart extends ConsumerWidget { // to the profile's display unit before charting or averaging final displayUnit = weightDisplayUnit(profile.isMetric); final points = chartEntriesFor(entries, targetUnit: displayUnit, categoryUnit: category.unit); - final avg = moving7dAverage(points); + final settings = category.chartSettings; + final avg = movingAverage(points, days: settings.averageWindow); return Column( children: getOverviewWidgets( @@ -73,6 +74,7 @@ class PlanWeightChart extends ConsumerWidget { weightUnit(profile.isMetric, context), context, metricType: category.metricType, + settings: settings, ), ); } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 56297f453..0459550d3 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1183,6 +1183,12 @@ "chartTypeHeatmap": "Heatmap", "chartTypeDelta": "Veränderung", "chartWeeklyChangeTitle": "{name}, Veränderung pro Woche", + "chartTrend": "Trendlinie", + "trendReactive": "Reaktiv", + "trendBalanced": "Ausgewogen", + "trendSluggish": "Geglättet", + "chartAverageWindow": "Durchschnitt über", + "chartAverageWindowDays": "{days, plural, one{1 Tag} other{{days} Tage}}", "chartTypeDistribution": "Verteilung", "chartDistributionTitle": "{name}, Verteilung", "distributionMedian": "Median", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 62604c5f8..1452fdc25 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -615,6 +615,35 @@ } } }, + "chartTrend": "Trend line", + "@chartTrend": { + "description": "Label of the setting for how closely the trend line follows the values" + }, + "trendReactive": "Reactive", + "@trendReactive": { + "description": "Trend line option: follows the values closely" + }, + "trendBalanced": "Balanced", + "@trendBalanced": { + "description": "Trend line option: the default, between reactive and sluggish" + }, + "trendSluggish": "Smooth", + "@trendSluggish": { + "description": "Trend line option: ignores short-term swings" + }, + "chartAverageWindow": "Average over", + "@chartAverageWindow": { + "description": "Label of the setting for how many days the moving average covers" + }, + "chartAverageWindowDays": "{days, plural, one{1 day} other{{days} days}}", + "@chartAverageWindowDays": { + "description": "One option of the average window setting, e.g. '7 days'", + "placeholders": { + "days": { + "type": "int" + } + } + }, "chartTypeDistribution": "Distribution", "@chartTypeDistribution": { "description": "Chart type option: a histogram of how often each value occurred" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index adaa907e7..2c524942b 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1222,6 +1222,12 @@ "chartTypeHeatmap": "Mapa de calor", "chartTypeDelta": "Variación", "chartWeeklyChangeTitle": "{name}, variación por semana", + "chartTrend": "Línea de tendencia", + "trendReactive": "Reactiva", + "trendBalanced": "Equilibrada", + "trendSluggish": "Suavizada", + "chartAverageWindow": "Promedio de", + "chartAverageWindowDays": "{days, plural, one{1 día} other{{days} días}}", "chartTypeDistribution": "Distribución", "chartDistributionTitle": "{name}, distribución", "distributionMedian": "Mediana", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 5632b4eb7..43cb74e29 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1193,6 +1193,12 @@ "chartTypeHeatmap": "Carte thermique", "chartTypeDelta": "Variation", "chartWeeklyChangeTitle": "{name}, variation par semaine", + "chartTrend": "Courbe de tendance", + "trendReactive": "Réactive", + "trendBalanced": "Équilibrée", + "trendSluggish": "Lissée", + "chartAverageWindow": "Moyenne sur", + "chartAverageWindowDays": "{days, plural, one{1 jour} other{{days} jours}}", "chartTypeDistribution": "Répartition", "chartDistributionTitle": "{name}, répartition", "distributionMedian": "Médiane", diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index d937aca68..bbc1c3dd6 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -2159,6 +2159,105 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get chartTypeDelta => + (super.noSuchMethod( + Invocation.getter(#chartTypeDelta), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#chartTypeDelta), + ), + ) + as String); + + @override + String get chartTrend => + (super.noSuchMethod( + Invocation.getter(#chartTrend), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#chartTrend), + ), + ) + as String); + + @override + String get trendReactive => + (super.noSuchMethod( + Invocation.getter(#trendReactive), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#trendReactive), + ), + ) + as String); + + @override + String get trendBalanced => + (super.noSuchMethod( + Invocation.getter(#trendBalanced), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#trendBalanced), + ), + ) + as String); + + @override + String get trendSluggish => + (super.noSuchMethod( + Invocation.getter(#trendSluggish), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#trendSluggish), + ), + ) + as String); + + @override + String get chartAverageWindow => + (super.noSuchMethod( + Invocation.getter(#chartAverageWindow), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#chartAverageWindow), + ), + ) + as String); + + @override + String get chartTypeDistribution => + (super.noSuchMethod( + Invocation.getter(#chartTypeDistribution), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#chartTypeDistribution), + ), + ) + as String); + + @override + String get distributionMedian => + (super.noSuchMethod( + Invocation.getter(#distributionMedian), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#distributionMedian), + ), + ) + as String); + + @override + String get distributionLatest => + (super.noSuchMethod( + Invocation.getter(#distributionLatest), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#distributionLatest), + ), + ) + as String); + @override String get measurement => (super.noSuchMethod( @@ -4643,6 +4742,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get useDynamicColor => + (super.noSuchMethod( + Invocation.getter(#useDynamicColor), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#useDynamicColor), + ), + ) + as String); + @override String get youAreOffline => (super.noSuchMethod( @@ -5303,6 +5413,61 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String chartWeeklyChangeTitle(String? name) => + (super.noSuchMethod( + Invocation.method(#chartWeeklyChangeTitle, [name]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#chartWeeklyChangeTitle, [name]), + ), + ) + as String); + + @override + String chartAverageWindowDays(int? days) => + (super.noSuchMethod( + Invocation.method(#chartAverageWindowDays, [days]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#chartAverageWindowDays, [days]), + ), + ) + as String); + + @override + String chartDistributionTitle(String? name) => + (super.noSuchMethod( + Invocation.method(#chartDistributionTitle, [name]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#chartDistributionTitle, [name]), + ), + ) + as String); + + @override + String distributionEntryCount(int? count) => + (super.noSuchMethod( + Invocation.method(#distributionEntryCount, [count]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#distributionEntryCount, [count]), + ), + ) + as String); + + @override + String distributionDayCount(int? count) => + (super.noSuchMethod( + Invocation.method(#distributionDayCount, [count]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#distributionDayCount, [count]), + ), + ) + as String); + @override String minLengthRoutine(int? number) => (super.noSuchMethod( diff --git a/test/features/measurements/models/measurement_category_test.dart b/test/features/measurements/models/measurement_category_test.dart index 9bb060809..42024b933 100644 --- a/test/features/measurements/models/measurement_category_test.dart +++ b/test/features/measurements/models/measurement_category_test.dart @@ -112,6 +112,42 @@ void main() { }); }); + group('chartConfig', () { + MeasurementCategory withConfig(Map config) => + MeasurementCategory(chartConfig: config); + + test('an unconfigured category gets the defaults', () { + // A row synced before the column existed reads null, one the user never + // configured an empty object; both mean the same thing + expect(MeasurementCategory().chartSettings.trend, TrendCharacter.balanced); + expect(MeasurementCategory().chartSettings.averageWindow, 7); + expect(withConfig({}).chartSettings.trend, TrendCharacter.balanced); + expect(withConfig({}).chartSettings.averageWindow, 7); + }); + + test('reads what was configured', () { + expect(withConfig({'trend': 'sluggish'}).chartSettings.trend, TrendCharacter.sluggish); + expect(withConfig({'average_window': 30}).chartSettings.averageWindow, 30); + }); + + test('a value this release does not know falls back to the default', () { + expect(withConfig({'trend': 'glacial'}).chartSettings.trend, TrendCharacter.balanced); + expect(withConfig({'average_window': 21}).chartSettings.averageWindow, 7); + expect(withConfig({'average_window': 'a fortnight'}).chartSettings.averageWindow, 7); + }); + + test('a setting is changed without dropping the keys of another client', () { + final category = withConfig({'goal_line': 75}).withChartSetting('trend', 'reactive'); + + expect(category.chartConfig, {'goal_line': 75, 'trend': 'reactive'}); + }); + + test('the trend character maps to the EMA period the chart uses', () { + expect(TrendCharacter.reactive.emaPeriod, lessThan(TrendCharacter.balanced.emaPeriod)); + expect(TrendCharacter.sluggish.emaPeriod, greaterThan(TrendCharacter.balanced.emaPeriod)); + }); + }); + group('binWidth', () { test('body weight follows the unit, like its limits do', () { expect(MetricType.bodyWeight.binWidth('kg'), 0.5); diff --git a/test/features/measurements/widgets/charts_test.dart b/test/features/measurements/widgets/charts_test.dart index 315ac00db..dcd3f7fb2 100644 --- a/test/features/measurements/widgets/charts_test.dart +++ b/test/features/measurements/widgets/charts_test.dart @@ -396,13 +396,13 @@ void main() { }); }); - group('moving7dAverage', () { + group('movingAverage', () { test('returns an empty list for no entries', () { - expect(moving7dAverage([]), isEmpty); + expect(movingAverage([]), isEmpty); }); test('averages over everything within the preceding 7 days', () { - final result = moving7dAverage([ + final result = movingAverage([ entry(10, DateTime(2026, 1, 1)), entry(20, DateTime(2026, 1, 2)), entry(30, DateTime(2026, 1, 3)), @@ -417,7 +417,7 @@ void main() { }); test('drops points that fell out of the window', () { - final result = moving7dAverage([ + final result = movingAverage([ entry(10, DateTime(2026, 1, 1)), entry(20, DateTime(2026, 1, 20)), ]); @@ -427,7 +427,7 @@ void main() { }); test('sorts unordered input by date first', () { - final result = moving7dAverage([ + final result = movingAverage([ entry(30, DateTime(2026, 1, 3)), entry(10, DateTime(2026, 1, 1)), entry(20, DateTime(2026, 1, 2)), @@ -439,12 +439,23 @@ void main() { 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 = moving7dAverage([ + 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('downsample', () { diff --git a/test/features/measurements/widgets/forms_test.dart b/test/features/measurements/widgets/forms_test.dart index e74c2b3a0..62d56d8e2 100644 --- a/test/features/measurements/widgets/forms_test.dart +++ b/test/features/measurements/widgets/forms_test.dart @@ -131,6 +131,94 @@ void main() { expect(find.byType(DropdownButtonFormField), findsOneWidget); }); + testWidgets('a leaf category gets the line chart settings', (tester) async { + final category = getMeasurementCategories()[1]; + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([category])); + + await tester.pumpWidget(wrap(MeasurementCategoryForm(category))); + await tester.pumpAndSettle(); + + expect(find.byType(DropdownButtonFormField), findsOneWidget); + expect(find.byType(DropdownButtonFormField), findsOneWidget); + }); + + testWidgets('a summed type has no line to configure', (tester) async { + // Its chart is one bar per day, which has neither a trend nor an + // average, and no pick can turn it into a line + final steps = getMeasurementCategories()[1].copyWith(metricType: MetricType.steps); + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([steps])); + + await tester.pumpWidget(wrap(MeasurementCategoryForm(steps))); + await tester.pumpAndSettle(); + + expect(find.byType(DropdownButtonFormField), findsNothing); + expect(find.byType(DropdownButtonFormField), findsNothing); + }); + + testWidgets('the line settings are disabled for a chart without a line', (tester) async { + // Kept rather than hidden: switching the chart type back applies them + // again, and a field that vanishes takes the reason with it + final category = getMeasurementCategories()[1].copyWith(chartType: ChartType.delta); + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([category])); + + await tester.pumpWidget(wrap(MeasurementCategoryForm(category))); + await tester.pumpAndSettle(); + + expect( + tester + .widget>( + find.byType(DropdownButtonFormField), + ) + .onChanged, + isNull, + ); + expect( + tester + .widget>( + find.byType(DropdownButtonFormField), + ) + .onChanged, + isNull, + ); + }); + + testWidgets('the line settings are enabled while the chart is a line', (tester) async { + final category = getMeasurementCategories()[1].copyWith(chartType: ChartType.auto); + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([category])); + + await tester.pumpWidget(wrap(MeasurementCategoryForm(category))); + await tester.pumpAndSettle(); + + expect( + tester + .widget>( + find.byType(DropdownButtonFormField), + ) + .onChanged, + isNotNull, + ); + }); + + testWidgets('picking a trend keeps the settings of another client', (tester) async { + final category = getMeasurementCategories()[1].copyWith(chartConfig: {'goal_line': 75}); + when(mockRepo.watchAll()).thenAnswer((_) => Stream.value([category])); + + await tester.pumpWidget(wrap(MeasurementCategoryForm(category))); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reactive').last); + await tester.pumpAndSettle(); + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + final saved = + verify(mockRepo.updateLocalDriftCategory(captureAny)).captured.single + as MeasurementCategory; + expect(saved.chartConfig, {'goal_line': 75, 'trend': 'reactive'}); + }); + testWidgets('editing existing category pre-fills name and unit', (tester) async { final existing = getMeasurementCategories()[1]; diff --git a/test/features/measurements/widgets/helpers_test.dart b/test/features/measurements/widgets/helpers_test.dart index 95b6ab00d..1ecb06eea 100644 --- a/test/features/measurements/widgets/helpers_test.dart +++ b/test/features/measurements/widgets/helpers_test.dart @@ -57,7 +57,7 @@ void main() { MeasurementChartEntry(10, DateTime(2026, 1, 1)), MeasurementChartEntry(20, DateTime(2026, 1, 10)), ]; - final avgEntries = moving7dAverage(rawEntries); + final avgEntries = movingAverage(rawEntries); group('chartEntriesFor', () { test('converts the aggregate bounds along with the value', () { @@ -100,6 +100,19 @@ void main() { }); }); + group('sensibleRange', () { + test('averages over the window the category configured', () { + final points = [ + MeasurementChartEntry(10, DateTime.now().subtract(const Duration(days: 11))), + MeasurementChartEntry(20, DateTime.now()), + ]; + + // the older point is outside 7 days but inside 14 + expect(sensibleRange(points).$2.last.value, 20); + expect(sensibleRange(points, averageDays: 14).$2.last.value, 15); + }); + }); + group('buildChartForMetricType routing', () { final entries = [ MeasurementChartEntry(1000, DateTime(2026, 1, 1)), @@ -135,7 +148,7 @@ void main() { final widget = buildChartForMetricType( MetricType.custom, many, - moving7dAverage(many), + movingAverage(many), 'kg', ); await tester.pumpWidget(_wrapChart(widget)); @@ -531,7 +544,7 @@ void main() { (ctx) => getOverviewWidgetsSeries( 'Weight', history, - moving7dAverage(history), + movingAverage(history), [], 'kg', ctx, @@ -572,7 +585,7 @@ void main() { (ctx) => getOverviewWidgetsSeries( 'Weight', history, - moving7dAverage(history), + movingAverage(history), [], 'kg', ctx, @@ -607,7 +620,7 @@ void main() { (ctx) => getOverviewWidgetsSeries( 'Weight', history.take(5).toList(), - moving7dAverage(history.take(5).toList()), + movingAverage(history.take(5).toList()), [], 'kg', ctx, @@ -636,8 +649,7 @@ void main() { ]; await _pumpWidgetList( tester, - (ctx) => - getOverviewWidgetsSeries('Weight', history, moving7dAverage(history), [], 'kg', ctx), + (ctx) => getOverviewWidgetsSeries('Weight', history, movingAverage(history), [], 'kg', ctx), ); final charts = tester.widgetList(find.byType(LineChart)).toList();