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

View File

@@ -71,6 +71,40 @@ MeasurementCategory _tripleGroup() {
return testMeasurementCategoryBloodPressure.copyWith(children: children);
}
/// A sleep group: the total plus two stages, all on the same night
MeasurementCategory _sleepGroup() {
MeasurementCategory child(String id, String name, MetricType type, int order, num value) =>
MeasurementCategory(
id: id,
name: name,
unit: 'min',
metricType: type,
parentId: 'sleep',
order: order,
entries: [
MeasurementEntry(
id: 'e-$id',
categoryId: id,
date: DateTime(2026, 1, 2),
value: value,
notes: '',
),
],
);
return MeasurementCategory(
id: 'sleep',
name: 'Sleep',
unit: 'min',
metricType: MetricType.sleep,
children: [
child('total', 'Total sleep', MetricType.sleepTotal, 0, 480),
child('deep', 'Deep sleep', MetricType.sleepDeep, 1, 90),
child('rem', 'REM sleep', MetricType.sleepRem, 2, 60),
],
);
}
void main() {
group('CategoriesCard group card', () {
testWidgets('shows one ListTile per child with latest reading', (tester) async {
@@ -167,6 +201,36 @@ void main() {
expect(find.byIcon(Icons.add), findsOneWidget);
});
testWidgets('the group itself can be opened, like any other category', (tester) async {
await tester.pumpWidget(_card(_bpGroup(withEntries: true)));
await tester.pumpAndSettle();
expect(find.text('Go to detail page'), findsOneWidget);
});
testWidgets('sleep stacks its stages into one bar per night', (tester) async {
await tester.pumpWidget(_card(_sleepGroup()));
await tester.pumpAndSettle();
final groups = tester.widget<BarChart>(find.byType(BarChart)).data.barGroups;
expect(groups, hasLength(1));
// The stages stack, the total does not: it already covers them
final rod = groups.single.barRods.single;
expect(rod.rodStackItems.map((s) => s.toY - s.fromY), [90, 60]);
expect(rod.toY, 150);
});
testWidgets('the roll-up row gets no colour dot', (tester) async {
await tester.pumpWidget(_card(_sleepGroup()));
await tester.pumpAndSettle();
// Total sleep is no segment of the stack, so no colour identifies it
final tiles = tester.widgetList<ListTile>(find.byType(ListTile)).toList();
expect(tiles.first.leading, isNull);
expect(tiles.skip(1).every((t) => t.leading != null), isTrue);
});
});
group('CategoriesCard daily aggregates', () {

View File

@@ -24,6 +24,7 @@ import 'package:mockito/mockito.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/models/measurement_entry.dart';
import 'package:wger/features/measurements/providers/measurement_repository.dart';
import 'package:wger/features/measurements/widgets/charts.dart';
import 'package:wger/features/measurements/widgets/entries.dart';
import 'package:wger/features/nutrition/providers/ingredient_repository.dart';
import 'package:wger/features/nutrition/providers/nutrition_repository.dart';
@@ -64,16 +65,7 @@ void main() {
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: SingleChildScrollView(
child: EntriesList(
MeasurementCategory(
id: category.id,
name: category.name,
unit: category.unit,
entries: category.entries,
),
),
),
body: SingleChildScrollView(child: EntriesList(category)),
),
),
);
@@ -96,4 +88,51 @@ void main() {
expect(find.byTooltip('Show menu'), findsOneWidget);
expect(find.byIcon(Icons.monitor_heart_outlined), findsOneWidget);
});
testWidgets('A group charts its components and lists the readings', (
WidgetTester tester,
) async {
// The list defaults to the last three months, so a fixed date would fall
// out of the range as time passes
final night = DateTime.now().subtract(const Duration(days: 1));
MeasurementCategory child(String id, String name, MetricType type, int order, num value) =>
MeasurementCategory(
id: id,
name: name,
unit: 'min',
metricType: type,
parentId: 'sleep',
order: order,
entries: [
MeasurementEntry(
id: 'e-$id',
categoryId: id,
date: night,
value: value,
notes: '',
),
],
);
final group = MeasurementCategory(
id: 'sleep',
name: 'Sleep',
unit: 'min',
metricType: MetricType.sleep,
children: [
child('total', 'Total sleep', MetricType.sleepTotal, 0, 480),
child('deep', 'Deep sleep', MetricType.sleepDeep, 1, 90),
],
);
await tester.pumpWidget(createEntriesList(group));
await tester.pumpAndSettle();
// The group holds no entries itself, so its own list would be empty: it
// shows the components' readings instead, the roll-up leading
expect(find.byType(MeasurementStackedBarChartWidgetFl), findsOneWidget);
expect(find.text('480 min'), findsOneWidget);
expect(find.textContaining('Deep sleep 90'), findsOneWidget);
// Each component is a way into its own screen
expect(find.byIcon(Icons.chevron_right), findsNWidgets(2));
});
}

View File

