Chart a group as a whole, and let it be opened

This commit is contained in:
Roland Geider
2026-08-02 14:05:54 +02:00
parent 3a26357a2c
commit e1b5f1345b
13 changed files with 727 additions and 47 deletions

View File

@@ -132,6 +132,11 @@ enum MetricType {
/// The components of this group, in group order; empty for every other type
List<(MetricType, String)> get components => _groupComponents[this] ?? const [];
/// `true` for the component that rolls its siblings up instead of being one
/// part next to them. Total sleep already covers the stages beside it, so a
/// stacked chart has to leave it out or it counts every night twice.
bool get isGroupTotal => this == MetricType.sleepTotal;
/// `true` for the types whose category id is derived instead of random,
/// see [deterministicCategoryId]. Body weight is excluded: the server
/// creates that category itself and the app looks it up by [isOfficial].

View File

@@ -134,7 +134,11 @@ class _MeasurementEntriesScreenState extends ConsumerState<MeasurementEntriesScr
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).newEntry,
MeasurementEntryForm(_categoryId),
// A group holds no entries itself: one reading is a value per
// component, entered in one go
category.isGroup
? GroupMeasurementEntryForm(category)
: MeasurementEntryForm(_categoryId),
),
);
},

View File

@@ -142,20 +142,20 @@ class CategoriesCard extends StatelessWidget {
/// chart, then one row per component with its latest reading; new readings
/// are entered for all components at once.
Widget _buildGroupCard(BuildContext context) {
// Two components are one reading with a low and a high end, so they are
// drawn as a bar spanning it. Anything else stays one line per component:
// more than two components cannot be a range, and neither can readings
// that are not paired, which happens once the date of one half is edited
// apart from the other.
final cutoff = range.cutoff;
final ranges = currentCategory.children.length == 2
? groupRangeEntries(currentCategory, cutoff: cutoff)
: const <MeasurementChartEntry>[];
final asRange = ranges.isNotEmpty;
final series = asRange
? const <MeasurementChartSeries>[]
: groupComponentSeries(currentCategory, cutoff: cutoff);
final hasData = asRange || series.any((s) => s.entries.isNotEmpty);
final hasData = groupHasData(currentCategory, cutoff: cutoff);
// A range is a single bar whose ends speak for themselves, and a stacked
// bar's segments carry the component colours; only the line chart needs
// the dots on the rows below to tie a component to its line.
final asRange =
currentCategory.children.length == 2 &&
groupRangeEntries(currentCategory, cutoff: cutoff).isNotEmpty;
// The stacked chart draws only the components that are parts of the whole,
// so a row's colour has to come from that list rather than from its
// position among all children
final stacked = currentCategory.metricType.isSummedPerDay
? stackableComponents(currentCategory)
: null;
return Card(
elevation: elevation,
@@ -176,25 +176,27 @@ class CategoriesCard extends StatelessWidget {
Container(
padding: const EdgeInsets.all(10),
height: 220,
child: asRange
? MeasurementBarChartWidgetFl(ranges, currentCategory.unit)
: MeasurementChartWidgetFl(series, currentCategory.unit),
child: buildGroupChart(context, currentCategory, cutoff: cutoff),
),
...currentCategory.children.mapIndexed((index, child) {
// Entries arrive sorted by date descending, so first is the latest
final latest = child.entries.firstOrNull;
final colorIndex = stacked == null
? index
: stacked.indexWhere((c) => c.id == child.id);
return ListTile(
dense: true,
// The dot ties the row to its line in the chart above. A range
// is a single bar, where the ends speak for themselves.
leading: asRange
// The dot ties the row to its part of the chart above. A range
// is a single bar, where the ends speak for themselves, and a
// roll-up component is no segment of the stack.
leading: asRange || colorIndex < 0
? null
: Container(
width: 12,
height: 12,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: componentColor(context, index),
color: componentColor(context, colorIndex),
),
),
title: Text(child.name),
@@ -212,21 +214,33 @@ class CategoriesCard extends StatelessWidget {
);
}),
const Divider(),
Align(
alignment: Alignment.centerRight,
child: IconButton(
onPressed: () async {
await Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).newEntry,
GroupMeasurementEntryForm(currentCategory),
),
);
},
icon: const Icon(Icons.add),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
child: Text(AppLocalizations.of(context).goToDetailPage),
onPressed: () {
Navigator.pushNamed(
context,
MeasurementEntriesScreen.routeName,
arguments: currentCategory.id,
);
},
),
IconButton(
onPressed: () async {
await Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).newEntry,
GroupMeasurementEntryForm(currentCategory),
),
);
},
icon: const Icon(Icons.add),
),
],
),
],
),

