feat(charts): add smoothed trendline to measurement charts

- Implement centered moving average trendline in charts.dart.
- Update MeasurementChartWidgetFl to render trendline bar data.
- Integrate smoothedTreadline logic into metric chart builder.

refactor(db): implement MetricType Drift converter
- Add MeasurementMetricTypeConverter to map enum to SQLite text.
- Update MeasurementCategoryTable to use the new converter.
This commit is contained in:
pankaj-basnet
2026-07-04 17:38:35 +05:45
parent 6c3373fc73
commit 5ff9d259d3
7 changed files with 94 additions and 9 deletions

View File

@@ -0,0 +1,31 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2020 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:drift/drift.dart';
import 'package:wger/models/measurements/measurement_category.dart';
/// Maps a [MetricType] to and from the SQLite string format.
class MeasurementMetricTypeConverter extends TypeConverter<MetricType, String> {
const MeasurementMetricTypeConverter();
@override
MetricType fromSql(String fromDb) => MetricType.fromWire(fromDb);
@override
String toSql(MetricType value) => value.wireValue;
}

View File

@@ -23,6 +23,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:powersync/powersync.dart' as ps;
import 'package:wger/database/converters/date_only_text_converter.dart';
import 'package:wger/database/converters/exercise_image_style_converter.dart';
import 'package:wger/database/converters/measurement_metric_type_converter.dart';
import 'package:wger/database/converters/time_of_day_converter.dart';
import 'package:wger/database/converters/utc_datetime_converter.dart';
import 'package:wger/database/converters/workout_impression_converter.dart';

View File

@@ -18,6 +18,7 @@
import 'package:drift/drift.dart';
import 'package:powersync/powersync.dart' as ps;
import 'package:wger/database/converters/measurement_metric_type_converter.dart';
import 'package:wger/database/converters/utc_datetime_converter.dart';
import 'package:wger/models/measurements/measurement_category.dart';
import 'package:wger/models/measurements/measurement_entry.dart';
@@ -31,16 +32,12 @@ class MeasurementCategoryTable extends Table {
TextColumn get name => text()();
TextColumn get unit => text()();
TextColumn get metricType => text().named('metric_type').withDefault(const Constant('custom'))();
TextColumn get metricType => text().map(const MeasurementMetricTypeConverter())();
}
const PowersyncMeasurementCategoryTable = ps.Table(
'measurements_category',
[
ps.Column.text('name'),
ps.Column.text('unit'),
// ps.Column.text('metric_type')
],
[ps.Column.text('name'), ps.Column.text('unit'), ps.Column.text('metric_type')],
);
@UseRowClass(MeasurementEntry)

View File

@@ -122,7 +122,7 @@ class MeasurementCategory with _$MeasurementCategory {
id: id != null ? Value(id!) : const Value.absent(),
name: Value(name),
unit: Value(unit),
metricType: Value(metricType.wireValue)
metricType: Value(metricType),
);
}
}

View File

@@ -55,9 +55,10 @@ String weightUnit(bool isMetric, BuildContext context) {
class MeasurementChartWidgetFl extends StatefulWidget {
final List<MeasurementChartEntry> _entries;
final List<MeasurementChartEntry>? avgs;
final List<MeasurementChartEntry>? trend;
final String _unit;
const MeasurementChartWidgetFl(this._entries, this._unit, {this.avgs});
const MeasurementChartWidgetFl(this._entries, this._unit, {this.avgs, this.trend});
@override
State<MeasurementChartWidgetFl> createState() => _MeasurementChartWidgetFlState();
@@ -212,6 +213,17 @@ class _MeasurementChartWidgetFlState extends State<MeasurementChartWidgetFl> {
barWidth: 1,
dotData: const FlDotData(show: false),
),
if (widget.trend != null && widget.trend!.isNotEmpty)
LineChartBarData(
spots: widget.trend!
.map((e) => FlSpot(e.date.millisecondsSinceEpoch.toDouble(), e.value.toDouble()))
.toList(),
isCurved: true,
curveSmoothness: 0.4,
color: Theme.of(context).colorScheme.secondary,
barWidth: 3,
dotData: const FlDotData(show: false),
),
],
);
}
@@ -382,6 +394,38 @@ class _MeasurementBarChartWidgetFlState extends State<MeasurementBarChartWidgetF
}
}
/// Produces a smoothed trendline via a Exponential Moving Average (EMA).
/// Produces a smoothed trendline via a Centered Moving Average (CMA).
List<MeasurementChartEntry> smoothedTrendline(
List<MeasurementChartEntry> vals, {
// int windowDays = 14,
int period = 10,
}) {
if (vals.isEmpty) {
return [];
}
final sorted = [...vals]..sort((a, b) => a.date.compareTo(b.date));
final List<MeasurementChartEntry> out = [];
// Seed the initialization layer with the first data point value
double currentEma = sorted[0].value.toDouble();
final double smoothing = 2 / (period + 1);
for (int i = 0; i < sorted.length; i++) {
final point = sorted[i];
if (i > 0) {
// EMA equation: point.weight * smoothing + ema * (1 - smoothing)
currentEma = (point.value * smoothing) + (currentEma * (1 - smoothing));
}
out.add(MeasurementChartEntry(currentEma, point.date));
}
return out;
}
class Indicator extends StatelessWidget {
const Indicator({
super.key,

View File

@@ -101,7 +101,7 @@ class _MeasurementCategoryFormState extends ConsumerState<MeasurementCategoryFor
initialValue: _draft.metricType,
decoration: InputDecoration(labelText: AppLocalizations.of(context).metricType),
items: MetricType.values
.map((t) => DropdownMenuItem(value: t, child: Text(t.name)))
.map((t) => DropdownMenuItem(value: t, child: Text(t.localized(context))))
.toList(),
onChanged: (value) {
if (value != null) {

View File

@@ -95,6 +95,14 @@ List<Widget> getOverviewWidgetsSeries(
text: AppLocalizations.of(context).indicatorAvg,
isSquare: true,
),
// if (!metricType.isSummedPerDay && !metricType.isRangeType)
if (!metricType.isSummedPerDay)
Indicator(
color: Theme.of(context).colorScheme.secondary,
text: 'trend',
// text: AppLocalizations.of(context).indicatorTrend,
isSquare: true,
),
],
),
];
@@ -136,9 +144,13 @@ Widget buildChartForMetricType(
if (metricType.isSummedPerDay) {
return MeasurementBarChartWidgetFl(aggregatePerDay(raw), unit);
}
// if (metricType.isRangeType) {
// return buildRangeChartForMetricType(metricType, raw, unit);
// }
return MeasurementChartWidgetFl(
raw,
unit,
avgs: avg,
trend: smoothedTrendline(raw),
);
}