From a0fddd62c910b5f00a0709d41aae00168965f681 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 6 Aug 2026 21:11:09 +0200 Subject: [PATCH] Tidy up the measurement and health helpers --- lib/features/health/models/health_metric.dart | 36 +++++++++----- .../health/providers/health_sync.dart | 2 +- .../health/providers/health_sync.g.dart | 2 +- .../models/measurement_category.dart | 8 ++-- .../providers/measurement_notifier.dart | 14 ++---- .../providers/measurement_notifier.g.dart | 2 +- .../providers/measurement_repository.dart | 11 +++++ .../screens/measurement_entries_screen.dart | 2 +- .../measurements/widgets/categories_card.dart | 2 +- .../measurements/widgets/entries.dart | 14 +++--- lib/features/measurements/widgets/forms.dart | 10 ++-- .../measurements/widgets/helpers.dart | 47 ++++++++++--------- .../nutrition/widgets/plan_weight_chart.dart | 10 ++-- 13 files changed, 93 insertions(+), 67 deletions(-) diff --git a/lib/features/health/models/health_metric.dart b/lib/features/health/models/health_metric.dart index ece506655..0e6d2795c 100644 --- a/lib/features/health/models/health_metric.dart +++ b/lib/features/health/models/health_metric.dart @@ -56,21 +56,35 @@ enum DailyAggregation { class HealthMetric { const HealthMetric({ required this.metricType, - required this.dataType, + required HealthDataType this.dataType, required this.toCategoryValue, - this.components = const [], this.dailyAggregation, this.dayRollsOverAtHour, this.enabled = false, this.disabledReason, this.readWindow = defaultReadWindow, - }); + }) : components = const []; + + /// A metric whose readings are split over several categories, e.g. blood + /// pressure. It has no platform type of its own: what it reads is what its + /// [components] read. + const HealthMetric.group({ + required this.metricType, + required this.components, + required this.toCategoryValue, + this.dailyAggregation, + this.dayRollsOverAtHour, + this.enabled = false, + this.disabledReason, + this.readWindow = defaultReadWindow, + }) : dataType = null; /// Metric type stored on the category, e.g. [MetricType.bodyFat]. final MetricType metricType; - /// Health platform type this metric reads. - final HealthDataType dataType; + /// Health platform type this metric reads, null for a group, whose + /// components carry theirs. + final HealthDataType? dataType; /// Name and unit the category is created under. They belong to the metric /// type, so a category the user creates by hand looks the same. @@ -118,8 +132,10 @@ class HealthMetric { /// All platform types this metric reads (the components' for a group), each /// one once even when several components read it. - List get dataTypes => - components.isEmpty ? [dataType] : components.expand((c) => c.dataTypes).toSet().toList(); + List get dataTypes { + final type = dataType; + return type != null ? [type] : components.expand((c) => c.dataTypes).toSet().toList(); + } } /// One component of a multi-value metric (e.g. systolic), imported into its @@ -168,9 +184,8 @@ const List healthMetrics = [ toCategoryValue: _identity, enabled: true, ), - HealthMetric( + HealthMetric.group( metricType: MetricType.bloodPressure, - dataType: HealthDataType.BLOOD_PRESSURE_SYSTOLIC, toCategoryValue: _identity, // Both platforms report mmHg; a reading is the systolic/diastolic pair // sharing one timestamp. @@ -201,7 +216,7 @@ const List healthMetrics = [ toCategoryValue: _identity, enabled: true, ), - HealthMetric( + HealthMetric.group( // SLEEP_ASLEEP is not the whole night, it is the coarsest stage: the // plugin filters it down to HealthKit's asleepUnspecified and to Health // Connect's STAGE_TYPE_SLEEPING. Anything writing a real hypnogram (an @@ -210,7 +225,6 @@ const List healthMetrics = [ // total therefore rolls the stages up, and each stage also gets its own // category. All types report minutes on both platforms. metricType: MetricType.sleep, - dataType: HealthDataType.SLEEP_ASLEEP, toCategoryValue: _identity, components: [ HealthMetricComponent( diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index 17a98c532..788204b9b 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -293,7 +293,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { // own category, or one child per component for a group metric. final List<(MeasurementCategory, Iterable)> targets; if (metric.components.isEmpty) { - final metricReadings = readings.where((r) => r.type == metric.dataType); + final metricReadings = readings.where((r) => metric.dataTypes.contains(r.type)); if (metricReadings.isEmpty) { if (readsFullHistory && withoutCategory.contains(metric.metricType.name)) { knownEmpty.add(metric.metricType.name); diff --git a/lib/features/health/providers/health_sync.g.dart b/lib/features/health/providers/health_sync.g.dart index 65985c959..667121e6c 100644 --- a/lib/features/health/providers/health_sync.g.dart +++ b/lib/features/health/providers/health_sync.g.dart @@ -56,7 +56,7 @@ final class HealthSyncNotifierProvider } } -String _$healthSyncNotifierHash() => r'ccc81caa4644114131dece9668817c26bf126932'; +String _$healthSyncNotifierHash() => r'299b7408f5fe389d19bd3b371c1972a977b8c3b0'; /// Imports body metrics from Apple Health / Health Connect into measurement /// categories. Read-only: reads the platform (via [HealthRepository]), writes to diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index 32f0ac1ad..23cdd735e 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -554,8 +554,9 @@ class MeasurementCategory with _$MeasurementCategory { copyWith(chartConfig: {...?chartConfig, key: value}); /// `true` for group parents (blood pressure etc.), which hold no entries of - /// their own - bool get isGroup => children.isNotEmpty; + /// their own. Answers for this row: a group whose components have not synced + /// yet has none, unlike the structural [MetricType.isGroup]. + bool get hasChildren => children.isNotEmpty; /// The user's body weight category. It has its own screens (weight feature) /// and is hidden from the general measurements UI. @@ -567,7 +568,8 @@ class MeasurementCategory with _$MeasurementCategory { /// differently, and a group has neither: its name and unit come from the /// metric type and its chart from what its components are to each other. bool get isEditable => - metricType == MetricType.custom || (!isGroup && metricType.availableChartTypes.isNotEmpty); + metricType == MetricType.custom || + (!hasChildren && metricType.availableChartTypes.isNotEmpty); MeasurementEntry findEntryById(String id) { return entries.firstWhere( diff --git a/lib/features/measurements/providers/measurement_notifier.dart b/lib/features/measurements/providers/measurement_notifier.dart index 83209d67f..13e922afb 100644 --- a/lib/features/measurements/providers/measurement_notifier.dart +++ b/lib/features/measurements/providers/measurement_notifier.dart @@ -133,11 +133,6 @@ final class MeasurementNotifier extends _$MeasurementNotifier { return _repo.watchAll(); } - Stream watchCategoryById(String id) { - _logger.finer('Watching local measurement category $id'); - return _repo.watchLocalDriftCategoryById(id); - } - Future getCategoryById(String id) async { // Data already loaded final categories = state.asData?.value; @@ -193,13 +188,13 @@ final class MeasurementNotifier extends _$MeasurementNotifier { final parent = category.copyWith( id: category.id ?? deterministicCategoryId(userId, category.metricType), ); - await _repo.addLocalDriftCategory(parent); // A group is a container, its readings live in one child per component. // The server creates them as well, on the same ids, so whichever side // gets there first wins and the other is acknowledged as a no-op - for (final (order, metricType) in parent.metricType.components.indexed) { - await _repo.addLocalDriftCategory( + await _repo.addLocalDriftCategoryGroup([ + parent, + for (final (order, metricType) in parent.metricType.components.indexed) MeasurementCategory( id: deterministicCategoryId(userId, metricType), name: metricType.canonicalName, @@ -208,8 +203,7 @@ final class MeasurementNotifier extends _$MeasurementNotifier { parentId: parent.id, order: order, ), - ); - } + ]); return parent.id; } diff --git a/lib/features/measurements/providers/measurement_notifier.g.dart b/lib/features/measurements/providers/measurement_notifier.g.dart index 2e8a0007e..c6e3b50c1 100644 --- a/lib/features/measurements/providers/measurement_notifier.g.dart +++ b/lib/features/measurements/providers/measurement_notifier.g.dart @@ -734,7 +734,7 @@ final class MeasurementNotifierProvider MeasurementNotifier create() => MeasurementNotifier(); } -String _$measurementNotifierHash() => r'c34dc2058c56e502cba8f1d84d867347dcc02f79'; +String _$measurementNotifierHash() => r'afc8a100a40967bd8e7ea41bdd1985502878fc12'; abstract class _$MeasurementNotifier extends $StreamNotifier> { Stream> build(); diff --git a/lib/features/measurements/providers/measurement_repository.dart b/lib/features/measurements/providers/measurement_repository.dart index 8e4b1c977..af463de83 100644 --- a/lib/features/measurements/providers/measurement_repository.dart +++ b/lib/features/measurements/providers/measurement_repository.dart @@ -562,6 +562,17 @@ class MeasurementRepository { await _db.into(_db.measurementCategoryTable).insert(category.toCompanion()); } + /// Inserts a group together with its components, in a single transaction so + /// a group is never left without the children its readings live in. + Future addLocalDriftCategoryGroup(List categories) async { + _logger.finer('Adding a local measurement group of ${categories.length} categories'); + await _db.transaction(() async { + for (final category in categories) { + await _db.into(_db.measurementCategoryTable).insert(category.toCompanion()); + } + }); + } + /// Persists the given display order: each category gets its list index as /// [MeasurementCategory.order]. Categories whose order is unchanged are not /// written, so no sync upload is queued for them. diff --git a/lib/features/measurements/screens/measurement_entries_screen.dart b/lib/features/measurements/screens/measurement_entries_screen.dart index ccb1060ef..203c6429e 100644 --- a/lib/features/measurements/screens/measurement_entries_screen.dart +++ b/lib/features/measurements/screens/measurement_entries_screen.dart @@ -138,7 +138,7 @@ class _MeasurementEntriesScreenState extends ConsumerState { num? _value; String _notes = ''; + /// Read once: a future built in build() is a new one on every rebuild, which + /// sends the FutureBuilder back to its loading state. + late final Future _categoryFuture; + @override void initState() { super.initState(); _value = widget._entry?.value; _notes = widget._entry?.notes ?? ''; _notesController.text = _notes; + _categoryFuture = ref.read(measurementProvider.notifier).getCategoryById(widget._categoryId); } @override @@ -308,12 +313,9 @@ class _MeasurementEntryFormState extends ConsumerState { @override Widget build(BuildContext context) { final notifier = ref.read(measurementProvider.notifier); - final Future categoryFuture = notifier.getCategoryById( - widget._categoryId, - ); return FutureBuilder( - future: categoryFuture, + future: _categoryFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const BoxedProgressIndicator(); diff --git a/lib/features/measurements/widgets/helpers.dart b/lib/features/measurements/widgets/helpers.dart index 3c307dd51..9241418e8 100644 --- a/lib/features/measurements/widgets/helpers.dart +++ b/lib/features/measurements/widgets/helpers.dart @@ -13,12 +13,13 @@ import 'package:wger/features/measurements/widgets/chart_range_selector.dart'; import 'package:wger/features/measurements/widgets/charts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -List getOverviewWidgets( - String title, - List raw, - List avg, - String unit, +/// A titled chart with the overall change below it, for a Column to spread. +List buildChartSection( BuildContext context, { + required String title, + required List raw, + required List avg, + required String unit, MetricType metricType = MetricType.custom, List planPeriods = const [], List? trend, @@ -61,13 +62,15 @@ List getOverviewWidgets( ]; } -List getOverviewWidgetsSeries( - String name, - List entriesAll, - List average, - List planPeriods, - String unit, +/// The chart of a measurement series: [buildChartSection] for the chart the +/// type resolves to, plus the legend naming the lines it draws. +List buildSeriesChartSection( BuildContext context, { + required String name, + required List entriesAll, + required List average, + required String unit, + List planPeriods = const [], MetricType metricType = MetricType.custom, String? mainChartTitle, ChartType chartType = ChartType.auto, @@ -86,21 +89,21 @@ List getOverviewWidgetsSeries( if (resolved == ChartType.heatmap || resolved == ChartType.delta || resolved == ChartType.distribution) { - return getOverviewWidgets( + return buildChartSection( + context, // The selector right above names the range, so the title says what the // bars are instead - switch (resolved) { + title: switch (resolved) { ChartType.delta => AppLocalizations.of(context).chartWeeklyChangeTitle(name), ChartType.distribution => AppLocalizations.of(context).chartDistributionTitle(name), _ => title, }, - entriesAll, + raw: entriesAll, // 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 ? average : const [], - unit, - context, + avg: resolved == ChartType.delta && !metricType.isSummedPerDay ? average : const [], + unit: unit, metricType: metricType, chartType: chartType, settings: settings, @@ -113,12 +116,12 @@ List getOverviewWidgetsSeries( final summed = metricType.isSummedPerDay; final trendAll = summed ? null : smoothedTrendline(entriesAll, period: settings.trend.emaPeriod); return [ - ...getOverviewWidgets( - title, - entriesAll, - average, - unit, + ...buildChartSection( context, + title: title, + raw: entriesAll, + avg: average, + unit: unit, metricType: metricType, planPeriods: planPeriods, trend: trendAll, diff --git a/lib/features/nutrition/widgets/plan_weight_chart.dart b/lib/features/nutrition/widgets/plan_weight_chart.dart index cfc11e421..5cf0c9881 100644 --- a/lib/features/nutrition/widgets/plan_weight_chart.dart +++ b/lib/features/nutrition/widgets/plan_weight_chart.dart @@ -67,12 +67,12 @@ class PlanWeightChart extends ConsumerWidget { final avg = movingAverage(points, days: settings.averageWindow); return Column( - children: getOverviewWidgets( - AppLocalizations.of(context).weight, - points, - avg, - weightUnit(profile.isMetric, context), + children: buildChartSection( context, + title: AppLocalizations.of(context).weight, + raw: points, + avg: avg, + unit: weightUnit(profile.isMetric, context), metricType: category.metricType, settings: settings, ),