View File

@@ -784,6 +784,184 @@ class _MeasurementBarChartWidgetFlState extends State<MeasurementBarChartWidgetF
}
}
/// One stacked bar: a day, and the value each component contributed to it.
///
/// [values] runs parallel to the components the chart was given, a null
/// standing for a component that has nothing on that day.
class MeasurementStackedEntry {
const MeasurementStackedEntry(this.date, this.values);
final DateTime date;
final List<num?> values;
/// The bar's full height, i.e. what the components add up to.
num get total => values.fold(0, (sum, value) => sum + (value ?? 0));
}
/// Stacked bar chart for a group whose components are parts of one whole, e.g.
/// the sleep stages of a night.
///
/// One bar per day, split into a segment per component in the components' own
/// order, so the bar's height is the night and its segments are how it was
/// spent. Colours come from [componentColor] by position, which is what ties a
/// segment to its legend entry.
class MeasurementStackedBarChartWidgetFl extends StatefulWidget {
final List<MeasurementStackedEntry> _entries;
final List<String> _labels;
final String _unit;
const MeasurementStackedBarChartWidgetFl(this._entries, this._labels, this._unit);
@override
State<MeasurementStackedBarChartWidgetFl> createState() =>
_MeasurementStackedBarChartWidgetFlState();
}
class _MeasurementStackedBarChartWidgetFlState extends State<MeasurementStackedBarChartWidgetFl> {
/// Number of dates to label on the x axis
static const X_LABEL_COUNT = 4;
/// Widest a single bar gets, for charts with only a handful of entries
static const MAX_BAR_WIDTH = 12.0;
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: 1.70,
child: Padding(
padding: const EdgeInsets.all(4),
child: LayoutBuilder(
builder: (context, constraints) => BarChart(mainData(constraints.maxWidth)),
),
),
);
}
/// The whole bar with its parts, since a single segment says little without
/// the night it belongs to.
BarTouchData tooltipData() {
return BarTouchData(
touchTooltipData: BarTouchTooltipData(
getTooltipColor: (group) => Theme.of(context).colorScheme.primaryContainer,
getTooltipItem: (group, groupIndex, rod, rodIndex) {
if (groupIndex < 0 || groupIndex >= widget._entries.length) {
return null;
}
final numberFormat = NumberFormat.decimalPattern(
Localizations.localeOf(context).toString(),
);
final entry = widget._entries[groupIndex];
final dateStr = DateFormat.Md(
Localizations.localeOf(context).languageCode,
).format(entry.date);
final parts = [
for (final (index, value) in entry.values.indexed)
if (value != null) '${widget._labels[index]}: ${numberFormat.format(value)}',
];
return BarTooltipItem(
'$dateStr: ${numberFormat.format(entry.total)} ${widget._unit}'
'${parts.isEmpty ? '' : '\n${parts.join('\n')}'}',
TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer),
);
},
),
);
}
BarChartData mainData(double availableWidth) {
final String locale = Localizations.localeOf(context).toString();
final NumberFormat numberFormat = NumberFormat.decimalPattern(locale);
final barWidth = widget._entries.isEmpty
? MAX_BAR_WIDTH
: (availableWidth / widget._entries.length * 0.7).clamp(1.0, MAX_BAR_WIDTH);
final labelStep = max(1, (widget._entries.length / X_LABEL_COUNT).ceil());
final labelOffset = labelStep ~/ 2;
final spansYears =
widget._entries.isNotEmpty &&
widget._entries.first.date.year != widget._entries.last.date.year;
return BarChartData(
barTouchData: tooltipData(),
gridData: FlGridData(
show: true,
drawVerticalLine: false,
getDrawingHorizontalLine: (value) {
return FlLine(color: Theme.of(context).colorScheme.primaryContainer, strokeWidth: 1);
},
),
titlesData: FlTitlesData(
show: true,
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
bottomTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
getTitlesWidget: (value, meta) {
final index = value.toInt();
if (index < 0 || index >= widget._entries.length) {
return const Text('');
}
if ((index - labelOffset) % labelStep != 0) {
return const Text('');
}
final DateTime date = widget._entries[index].date;
if (spansYears) {
return Text(localizedDate(context).format(date));
}
return Text(DateFormat.Md(Localizations.localeOf(context).languageCode).format(date));
},
),
),
leftTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 65,
getTitlesWidget: (value, meta) {
if (value == meta.min || value == meta.max) {
return const Text('');
}
return _YAxisLabel('${numberFormat.format(value)} ${widget._unit}');
},
),
),
),
borderData: FlBorderData(
show: true,
border: Border.all(color: Theme.of(context).colorScheme.primaryContainer),
),
barGroups: widget._entries.asMap().entries.map((e) {
// fl_chart stacks by absolute offsets rather than by segment heights,
// so each part is placed on top of what came before it
var offset = 0.0;
final stack = <BarChartRodStackItem>[];
for (final (index, value) in e.value.values.indexed) {
if (value == null || value <= 0) {
continue;
}
stack.add(
BarChartRodStackItem(offset, offset + value.toDouble(), componentColor(context, index)),
);
offset += value.toDouble();
}
return BarChartGroupData(
x: e.key,
barRods: [
BarChartRodData(
toY: offset,
width: barWidth,
rodStackItems: stack,
borderRadius: const BorderRadius.vertical(top: Radius.circular(2)),
),
],
);
}).toList(),
);
}
}
/// Produces a smoothed trendline via an Exponential Moving Average (EMA),
/// seeded with the first data point. A larger [period] tracks the raw values
/// more loosely (smoother, more lag).

