Add per-category chart settings (trend, average window)

This commit is contained in:
Roland Geider
2026-08-05 21:29:31 +02:00
parent cd4797538f
commit 82be49c8a0
23 changed files with 654 additions and 60 deletions

View File

@@ -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(

View File

@@ -4730,6 +4730,17 @@ class $MeasurementCategoryTableTable extends MeasurementCategoryTable
).withConverter<ChartType>(
$MeasurementCategoryTableTable.$converterchartType,
);
@override
late final GeneratedColumnWithTypeConverter<Map<String, dynamic>?, String> chartConfig =
GeneratedColumn<String>(
'chart_config',
aliasedName,
true,
type: DriftSqlType.string,
requiredDuringInsert: false,
).withConverter<Map<String, dynamic>?>(
$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<ChartType, String?> $converterchartType =
const MeasurementChartTypeConverter();
static TypeConverter<Map<String, dynamic>, String> $converterchartConfig =
const JsonMapConverter();
static TypeConverter<Map<String, dynamic>?, String?> $converterchartConfign =
NullAwareTypeConverter.wrap($converterchartConfig);
}
class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCategory> {
@@ -4894,6 +4916,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
final Value<String> unit;
final Value<MetricType> metricType;
final Value<ChartType> chartType;
final Value<Map<String, dynamic>?> chartConfig;
final Value<String?> parentId;
final Value<int> order;
final Value<bool> isOfficial;
@@ -4904,6 +4927,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
this.unit = const Value.absent(),
this.metricType = const Value.absent(),
this.chartType = const Value.absent(),
this.chartConfig = const Value.absent(),
this.parentId = const Value.absent(),
this.order = const Value.absent(),
this.isOfficial = const Value.absent(),
@@ -4915,6 +4939,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
required String unit,
required MetricType metricType,
this.chartType = const Value.absent(),
this.chartConfig = const Value.absent(),
this.parentId = const Value.absent(),
this.order = const Value.absent(),
this.isOfficial = const Value.absent(),
@@ -4928,6 +4953,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
Expression<String>? unit,
Expression<String>? metricType,
Expression<String>? chartType,
Expression<String>? chartConfig,
Expression<String>? parentId,
Expression<int>? order,
Expression<bool>? isOfficial,
@@ -4939,6 +4965,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
if (unit != null) 'unit': unit,
if (metricType != null) 'metric_type': metricType,
if (chartType != null) 'chart_type': chartType,
if (chartConfig != null) 'chart_config': chartConfig,
if (parentId != null) 'parent_id': parentId,
if (order != null) 'order': order,
if (isOfficial != null) 'is_official': isOfficial,
@@ -4952,6 +4979,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
Value<String>? unit,
Value<MetricType>? metricType,
Value<ChartType>? chartType,
Value<Map<String, dynamic>?>? chartConfig,
Value<String?>? parentId,
Value<int>? order,
Value<bool>? isOfficial,
@@ -4963,6 +4991,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
unit: unit ?? this.unit,
metricType: metricType ?? this.metricType,
chartType: chartType ?? this.chartType,
chartConfig: chartConfig ?? this.chartConfig,
parentId: parentId ?? this.parentId,
order: order ?? this.order,
isOfficial: isOfficial ?? this.isOfficial,
@@ -4996,6 +5025,13 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
),
);
}
if (chartConfig.present) {
map['chart_config'] = Variable<String>(
$MeasurementCategoryTableTable.$converterchartConfign.toSql(
chartConfig.value,
),
);
}
if (parentId.present) {
map['parent_id'] = Variable<String>(parentId.value);
}
@@ -5019,6 +5055,7 @@ class MeasurementCategoryTableCompanion extends UpdateCompanion<MeasurementCateg
..write('unit: $unit, ')
..write('metricType: $metricType, ')
..write('chartType: $chartType, ')
..write('chartConfig: $chartConfig, ')
..write('parentId: $parentId, ')
..write('order: $order, ')
..write('isOfficial: $isOfficial, ')
@@ -16314,6 +16351,7 @@ typedef $$MeasurementCategoryTableTableCreateCompanionBuilder =
required String unit,
required MetricType metricType,
Value<ChartType> chartType,
Value<Map<String, dynamic>?> chartConfig,
Value<String?> parentId,
Value<int> order,
Value<bool> isOfficial,
@@ -16326,6 +16364,7 @@ typedef $$MeasurementCategoryTableTableUpdateCompanionBuilder =
Value<String> unit,
Value<MetricType> metricType,
Value<ChartType> chartType,
Value<Map<String, dynamic>?> chartConfig,
Value<String?> parentId,
Value<int> order,
Value<bool> isOfficial,
@@ -16421,6 +16460,12 @@ class $$MeasurementCategoryTableTableFilterComposer
builder: (column) => ColumnWithTypeConverterFilters(column),
);
ColumnWithTypeConverterFilters<Map<String, dynamic>?, Map<String, dynamic>, String>
get chartConfig => $composableBuilder(
column: $table.chartConfig,
builder: (column) => ColumnWithTypeConverterFilters(column),
);
ColumnFilters<int> get order => $composableBuilder(
column: $table.order,
builder: (column) => ColumnFilters(column),
@@ -16512,6 +16557,11 @@ class $$MeasurementCategoryTableTableOrderingComposer
builder: (column) => ColumnOrderings(column),
);
ColumnOrderings<String> get chartConfig => $composableBuilder(
column: $table.chartConfig,
builder: (column) => ColumnOrderings(column),
);
ColumnOrderings<int> get order => $composableBuilder(
column: $table.order,
builder: (column) => ColumnOrderings(column),
@@ -16571,6 +16621,12 @@ class $$MeasurementCategoryTableTableAnnotationComposer
GeneratedColumnWithTypeConverter<ChartType, String> get chartType =>
$composableBuilder(column: $table.chartType, builder: (column) => column);
GeneratedColumnWithTypeConverter<Map<String, dynamic>?, String> get chartConfig =>
$composableBuilder(
column: $table.chartConfig,
builder: (column) => column,
);
GeneratedColumn<int> get order =>
$composableBuilder(column: $table.order, builder: (column) => column);
@@ -16670,6 +16726,7 @@ class $$MeasurementCategoryTableTableTableManager
Value<String> unit = const Value.absent(),
Value<MetricType> metricType = const Value.absent(),
Value<ChartType> chartType = const Value.absent(),
Value<Map<String, dynamic>?> chartConfig = const Value.absent(),
Value<String?> parentId = const Value.absent(),
Value<int> order = const Value.absent(),
Value<bool> 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> chartType = const Value.absent(),
Value<Map<String, dynamic>?> chartConfig = const Value.absent(),
Value<String?> parentId = const Value.absent(),
Value<int> order = const Value.absent(),
Value<bool> isOfficial = const Value.absent(),
@@ -16702,6 +16761,7 @@ class $$MeasurementCategoryTableTableTableManager
unit: unit,
metricType: metricType,
chartType: chartType,
chartConfig: chartConfig,
parentId: parentId,
order: order,
isOfficial: isOfficial,

View File

@@ -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'

View File

@@ -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<String, dynamic>? 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<String, dynamic>? 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),