@@ -154,6 +154,159 @@ void main() {
});
});
group('group charts', () {
MeasurementEntry entry(String categoryId, DateTime date, num value) =>
MeasurementEntry(categoryId: categoryId, date: date, value: value, notes: '');
/// A sleep group as the importer writes it: the total plus its stages.
MeasurementCategory sleepGroup({bool withStages = true}) => MeasurementCategory(
id: 'g',
name: 'Sleep',
unit: 'min',
metricType: MetricType.sleep,
children: [
MeasurementCategory(
id: 'total',
name: 'Total sleep',
unit: 'min',
metricType: MetricType.sleepTotal,
parentId: 'g',
entries: [entry('total', DateTime(2026, 1, 2), 480)],
),
MeasurementCategory(
id: 'deep',
name: 'Deep sleep',
unit: 'min',
metricType: MetricType.sleepDeep,
parentId: 'g',
order: 1,
entries: withStages ? [entry('deep', DateTime(2026, 1, 2), 90)] : const [],
),
MeasurementCategory(
id: 'rem',
name: 'REM sleep',
unit: 'min',
metricType: MetricType.sleepRem,
parentId: 'g',
order: 2,
entries: withStages ? [entry('rem', DateTime(2026, 1, 2), 60)] : const [],
),
],
);
MeasurementCategory bloodPressure() => MeasurementCategory(
id: 'bp',
name: 'Blood pressure',
unit: 'mmHg',
metricType: MetricType.bloodPressure,
children: [
MeasurementCategory(
id: 'sys',
name: 'Systolic',
unit: 'mmHg',
metricType: MetricType.bloodPressureSystolic,
parentId: 'bp',
entries: [entry('sys', DateTime(2026, 1, 2, 8), 120)],
),
MeasurementCategory(
id: 'dia',
name: 'Diastolic',
unit: 'mmHg',
metricType: MetricType.bloodPressureDiastolic,
parentId: 'bp',
order: 1,
entries: [entry('dia', DateTime(2026, 1, 2, 8), 80)],
),
],
);
test('the roll-up component is left out of the stack', () {
// Total sleep covers the stages, so stacking it would count the night
// twice
expect(
stackableComponents(sleepGroup()).map((c) => c.metricType),
[MetricType.sleepDeep, MetricType.sleepRem],
);
expect(stackableComponents(bloodPressure()), hasLength(2));
});
test('stacked entries carry one value per component and day', () {
final components = stackableComponents(sleepGroup());
final stacked = groupStackedEntries(components);
expect(stacked, hasLength(1));
expect(stacked.single.date, DateTime(2026, 1, 2));
expect(stacked.single.values, [90, 60]);
expect(stacked.single.total, 150);
});
test('several entries of one day add up within their component', () {
// A nap next to the night: the bar shows the day, not the segment
final group = MeasurementCategory(
id: 'g',
name: 'Sleep',
unit: 'min',
metricType: MetricType.sleep,
children: [
MeasurementCategory(
id: 'deep',
name: 'Deep sleep',
unit: 'min',
metricType: MetricType.sleepDeep,
parentId: 'g',
entries: [
entry('deep', DateTime(2026, 1, 2, 3), 90),
entry('deep', DateTime(2026, 1, 2, 14), 20),
],
),
],
);
expect(groupStackedEntries(group.children).single.values, [110]);
});
test('readings pair the components on their shared timestamp', () {
final readings = groupReadings(bloodPressure());
expect(readings, hasLength(1));
expect(readings.single.$1, DateTime(2026, 1, 2, 8));
expect(readings.single.$2, {'Systolic': 120, 'Diastolic': 80});
});
testWidgets('a summed group stacks its components', (tester) async {
await tester.pumpWidget(
_wrapChart(Builder(builder: (ctx) => buildGroupChart(ctx, sleepGroup()))),
);
await tester.pumpAndSettle();
expect(find.byType(MeasurementStackedBarChartWidgetFl), findsOneWidget);
});
testWidgets('a two-component group is a floating bar per reading', (tester) async {
await tester.pumpWidget(
_wrapChart(Builder(builder: (ctx) => buildGroupChart(ctx, bloodPressure()))),
);
await tester.pumpAndSettle();
expect(find.byType(MeasurementBarChartWidgetFl), findsOneWidget);
expect(find.byType(MeasurementStackedBarChartWidgetFl), findsNothing);
});
testWidgets('without stage data the group falls back to lines', (tester) async {
// Only the total reported, so there is nothing to stack. Falling through
// to the line chart keeps the card from going blank while data exists
await tester.pumpWidget(
_wrapChart(
Builder(builder: (ctx) => buildGroupChart(ctx, sleepGroup(withStages: false))),
),
);
await tester.pumpAndSettle();
expect(find.byType(MeasurementStackedBarChartWidgetFl), findsNothing);
expect(find.byType(MeasurementChartWidgetFl), findsOneWidget);
});
});
group('getOverviewWidgets', () {
testWidgets('empty raw shows no-data placeholder', (tester) async {
await _pumpWidgetList(tester, (ctx) => getOverviewWidgets('Test', [], [], 'cm', ctx));