View File

@@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/core/form_screen.dart';
@@ -25,6 +26,7 @@ import 'package:wger/features/measurements/measurements.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/models/unit_conversion.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
import 'package:wger/features/measurements/screens/measurement_entries_screen.dart';
import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'package:wger/features/measurements/widgets/charts.dart';
import 'package:wger/features/measurements/widgets/helpers.dart';
@@ -51,6 +53,12 @@ class _EntriesListState extends ConsumerState<EntriesList> {
final i18n = AppLocalizations.of(context);
final category = widget.category;
// A group carries no entries of its own, its readings live in the
// components, so everything below would chart an empty list
if (category.isGroup) {
return _buildGroup(context, category);
}
// Plan periods only matter where a nutrition plan can plausibly move the
// metric; other categories skip the watch, so nutrition edits don't
// rebuild them
@@ -165,4 +173,110 @@ class _EntriesListState extends ConsumerState<EntriesList> {
],
);
}
/// Detail view of a multi-value group: one chart over all components, a
/// legend that doubles as the way into each component, and the readings
/// themselves.
///
/// Readings are shown but not edited here: one of them is several entries,
/// and the group form only creates. Editing stays on the component screens,
/// which the legend rows lead to.
Widget _buildGroup(BuildContext context, MeasurementCategory category) {
final i18n = AppLocalizations.of(context);
final numberFormat = localizedNumberFormat(context);
final datetimeFormat = localizedDate(context);
final cutoff = _range.cutoff;
final hasData = groupHasData(category, cutoff: cutoff);
final readings = groupReadings(category, cutoff: cutoff);
// Only the stacked chart leaves a component out, so the colours of the
// rows below have to follow the same list
final stacked = category.metricType.isSummedPerDay ? stackableComponents(category) : null;
return Column(
children: [
ChartRangeSelector(
value: _range,
onChanged: (range) => setState(() => _range = range),
),
Text(
_range.chartTitle(i18n, category.name),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge,
),
Container(
padding: const EdgeInsets.all(15),
height: 220,
child: hasData
? buildGroupChart(context, category, cutoff: cutoff)
: Center(
child: Text(
i18n.noDataAvailable,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Theme.of(context).colorScheme.secondary.withValues(alpha: 0.7),
),
),
),
),
...category.children.mapIndexed((index, child) {
final colorIndex = stacked == null ? index : stacked.indexWhere((c) => c.id == child.id);
return ListTile(
dense: true,
leading: colorIndex < 0
? null
: Container(
width: 12,
height: 12,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: componentColor(context, colorIndex),
),
),
title: Text(child.name),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.pushNamed(
context,
MeasurementEntriesScreen.routeName,
arguments: child.id,
),
);
}),
const Divider(),
SizedBox(
height: 300,
child: ListView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: readings.length,
itemBuilder: (context, index) {
final (date, values) = readings[index];
final total = category.children
.firstWhereOrNull((c) => c.metricType.isGroupTotal)
?.name;
// A roll-up leads and the parts explain it; without one the
// values are the reading itself, written the way it is read
// (a blood pressure as 120/80)
final headline = total != null && values.containsKey(total)
? '${numberFormat.format(values[total])} ${category.unit}'
: '${values.values.sorted((a, b) => b.compareTo(a)).map(numberFormat.format).join('/')} ${category.unit}';
final parts = [
for (final MapEntry(key: name, value: value) in values.entries)
if (name != total) '$name ${numberFormat.format(value)}',
];
return Card(
child: ListTile(
title: Text(headline),
subtitle: Text(
[
datetimeFormat.format(date),
if (parts.isNotEmpty) parts.join(', '),
].join(' · '),
),
),
);
},
),
),
],
);
}
}