View File

@@ -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<String, dynamic>? 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<MeasurementCategory> 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<MeasurementEntry> entries, MetricType metricType, ChartType chartType, String? parentId, int order, bool isOfficial, List<MeasurementCategory> children
String? id, String name, String unit, List<MeasurementEntry> entries, MetricType metricType, ChartType chartType, Map<String, dynamic>? chartConfig, String? parentId, int order, bool isOfficial, List<MeasurementCategory> 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<MeasurementEntry>,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<String, dynamic>?,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

View File

@@ -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

View File

@@ -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(),

View File

@@ -16,7 +16,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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);
}

View File

@@ -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<MeasurementChartEntry> moving7dAverage(List<MeasurementChartEntry> vals) {
/// For each point, the average of all the points in the [days] preceding it.
List<MeasurementChartEntry> movingAverage(List<MeasurementChartEntry> vals, {int days = 7}) {
var start = 0;
var end = 0;
final List<MeasurementChartEntry> out = <MeasurementChartEntry>[];
@@ -546,7 +546,7 @@ List<MeasurementChartEntry> moving7dAverage(List<MeasurementChartEntry> 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++;

View File

@@ -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,

View File

@@ -67,6 +67,15 @@ class _MeasurementCategoryFormState extends ConsumerState<MeasurementCategoryFor
// one takes both from its metric type, which is also what is shown for it
final isCustom = _draft.metricType == MetricType.custom;
// The trend line and the moving average are parts of the line chart: a
// category that can never be drawn as one is not offered them at all, and
// one that is currently drawn as something else keeps its settings but
// cannot change them
final canDrawLine =
!hasChildren && _draft.metricType.availableChartTypes.contains(ChartType.line);
final drawsLine = _draft.metricType.resolveChartType(_draft.chartType) == ChartType.line;
final settings = _draft.chartSettings;
return Form(
key: _form,
child: Column(
@@ -142,6 +151,50 @@ class _MeasurementCategoryFormState extends ConsumerState<MeasurementCategoryFor
},
),
// Trend character and average window, disabled while the category is
// drawn as something that has neither
if (canDrawLine) ...[
DropdownButtonFormField<TrendCharacter>(
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<int>(
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

View File

@@ -17,6 +17,7 @@ List<Widget> getOverviewWidgets(
List<PlanPeriod> planPeriods = const [],
List<MeasurementChartEntry>? trend,
ChartType chartType = ChartType.auto,
ChartSettings settings = const ChartSettings(),
}) {
return [
Text(
@@ -44,6 +45,7 @@ List<Widget> getOverviewWidgets(
planPeriods: planPeriods,
trend: trend,
chartType: chartType,
settings: settings,
),
),
if (avg.isNotEmpty) MeasurementOverallChangeWidget(avg.first, avg.last, unit),
@@ -54,13 +56,14 @@ List<Widget> getOverviewWidgets(
List<Widget> getOverviewWidgetsSeries(
String name,
List<MeasurementChartEntry> entriesAll,
List<MeasurementChartEntry> entries7dAvg,
List<MeasurementChartEntry> average,
List<PlanPeriod> 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<Widget> 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<Widget> 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<Widget> 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<Widget> 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<MeasurementChartEntry> 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<MeasurementChartEntry>, List<MeasurementChartEntry>) sensibleRange(
List<MeasurementChartEntry> entriesAll,
) {
final entries7dAvg = moving7dAverage(entriesAll);
List<MeasurementChartEntry> 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<PlanPeriod> planPeriods = const [],
List<MeasurementChartEntry>? 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,
);
}

View File

@@ -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

View File

@@ -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,
),
);
}

View File

@@ -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",

View File

@@ -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"

View File

@@ -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",

View File

@@ -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",

View File

@@ -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<String>(
this,
Invocation.getter(#chartTypeDelta),
),
)
as String);
@override
String get chartTrend =>
(super.noSuchMethod(
Invocation.getter(#chartTrend),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#chartTrend),
),
)
as String);
@override
String get trendReactive =>
(super.noSuchMethod(
Invocation.getter(#trendReactive),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#trendReactive),
),
)
as String);
@override
String get trendBalanced =>
(super.noSuchMethod(
Invocation.getter(#trendBalanced),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#trendBalanced),
),
)
as String);
@override
String get trendSluggish =>
(super.noSuchMethod(
Invocation.getter(#trendSluggish),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#trendSluggish),
),
)
as String);
@override
String get chartAverageWindow =>
(super.noSuchMethod(
Invocation.getter(#chartAverageWindow),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#chartAverageWindow),
),
)
as String);
@override
String get chartTypeDistribution =>
(super.noSuchMethod(
Invocation.getter(#chartTypeDistribution),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#chartTypeDistribution),
),
)
as String);
@override
String get distributionMedian =>
(super.noSuchMethod(
Invocation.getter(#distributionMedian),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#distributionMedian),
),
)
as String);
@override
String get distributionLatest =>
(super.noSuchMethod(
Invocation.getter(#distributionLatest),
returnValue: _i3.dummyValue<String>(
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<String>(
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<String>(
this,
Invocation.method(#chartWeeklyChangeTitle, [name]),
),
)
as String);
@override
String chartAverageWindowDays(int? days) =>
(super.noSuchMethod(
Invocation.method(#chartAverageWindowDays, [days]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#chartAverageWindowDays, [days]),
),
)
as String);
@override
String chartDistributionTitle(String? name) =>
(super.noSuchMethod(
Invocation.method(#chartDistributionTitle, [name]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#chartDistributionTitle, [name]),
),
)
as String);
@override
String distributionEntryCount(int? count) =>
(super.noSuchMethod(
Invocation.method(#distributionEntryCount, [count]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#distributionEntryCount, [count]),
),
)
as String);
@override
String distributionDayCount(int? count) =>
(super.noSuchMethod(
Invocation.method(#distributionDayCount, [count]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#distributionDayCount, [count]),
),
)
as String);
@override
String minLengthRoutine(int? number) =>
(super.noSuchMethod(

View File

@@ -112,6 +112,42 @@ void main() {
});
});
group('chartConfig', () {
MeasurementCategory withConfig(Map<String, dynamic> 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);

View File

@@ -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', () {

View File

@@ -131,6 +131,94 @@ void main() {
expect(find.byType(DropdownButtonFormField<ChartType>), 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<TrendCharacter>), findsOneWidget);
expect(find.byType(DropdownButtonFormField<int>), 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<TrendCharacter>), findsNothing);
expect(find.byType(DropdownButtonFormField<int>), 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<DropdownButtonFormField<TrendCharacter>>(
find.byType(DropdownButtonFormField<TrendCharacter>),
)
.onChanged,
isNull,
);
expect(
tester
.widget<DropdownButtonFormField<int>>(
find.byType(DropdownButtonFormField<int>),
)
.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<DropdownButtonFormField<TrendCharacter>>(
find.byType(DropdownButtonFormField<TrendCharacter>),
)
.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<TrendCharacter>));
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];

View File

@@ -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<LineChart>(find.byType(LineChart)).toList();