View File

@@ -29,7 +29,7 @@ List<Widget> getOverviewWidgets(
child: raw.isEmpty
? Center(
child: Text(
'No data available',
AppLocalizations.of(context).noDataAvailable,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Theme.of(context).colorScheme.secondary.withValues(alpha: 0.7),
),
@@ -240,6 +240,108 @@ List<MeasurementChartSeries> groupComponentSeries(MeasurementCategory group, {Da
.toList();
}
/// The components of [group] that stack into one whole, i.e. everything but a
/// roll-up component (see [MetricType.isGroupTotal]).
List<MeasurementCategory> stackableComponents(MeasurementCategory group) =>
group.children.where((c) => !c.metricType.isGroupTotal).toList();
/// One stacked bar per day for [components], stacked in the order they are
/// given.
///
/// Only days that any component reported are returned. Values are read through
/// the unit helper, like everywhere else, so a component holding mixed units
/// still stacks correctly. Only readings from [cutoff] on are included; null
/// covers the full history.
List<MeasurementStackedEntry> groupStackedEntries(
List<MeasurementCategory> components, {
DateTime? cutoff,
}) {
final byDay = <DateTime, List<num?>>{};
for (final (index, child) in components.indexed) {
for (final entry in child.entries) {
if (cutoff != null && entry.date.isBefore(cutoff)) {
continue;
}
final day = DateTime(entry.date.year, entry.date.month, entry.date.day);
final values = byDay.putIfAbsent(day, () => List<num?>.filled(components.length, null));
final value = entry.valueIn(child.unit, categoryUnit: child.unit);
// A component can hold several entries for one day (a nap next to the
// night), and the bar shows the day, so they add up
values[index] = (values[index] ?? 0) + value;
}
}
return [
for (final MapEntry(key: day, value: values) in byDay.entries)
MeasurementStackedEntry(
day,
values,
),
]..sort((a, b) => a.date.compareTo(b.date));
}
/// The chart a multi-value group gets, which follows from what its components
/// are to each other.
///
/// Components that are parts of one whole (the sleep stages) stack into one
/// bar per day. Two components that are the ends of a reading (blood pressure)
/// become one floating bar spanning them. Everything else, and anything the
/// first two have no data for, falls back to one line per component so the
/// card never goes blank while there is something to show.
Widget buildGroupChart(BuildContext context, MeasurementCategory group, {DateTime? cutoff}) {
if (group.metricType.isSummedPerDay) {
final components = stackableComponents(group);
final stacked = groupStackedEntries(components, cutoff: cutoff);
if (stacked.isNotEmpty) {
return MeasurementStackedBarChartWidgetFl(
stacked,
components.map((c) => c.name).toList(),
group.unit,
);
}
}
final ranges = group.children.length == 2
? groupRangeEntries(group, cutoff: cutoff)
: const <MeasurementChartEntry>[];
if (ranges.isNotEmpty) {
return MeasurementBarChartWidgetFl(ranges, group.unit);
}
return MeasurementChartWidgetFl(groupComponentSeries(group, cutoff: cutoff), group.unit);
}
/// The readings of a group, newest first: one per timestamp, with what each
/// component holds for it.
///
/// Components are paired by their shared timestamp, which is how the importer
/// and the group form write them. A reading only some components reported is
/// kept, listing what there is: for a group whose parts are optional (a night
/// without deep sleep) that is the normal case, not a broken pair. Only
/// readings from [cutoff] on are included; null covers the full history.
List<(DateTime, Map<String, num>)> groupReadings(MeasurementCategory group, {DateTime? cutoff}) {
final byDate = <DateTime, Map<String, num>>{};
for (final child in group.children) {
for (final entry in child.entries) {
if (cutoff != null && entry.date.isBefore(cutoff)) {
continue;
}
final values = byDate.putIfAbsent(entry.date, () => {});
final value = entry.valueIn(child.unit, categoryUnit: child.unit);
values[child.name] = (values[child.name] ?? 0) + value;
}
}
return [for (final MapEntry(key: date, value: values) in byDate.entries) (date, values)]
..sort((a, b) => b.$1.compareTo(a.$1));
}
/// Whether [group] has anything to draw at all, i.e. any component holds a
/// reading within [cutoff].
bool groupHasData(MeasurementCategory group, {DateTime? cutoff}) => group.children.any(
(child) => child.entries.any((e) => cutoff == null || !e.date.isBefore(cutoff)),
);
Widget buildChartForMetricType(
MetricType metricType,
List<MeasurementChartEntry> raw,

View File

@@ -1149,6 +1149,7 @@
"metricSleepDeep": "Tiefschlaf",
"metricSleepRem": "REM-Schlaf",
"metricSleepAwake": "Wach",
"noDataAvailable": "Keine Daten vorhanden",
"partOfGroup": "Teil der Gruppe",
"noGroup": "Keine Gruppe",
"healthSync": "Health-Synchronisation",

View File

@@ -649,6 +649,10 @@
"@metricSleep": {
"description": "Label for sleep duration measurement"
},
"noDataAvailable": "No data available",
"@noDataAvailable": {
"description": "Shown in place of a chart when the category has no entries in the selected range"
},
"metricSleepTotal": "Total sleep",
"@metricSleepTotal": {
"description": "Label for the total time asleep in a night, all sleep stages together"

View File

@@ -1188,6 +1188,7 @@
"metricSleepDeep": "Sueño profundo",
"metricSleepRem": "Sueño REM",
"metricSleepAwake": "Despierto",
"noDataAvailable": "No hay datos disponibles",
"partOfGroup": "Parte del grupo",
"noGroup": "Sin grupo",
"healthSync": "Sincronización de salud",

View File

@@ -1159,6 +1159,7 @@
"metricSleepDeep": "Sommeil profond",
"metricSleepRem": "Sommeil paradoxal",
"metricSleepAwake": "Éveillé",
"noDataAvailable": "Aucune donnée disponible",
"partOfGroup": "Fait partie du groupe",
"noGroup": "Aucun groupe",
"healthSync": "Synchronisation santé",