diff --git a/lib/core/formatting/formatting.dart b/lib/core/formatting/formatting.dart index 864bddd41..ba08515fc 100644 --- a/lib/core/formatting/formatting.dart +++ b/lib/core/formatting/formatting.dart @@ -50,9 +50,17 @@ String hoursAndMinutes(num minutes, String locale) { /// A measured value on its own, formatted the way its unit is read. For the /// ends of a range, where only the last one carries the unit. -String measurementValue(BuildContext context, num value, String unit) => unit == durationUnit +/// +/// [decimals] caps the fraction digits, for at-a-glance readings; without it +/// the locale default (up to three) applies. A duration ignores it, hours and +/// minutes have no decimals to cap. +String measurementValue(BuildContext context, num value, String unit, {int? decimals}) => + unit == durationUnit ? hoursAndMinutes(value, Localizations.localeOf(context).toString()) - : localizedNumberFormat(context).format(value); + : (decimals == null + ? localizedNumberFormat(context) + : (localizedNumberFormat(context)..maximumFractionDigits = decimals)) + .format(value); /// The unit as it is shown. A duration is stored in minutes but read in hours, /// and the symbol stays untranslated like the units of the other categories. @@ -63,9 +71,9 @@ String measurementUnit(String unit) => unit == durationUnit ? 'h' : unit; String unitSuffixed(String formatted, String unit) => unit.isEmpty ? formatted : '$formatted ${measurementUnit(unit)}'; -/// A measured value with its unit. -String measurementWithUnit(BuildContext context, num value, String unit) => - unitSuffixed(measurementValue(context, value, unit), unit); +/// A measured value with its unit. [decimals] as in [measurementValue]. +String measurementWithUnit(BuildContext context, num value, String unit, {int? decimals}) => + unitSuffixed(measurementValue(context, value, unit, decimals: decimals), unit); /// Ticks a duration axis aims for, few enough that the labels stay apart. const _DURATION_TICKS = 6; diff --git a/lib/features/measurements/charts/calendar.dart b/lib/features/measurements/charts/calendar.dart new file mode 100644 index 000000000..1dd5fc0aa --- /dev/null +++ b/lib/features/measurements/charts/calendar.dart @@ -0,0 +1,39 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +/// Calendar-day arithmetic for the charts, in one place because it is easy to +/// get subtly wrong: a Duration is wall-clock time and a DST day is 23 or 25 +/// hours long, so days are shifted through the date components and counted in +/// UTC, never added as multiples of 24 hours. +library; + +/// [date]'s calendar day, i.e. its midnight. +DateTime dayOf(DateTime date) => DateTime(date.year, date.month, date.day); + +/// The calendar day [days] days after [day] (negative for before), at midnight. +DateTime shiftDays(DateTime day, int days) => DateTime(day.year, day.month, day.day + days); + +/// The Monday of the week [date] falls into, at midnight. +DateTime weekStart(DateTime date) => shiftDays(date, -(date.weekday - 1)); + +/// Whole days from [from] to [to], both taken as calendar days. +int daysBetween(DateTime from, DateTime to) => DateTime.utc( + to.year, + to.month, + to.day, +).difference(DateTime.utc(from.year, from.month, from.day)).inDays; diff --git a/lib/features/measurements/charts/colors.dart b/lib/features/measurements/charts/colors.dart index adb8e3594..aee5a022f 100644 --- a/lib/features/measurements/charts/colors.dart +++ b/lib/features/measurements/charts/colors.dart @@ -23,11 +23,18 @@ import 'package:wger/features/measurements/charts/series.dart'; Color planBandColor(BuildContext context) => Theme.of(context).colorScheme.primary.withValues(alpha: 0.15); +/// The component colours in order: what [componentColor] indexes into, and +/// what the spark painters take as a whole. One list, so a spark segment, its +/// full-chart line and the legend never drift apart. +List componentPalette(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return [scheme.primary, scheme.tertiary, scheme.secondary, scheme.error]; +} + /// Colour of the [index]-th [MeasurementSeriesRole.component] line. Shared /// with the legend so a component's colour matches its line. Color componentColor(BuildContext context, int index) { - final scheme = Theme.of(context).colorScheme; - final colors = [scheme.primary, scheme.tertiary, scheme.secondary, scheme.error]; + final colors = componentPalette(context); return colors[index % colors.length]; } diff --git a/lib/features/measurements/charts/data.dart b/lib/features/measurements/charts/data.dart index e6876519f..a89857a8a 100644 --- a/lib/features/measurements/charts/data.dart +++ b/lib/features/measurements/charts/data.dart @@ -20,6 +20,7 @@ import 'dart:math'; import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; +import 'package:wger/features/measurements/charts/calendar.dart'; import 'package:wger/features/measurements/charts/range.dart'; import 'package:wger/features/measurements/charts/series.dart'; import 'package:wger/features/measurements/measurements.dart'; @@ -106,10 +107,6 @@ List smoothedTrendline( return out; } -/// The Monday of the week [date] falls into, at midnight. -DateTime weekStart(DateTime date) => - DateTime(date.year, date.month, date.day).subtract(Duration(days: date.weekday - 1)); - /// Sums entries per calendar day. Used for metric types where individual /// samples aren't meaningful on their own (steps, distance, energy, sleep) — /// see MeasurementMetricType.isSummedPerDay. @@ -434,6 +431,25 @@ List groupStackedEntries( ]..sort((a, b) => a.date.compareTo(b.date)); } +/// How one reading of [group] is quoted: the roll-up total alone where there +/// is one, otherwise the values joined the way the reading is read (a blood +/// pressure as 120/80, largest first). +/// +/// The one place this rule lives: the overview tile and the entries screen +/// quote through it, so they can never disagree. [values] holds what was +/// measured, keyed by component id; [format] renders one value. +String quoteGroupReading( + MeasurementCategory group, + Map values, + String Function(num) format, +) { + final total = group.children.firstWhereOrNull((c) => c.metricType.isGroupTotal)?.id; + if (total != null && values.containsKey(total)) { + return format(values[total]!); + } + return values.values.sorted((a, b) => b.compareTo(a)).map(format).join('/'); +} + /// The readings of a group, newest first: one per timestamp, with what each /// component holds for it. /// @@ -689,22 +705,12 @@ MeasurementHeatmapGrid buildHeatmapGrid( int maxWeeks = heatmapMaxWeeks, DateTime? today, }) { - // Calendar arithmetic, not Duration: a DST day is 23 or 25 hours long - DateTime dayOf(DateTime date) => DateTime(date.year, date.month, date.day); - DateTime shift(DateTime day, int days) => DateTime(day.year, day.month, day.day + days); - DateTime mondayOf(DateTime date) => shift(date, -(date.weekday - 1)); - int daysBetween(DateTime from, DateTime to) => DateTime.utc( - to.year, - to.month, - to.day, - ).difference(DateTime.utc(from.year, from.month, from.day)).inDays; - final values = {for (final day in days) dayOf(day.date): day.value}; final now = dayOf(today ?? DateTime.now()); if (values.isEmpty) { return MeasurementHeatmapGrid( - start: shift(mondayOf(now), -7 * (maxWeeks - 1)), + start: shiftDays(weekStart(now), -7 * (maxWeeks - 1)), weeks: maxWeeks, values: const {}, maxValue: 0, @@ -713,13 +719,13 @@ MeasurementHeatmapGrid buildHeatmapGrid( final first = values.keys.reduce((a, b) => a.isBefore(b) ? a : b); final last = values.keys.reduce((a, b) => a.isAfter(b) ? a : b); - final oldestVisible = shift(mondayOf(now), -7 * (maxWeeks - 1)); - final end = mondayOf(last).isBefore(oldestVisible) ? last : now; + final oldestVisible = shiftDays(weekStart(now), -7 * (maxWeeks - 1)); + final end = weekStart(last).isBefore(oldestVisible) ? last : now; - final endMonday = mondayOf(end); - final weeks = min(maxWeeks, daysBetween(mondayOf(first), endMonday) ~/ 7 + 1); - final start = shift(endMonday, -7 * (weeks - 1)); - final lastDay = shift(start, 7 * weeks - 1); + final endMonday = weekStart(end); + final weeks = min(maxWeeks, daysBetween(weekStart(first), endMonday) ~/ 7 + 1); + final start = shiftDays(endMonday, -7 * (weeks - 1)); + final lastDay = shiftDays(start, 7 * weeks - 1); // Only the days the grid actually shows. A history longer than the grid is // wide keeps its older days out of the window, and a spike among them would diff --git a/lib/features/measurements/charts/range.dart b/lib/features/measurements/charts/range.dart index 705655066..eb2b488d1 100644 --- a/lib/features/measurements/charts/range.dart +++ b/lib/features/measurements/charts/range.dart @@ -28,7 +28,10 @@ enum ChartRange { all(null), lastYear(365), last3Months(90), - lastMonth(30); + lastMonth(30), + // Six, not seven: the cutoff lands at midnight six days back, so the window + // is today plus the six days before it, i.e. one week of calendar days + lastWeek(6); const ChartRange(this._days); @@ -71,5 +74,6 @@ enum ChartRange { ChartRange.lastYear => i18n.chartRangeYears(1), ChartRange.last3Months => i18n.chartRangeMonths(3), ChartRange.lastMonth => i18n.chartRangeMonths(1), + ChartRange.lastWeek => i18n.chartRangeWeeks(1), }; } diff --git a/lib/features/measurements/charts/spark.dart b/lib/features/measurements/charts/spark.dart new file mode 100644 index 000000000..943d99f76 --- /dev/null +++ b/lib/features/measurements/charts/spark.dart @@ -0,0 +1,326 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +/// What the spark chart of an overview tile draws: the miniature a category's +/// chart type survives as, and the window the range filter gives it. The +/// widgets that paint it live in `../widgets/charts/spark_charts.dart`. +library; + +import 'dart:math'; + +import 'package:collection/collection.dart'; +import 'package:wger/features/measurements/charts/calendar.dart'; +import 'package:wger/features/measurements/charts/series.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; + +/// The shapes a spark chart comes in. Fewer than the full chart types: a +/// distribution does not survive miniaturisation and a group's structural +/// charts (floating, stacked) are bar sparks with more than one segment. +enum SparkKind { line, bars, delta, heatmap } + +/// Fewest and most week columns of a heatmap spark. The filter decides within +/// these: below the floor a heatmap says nothing about regularity, above the +/// cap the columns stop fitting the tile as legible cells. +const sparkHeatmapMinWeeks = 4; +const sparkHeatmapMaxWeeks = 16; + +/// Longest a bar or delta spark gets, in weekly slots. Bounds the unlimited +/// range: a year of weeks is where the slots reach hairline width. +const sparkMaxWeeks = 52; + +/// Widest window drawn as one slot per day. Beyond it the daily bars fall +/// below legibility and the bar family switches to weekly slots. +const sparkWeeklyThresholdDays = 35; + +/// Fewest points in the window before a line spark draws dots instead: a line +/// through a handful of readings claims a continuity they do not have. +const sparkSparseMinDays = 3; + +/// The spark a category of [metricType] is drawn as, honoring [picked] +/// wherever the format survives miniaturisation. +/// +/// A distribution has no time axis to shrink, so it falls back to the type's +/// default spark, the same principle as `resolveChartTypeForData`'s fallback +/// for a pick that does not fit its data. +SparkKind sparkKindFor(MetricType metricType, ChartType picked) => + switch (metricType.resolveChartType(picked)) { + ChartType.heatmap => SparkKind.heatmap, + ChartType.delta => SparkKind.delta, + ChartType.bar => SparkKind.bars, + ChartType.distribution => metricType.isSummedPerDay ? SparkKind.bars : SparkKind.line, + _ => SparkKind.line, + }; + +/// The stretch a spark covers and how it is slotted. +/// +/// [start] doubles as the query bound and identifies a provider, so it is +/// always a midnight (see `ChartRange.countCutoff` for the same rule). It is +/// null only for a full-history line, whose start follows from the data. +class SparkWindow { + const SparkWindow({this.start, this.days, this.weekly = false}); + + final DateTime? start; + final int? days; + + /// Whether the bars hold one week rather than one day. Weekly windows start + /// on a Monday, so the slots are calendar weeks. + final bool weekly; + + /// How many slots a bar spark lays across the width. + int? get slotCount => days == null ? null : (weekly ? days! ~/ 7 : days); +} + +/// The window a spark of [kind] draws under the range filter, whose cutoff is +/// passed in (null for the full history). +/// +/// The line follows the filter as it is. The bar family switches to weekly +/// slots beyond [sparkWeeklyThresholdDays] and is capped at [sparkMaxWeeks]; +/// the heatmap follows it within its own, tighter legibility bounds. The +/// delta window gets one slot beyond its weeks for the running week. +SparkWindow sparkWindowFor(SparkKind kind, {required DateTime? cutoff, DateTime? today}) { + final now = dayOf(today ?? DateTime.now()); + final days = cutoff == null ? null : daysBetween(dayOf(cutoff), now) + 1; + int weeksOf(int? days) => days == null ? sparkMaxWeeks : min(sparkMaxWeeks, (days / 7).ceil()); + + switch (kind) { + case SparkKind.heatmap: + final weeks = weeksOf(days).clamp(sparkHeatmapMinWeeks, sparkHeatmapMaxWeeks); + return SparkWindow( + start: shiftDays(weekStart(now), -7 * (weeks - 1)), + days: 7 * weeks, + weekly: true, + ); + + case SparkKind.delta: + final weeks = weeksOf(days); + return SparkWindow( + start: shiftDays(weekStart(now), -7 * weeks), + days: 7 * (weeks + 1), + weekly: true, + ); + + case SparkKind.bars: + if (days != null && days <= sparkWeeklyThresholdDays) { + return SparkWindow(start: dayOf(cutoff!), days: days); + } + final weeks = weeksOf(days); + return SparkWindow( + start: shiftDays(weekStart(now), -7 * (weeks - 1)), + days: 7 * weeks, + weekly: true, + ); + + case SparkKind.line: + return days == null ? const SparkWindow() : SparkWindow(start: dayOf(cutoff!), days: days); + } +} + +/// Whether the window holds too few points for a line, see [sparkSparseMinDays]. +bool sparkIsSparse(List days) => days.length < sparkSparseMinDays; + +/// One point per calendar week: the mean of the week's daily values, carrying +/// the span of everything measured in it as its range. +/// +/// The mean rather than the sum, so a weekly bar keeps the daily level and the +/// axis does not jump by a factor of seven when the range filter crosses the +/// weekly threshold. The plain bars ignore the range; the floating bars draw +/// it (a week of blood pressure readings from diastolic to systolic). +List sparkWeeklyPoints(List days) => [ + for (final MapEntry(key: week, value: ofWeek) in groupBy( + days, + (MeasurementChartEntry e) => weekStart(e.date), + ).entries) + MeasurementChartEntry( + ofWeek.map((e) => e.value).average, + week, + min: ofWeek.map((e) => e.min ?? e.value).min, + max: ofWeek.map((e) => e.max ?? e.value).max, + ), +]..sort((a, b) => a.date.compareTo(b.date)); + +/// One stacked bar per calendar week: per component the mean over the days it +/// reported, so the stack keeps the height of a typical night. +List sparkWeeklyStacks(List days) { + if (days.isEmpty) { + return const []; + } + + final components = days.first.values.length; + return [ + for (final MapEntry(key: week, value: ofWeek) in groupBy( + days, + (MeasurementStackedEntry e) => weekStart(e.date), + ).entries) + MeasurementStackedEntry(week, [ + for (var component = 0; component < components; component++) + switch (ofWeek.map((e) => e.values[component]).nonNulls.toList()) { + [] => null, + final reported => reported.average, + }, + ]), + ]..sort((a, b) => a.date.compareTo(b.date)); +} + +/// One piece of a spark bar: plain bars have one from zero, floating bars one +/// spanning the reading, stacked bars one per component. The colour index +/// picks the component colour and is 0 for the single-segment shapes. +typedef SparkSegment = ({num from, num to, int colorIndex}); + +/// One bar and the slot it sits in. +typedef SparkBar = ({int slot, List segments}); + +/// What a bar spark draws: [slotCount] slots across the width, of which only +/// the measured ones hold a bar. +class SparkBarsData { + final int slotCount; + final List bars; + + /// Whether the values are changes: their bars hang off a zero hairline and + /// point both ways. + final bool signed; + + const SparkBarsData({required this.slotCount, required this.bars, this.signed = false}); + + bool get isEmpty => bars.isEmpty; + + Iterable get _drawn sync* { + for (final bar in bars) { + for (final segment in bar.segments) { + yield segment.from; + yield segment.to; + } + } + } + + /// Bounds of everything drawn, including the zero line of a signed spark. + /// Zero for an empty spark, which is never painted. + num get minValue => signed ? _drawn.fold(0, (a, b) => a < b ? a : b) : _fold((a, b) => a < b); + + num get maxValue => signed ? _drawn.fold(0, (a, b) => a > b ? a : b) : _fold((a, b) => a > b); + + num _fold(bool Function(num, num) keepFirst) => + _drawn.isEmpty ? 0 : _drawn.reduce((a, b) => keepFirst(a, b) ? a : b); +} + +/// One plain bar per entry, from zero to its value, slotted per day or, with +/// `slotDays: 7` and a Monday [start], per calendar week. +SparkBarsData sparkBars( + List entries, { + required DateTime start, + required int slotCount, + int slotDays = 1, +}) => SparkBarsData( + slotCount: slotCount, + bars: _slotted( + entries, + start, + slotDays, + slotCount, + (e) => e.date, + (e) => [ + (from: 0, to: e.value, colorIndex: 0), + ], + ), +); + +/// One floating bar per entry, spanning the reading's range (a blood pressure +/// day or week from diastolic to systolic). Points without a range carry a +/// single value and are drawn as a short bar around it. +SparkBarsData sparkFloatingBars( + List ranges, { + required DateTime start, + required int slotCount, + int slotDays = 1, +}) => SparkBarsData( + slotCount: slotCount, + bars: _slotted( + ranges, + start, + slotDays, + slotCount, + (e) => e.date, + (e) => [ + (from: e.min ?? e.value, to: e.max ?? e.value, colorIndex: 0), + ], + ), +); + +/// One stacked bar per entry, a segment per component in the order the +/// entries carry them (see `groupStackedEntries`). +SparkBarsData sparkStackedBars( + List days, { + required DateTime start, + required int slotCount, + int slotDays = 1, +}) { + List segmentsOf(MeasurementStackedEntry entry) { + var offset = 0.0; + final segments = []; + for (final (index, value) in entry.values.indexed) { + if (value == null || value <= 0) { + continue; + } + segments.add((from: offset, to: offset + value, colorIndex: index)); + offset += value.toDouble(); + } + return segments; + } + + return SparkBarsData( + slotCount: slotCount, + bars: _slotted(days, start, slotDays, slotCount, (e) => e.date, segmentsOf), + ); +} + +/// One signed bar per week (see `weeklyDeltas`), hanging off the zero line. +SparkBarsData sparkDeltaBars( + List deltas, { + required DateTime start, + required int slotCount, +}) => SparkBarsData( + slotCount: slotCount, + signed: true, + bars: _slotted( + deltas, + start, + 7, + slotCount, + (e) => e.date, + (e) => [ + (from: 0, to: e.value, colorIndex: 0), + ], + ), +); + +/// The entries laid into their slots, [slotDays] calendar days per slot; +/// whatever falls outside the window is dropped. +List _slotted( + List entries, + DateTime start, + int slotDays, + int slotCount, + DateTime Function(T) dateOf, + List Function(T) segments, +) => [ + // Truncating division would fold the days just before the window into slot + // 0, so the days are bounds-checked before they become a slot + for (final entry in entries) + if (daysBetween(start, dateOf(entry)) case final days + when days >= 0 && days ~/ slotDays < slotCount) + (slot: days ~/ slotDays, segments: segments(entry)), +]; diff --git a/lib/features/measurements/models/measurement_category.dart b/lib/features/measurements/models/measurement_category.dart index c09be929b..f21669562 100644 --- a/lib/features/measurements/models/measurement_category.dart +++ b/lib/features/measurements/models/measurement_category.dart @@ -412,6 +412,23 @@ enum MetricType { _ => const MetricLimits(0, measurementSchemaMaxValue), }; + /// Most decimals a value of this type is shown with at a glance: the tile + /// hero, its chips and the group rows. Detail screens, forms and tooltips + /// keep the stored value. + /// + /// Follows the resolution the metric is measured at, like [binWidth]: a + /// pulse has no meaningful tenths, a body weight does, and a short walk + /// needs its hundredths of a kilometre. Durations never ask, they are read + /// as hours and minutes. + int get displayDecimals => switch (this) { + MetricType.bodyWeight || + MetricType.leanBodyMass || + MetricType.bodyFat || + MetricType.custom => 1, + MetricType.distance => 2, + _ => 0, + }; + /// Width of one distribution-histogram bin, in the unit the type is stored /// in. Body weight is the only type that comes in more than one unit, so it /// is the only one [unit] matters for. Null for the types nothing is known diff --git a/lib/features/measurements/screens/measurement_categories_screen.dart b/lib/features/measurements/screens/measurement_categories_screen.dart index 910cb9ffd..e2797c6b3 100644 --- a/lib/features/measurements/screens/measurement_categories_screen.dart +++ b/lib/features/measurements/screens/measurement_categories_screen.dart @@ -20,7 +20,7 @@ import 'package:flutter/material.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/features/measurements/screens/measurement_category_sort_screen.dart'; import 'package:wger/features/measurements/widgets/categories.dart'; -import 'package:wger/features/measurements/widgets/metric_picker.dart'; +import 'package:wger/features/measurements/widgets/measurement_fab.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; class MeasurementCategoriesScreen extends StatelessWidget { @@ -43,10 +43,7 @@ class MeasurementCategoriesScreen extends StatelessWidget { ), ], ), - floatingActionButton: FloatingActionButton( - child: const Icon(Icons.add, color: Colors.white), - onPressed: () => showMetricPicker(context), - ), + floatingActionButton: const MeasurementsFab(), body: const WidescreenWrapper( child: CategoriesList(), ), diff --git a/lib/features/measurements/widgets/categories.dart b/lib/features/measurements/widgets/categories.dart index a3150f078..5dbd511b0 100644 --- a/lib/features/measurements/widgets/categories.dart +++ b/lib/features/measurements/widgets/categories.dart @@ -28,6 +28,7 @@ import 'package:wger/features/measurements/providers/measurement_notifier.dart'; import 'package:wger/features/measurements/screens/weight_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/measurement_tile.dart'; import 'package:wger/features/measurements/widgets/weight_form.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -54,16 +55,12 @@ class _CategoriesListState extends ConsumerState { loggerName: 'CategoriesList', data: (categoriesList) { // Children of multi-value groups are rendered inside their parent's - // card, not as own list items. Body weight leads the list below - // instead of taking its position among the others. + // tile, not as own grid items. Body weight keeps its full card on top + // of the grid instead of becoming a tile among the others. final topLevel = categoriesList .where((c) => c.parentId == null && !c.isOfficialBodyWeight) .toList(); - - final cards = [ - ?_weightCard(), - for (final category in topLevel) CategoriesCard(category, range: _range), - ]; + final weightCard = _weightCard(); return Column( children: [ @@ -73,10 +70,31 @@ class _CategoriesListState extends ConsumerState { onChanged: (range) => setState(() => _range = range), ), Expanded( - child: ListView.builder( - padding: const EdgeInsets.all(10.0), - itemCount: cards.length, - itemBuilder: (context, index) => cards[index], + child: CustomScrollView( + slivers: [ + if (weightCard != null) + SliverPadding( + padding: const EdgeInsets.all(10), + sliver: SliverToBoxAdapter(child: weightCard), + ), + SliverPadding( + padding: const EdgeInsets.symmetric(horizontal: 10), + sliver: SliverGrid( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + mainAxisExtent: measurementTileExtent, + mainAxisSpacing: 10, + crossAxisSpacing: 10, + ), + delegate: SliverChildBuilderDelegate( + (context, index) => MeasurementTile(topLevel[index], range: _range), + childCount: topLevel.length, + ), + ), + ), + // Keeps the last row clear of the FAB + const SliverToBoxAdapter(child: SizedBox(height: 88)), + ], ), ), ], diff --git a/lib/features/measurements/widgets/categories_card.dart b/lib/features/measurements/widgets/categories_card.dart index 8bdba5286..94612cc12 100644 --- a/lib/features/measurements/widgets/categories_card.dart +++ b/lib/features/measurements/widgets/categories_card.dart @@ -244,6 +244,7 @@ class CategoriesCard extends ConsumerWidget { context, value.valueIn(child.unit, categoryUnit: child.unit), child.unit, + decimals: child.metricType.displayDecimals, ) : '—', style: Theme.of(context).textTheme.bodyLarge, diff --git a/lib/features/measurements/widgets/charts.dart b/lib/features/measurements/widgets/charts.dart index ab28aef2f..9737a7c54 100644 --- a/lib/features/measurements/widgets/charts.dart +++ b/lib/features/measurements/widgets/charts.dart @@ -23,3 +23,4 @@ library; export 'charts/chart_widgets.dart'; export 'charts/distribution_chart.dart'; export 'charts/heatmap_chart.dart'; +export 'charts/spark_charts.dart'; diff --git a/lib/features/measurements/widgets/charts/spark_charts.dart b/lib/features/measurements/widgets/charts/spark_charts.dart new file mode 100644 index 000000000..a98779c1d --- /dev/null +++ b/lib/features/measurements/widgets/charts/spark_charts.dart @@ -0,0 +1,312 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +/// The spark charts of the overview tiles: value as the hero, chart as +/// context. Painted by hand like the heatmap, not with fl_chart: a spark has +/// no axes, tooltips, bands or legend, only the shape. What they draw is +/// computed in `../../charts/spark.dart`. +library; + +import 'dart:math'; +import 'dart:ui' show PointMode; + +import 'package:flutter/material.dart'; +import 'package:wger/features/measurements/charts/calendar.dart'; +import 'package:wger/features/measurements/charts/colors.dart'; +import 'package:wger/features/measurements/charts/data.dart'; +import 'package:wger/features/measurements/charts/series.dart'; +import 'package:wger/features/measurements/charts/spark.dart'; + +/// Fraction of the value span kept clear above and below a spark, so the +/// extremes are not glued to the edges. +const _valuePadding = 0.12; + +/// Radius of a spark dot. +const _dotRadius = 2.5; + +/// A value series as a miniature line, or as bare dots for a sparse category, +/// where a line would claim a continuity a handful of readings does not have. +class SparkLineChart extends StatelessWidget { + const SparkLineChart( + this.entries, { + required this.start, + required this.days, + this.dots = false, + super.key, + }); + + final List entries; + + /// First day of the window; with [days] it fixes the x axis, so the spark + /// keeps its time scale even when only part of the window was measured. + final DateTime start; + final int days; + + final bool dots; + + @override + Widget build(BuildContext context) { + return CustomPaint( + size: Size.infinite, + painter: _SparkLinePainter( + entries: entries, + start: start, + days: days, + dots: dots, + color: Theme.of(context).colorScheme.primary, + ), + ); + } +} + +class _SparkLinePainter extends CustomPainter { + _SparkLinePainter({ + required this.entries, + required this.start, + required this.days, + required this.dots, + required this.color, + }); + + final List entries; + final DateTime start; + final int days; + final bool dots; + final Color color; + + @override + void paint(Canvas canvas, Size size) { + if (entries.isEmpty) { + return; + } + + final values = entries.map((e) => e.value); + final low = values.reduce(min); + final high = values.reduce(max); + final span = high - low; + + double x(DateTime date) => + days <= 1 ? size.width / 2 : daysBetween(start, date) / (days - 1) * size.width; + // A flat series sits mid-height rather than dividing by a zero span + double y(num value) => span == 0 + ? size.height / 2 + : size.height * (_valuePadding + (1 - 2 * _valuePadding) * (high - value) / span); + + final points = [for (final e in entries) Offset(x(e.date), y(e.value))]; + final fill = Paint()..color = color; + + if (dots || points.length == 1) { + for (final point in points) { + canvas.drawCircle(point, _dotRadius, fill); + } + return; + } + + canvas.drawPoints( + PointMode.polygon, + points, + Paint() + ..color = color + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..style = PaintingStyle.stroke, + ); + // The end dot marks where the series stands today, like the hero value + canvas.drawCircle(points.last, _dotRadius, fill); + } + + @override + bool shouldRepaint(_SparkLinePainter oldDelegate) => + oldDelegate.entries != entries || + oldDelegate.start != start || + oldDelegate.dots != dots || + oldDelegate.color != color; +} + +/// The bar family as a miniature: plain daily bars, floating bars (blood +/// pressure), stacked bars (sleep stages) and, with `signed`, the weekly +/// change bars around a zero hairline. Which one it is follows from the data, +/// see the `spark*Bars` builders. +class SparkBarChart extends StatelessWidget { + const SparkBarChart(this.data, {super.key}); + + final SparkBarsData data; + + @override + Widget build(BuildContext context) { + return CustomPaint( + size: Size.infinite, + painter: _SparkBarPainter( + data: data, + // componentColor's palette, so a stacked spark's segments match the + // full chart of the tile it leads to + palette: componentPalette(context), + zeroLine: Theme.of(context).colorScheme.outline, + ), + ); + } +} + +class _SparkBarPainter extends CustomPainter { + _SparkBarPainter({required this.data, required this.palette, required this.zeroLine}); + + final SparkBarsData data; + final List palette; + final Color zeroLine; + + @override + void paint(Canvas canvas, Size size) { + if (data.isEmpty) { + return; + } + + final low = data.minValue; + final high = data.maxValue; + final span = high - low; + + double y(num value) => span == 0 + ? size.height / 2 + : size.height * (_valuePadding + (1 - 2 * _valuePadding) * (high - value) / span); + + final slotWidth = size.width / data.slotCount; + final barWidth = (slotWidth * 0.6).clamp(2.0, 12.0); + + if (data.signed) { + canvas.drawLine( + Offset(0, y(0)), + Offset(size.width, y(0)), + Paint() + ..color = zeroLine + ..strokeWidth = 1, + ); + } + + final paint = Paint()..style = PaintingStyle.fill; + for (final bar in data.bars) { + final left = bar.slot * slotWidth + (slotWidth - barWidth) / 2; + for (final segment in bar.segments) { + final top = y(max(segment.from, segment.to)); + // Never thinner than a hairline, or a small value disappears + final bottom = max(y(min(segment.from, segment.to)), top + 1); + paint.color = palette[segment.colorIndex % palette.length]; + canvas.drawRRect( + RRect.fromLTRBR(left, top, left + barWidth, bottom, _radiusOf(bar, segment, barWidth)), + paint, + ); + } + } + } + + /// A lone segment is a small pill; the segments of a stack stay square so + /// they meet without seams. + Radius _radiusOf(SparkBar bar, SparkSegment segment, double barWidth) => + bar.segments.length == 1 ? Radius.circular(barWidth / 3) : Radius.zero; + + @override + bool shouldRepaint(_SparkBarPainter oldDelegate) => + oldDelegate.data != data || oldDelegate.palette != palette; +} + +/// A calendar strip laid out like the full heatmap (weeks as columns, +/// weekdays as rows), without the labels or the tap readout: the width +/// carries the time axis, the filter says which stretch it is. +class SparkHeatmap extends StatelessWidget { + const SparkHeatmap(this.days, {required this.weeks, this.today, super.key}); + + /// One entry per calendar day, see `aggregatePerDay` / `averagePerDay`. + final List days; + + /// Week columns to lay out, see `sparkWindowFor`. + final int weeks; + + /// Injectable for tests; the widgets leave it at the current day. + final DateTime? today; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + + return CustomPaint( + size: Size.infinite, + painter: _SparkHeatmapPainter( + grid: buildHeatmapGrid(days, maxWeeks: weeks, today: today), + today: today ?? DateTime.now(), + filled: scheme.primary, + empty: scheme.surfaceContainerHighest, + ), + ); + } +} + +class _SparkHeatmapPainter extends CustomPainter { + _SparkHeatmapPainter({ + required this.grid, + required this.today, + required this.filled, + required this.empty, + }); + + final MeasurementHeatmapGrid grid; + final DateTime today; + final Color filled; + final Color empty; + + @override + void paint(Canvas canvas, Size size) { + // Square cells centered in the box, week columns and weekday rows + final step = min(size.width / grid.weeks, size.height / DateTime.daysPerWeek); + final cell = step - (step * 0.18).clamp(1.0, 3.0); + final left = (size.width - step * grid.weeks) / 2; + final top = (size.height - step * DateTime.daysPerWeek) / 2; + final endOfToday = DateTime(today.year, today.month, today.day); + + final paint = Paint()..style = PaintingStyle.fill; + for (var week = 0; week < grid.weeks; week++) { + for (var weekday = 0; weekday < DateTime.daysPerWeek; weekday++) { + // Days of the current week that have not happened yet stay blank + if (grid.dayAt(week, weekday).isAfter(endOfToday)) { + continue; + } + + paint.color = _cellColor(grid.valueAt(week, weekday)); + canvas.drawRRect( + RRect.fromRectAndRadius( + Offset(left + week * step, top + weekday * step) & Size(cell, cell), + Radius.circular(min(2, cell / 4)), + ), + paint, + ); + } + } + } + + /// The full heatmap's colour rule: neutral for a day without a measurement, + /// tinted by size for the rest, starting well above transparent. + Color _cellColor(num? value) { + if (value == null) { + return empty; + } + final share = grid.maxValue <= 0 ? 1.0 : (value / grid.maxValue).clamp(0.0, 1.0); + return Color.lerp(filled.withValues(alpha: 0.3), filled, share)!; + } + + @override + bool shouldRepaint(_SparkHeatmapPainter oldDelegate) => + oldDelegate.grid != grid || oldDelegate.filled != filled; +} diff --git a/lib/features/measurements/widgets/entries.dart b/lib/features/measurements/widgets/entries.dart index 977443e27..264315df4 100644 --- a/lib/features/measurements/widgets/entries.dart +++ b/lib/features/measurements/widgets/entries.dart @@ -367,9 +367,7 @@ class _GroupReadingsListState extends ConsumerState<_GroupReadingsList> with _Gr // 120/80) String formatted(num value) => measurementValue(context, value, category.unit); final headline = unitSuffixed( - total != null && values.containsKey(total) - ? formatted(values[total]!) - : values.values.sorted((a, b) => b.compareTo(a)).map(formatted).join('/'), + quoteGroupReading(category, values, formatted), category.unit, ); final parts = [ diff --git a/lib/features/measurements/widgets/measurement_fab.dart b/lib/features/measurements/widgets/measurement_fab.dart new file mode 100644 index 000000000..9cd9cac81 --- /dev/null +++ b/lib/features/measurements/widgets/measurement_fab.dart @@ -0,0 +1,99 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/core/form_screen.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_notifier.dart'; +import 'package:wger/features/measurements/widgets/forms.dart'; +import 'package:wger/features/measurements/widgets/metric_picker.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// The overview's add button: opens a menu with one action per hand-kept +/// category (straight into its entry form) plus the metric picker for +/// starting something new. +/// +/// A [MenuAnchor] rather than a hand-rolled expanding FAB: dismissal, +/// positioning and focus come with it. Flutter's M3 menu is also as close as +/// the stable SDK gets to the M3 FAB menu for now. +class MeasurementsFab extends ConsumerWidget { + const MeasurementsFab({super.key}); + + Future _addEntry(BuildContext context, MeasurementCategory category) async { + await Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).newEntry, + category.hasChildren + ? GroupMeasurementEntryForm(category) + : MeasurementEntryForm(category.id!), + ), + ); + } + + /// Whether [category] is fed by hand rather than by the health sync, judged + /// by who wrote its newest reading. A category without entries counts as + /// hand-kept: it was just created and logging is what it is waiting for. + bool _isHandKept(MeasurementCategory category, Map latest) { + final newest = category.hasChildren + ? category.children.map((c) => latest[c.id]) + : [latest[category.id]]; + + return newest.nonNulls.every((entry) => entry.source == 'user'); + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final categories = ref.watch(measurementCategoriesProvider).value ?? const []; + final latest = ref.watch(latestMeasurementEntriesProvider).value ?? const {}; + final handKept = [ + for (final category in categories) + if (category.parentId == null && + !category.isOfficialBodyWeight && + _isHandKept(category, latest)) + category, + ]; + + return MenuAnchor( + menuChildren: [ + for (final category in handKept) + MenuItemButton( + leadingIcon: const Icon(Icons.add), + onPressed: () => _addEntry(context, category), + child: Text(category.displayName(context)), + ), + MenuItemButton( + leadingIcon: const Icon(Icons.playlist_add), + onPressed: () => showMetricPicker(context), + child: Text(AppLocalizations.of(context).trackNewMetric), + ), + ], + builder: (context, controller, child) => FloatingActionButton( + onPressed: () => controller.isOpen ? controller.close() : controller.open(), + child: AnimatedRotation( + turns: controller.isOpen ? 0.125 : 0, + duration: const Duration(milliseconds: 200), + child: const Icon(Icons.add, color: Colors.white), + ), + ), + ); + } +} diff --git a/lib/features/measurements/widgets/measurement_tile.dart b/lib/features/measurements/widgets/measurement_tile.dart new file mode 100644 index 000000000..754f371c4 --- /dev/null +++ b/lib/features/measurements/widgets/measurement_tile.dart @@ -0,0 +1,545 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +import 'dart:math'; + +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:intl/intl.dart'; +import 'package:wger/core/formatting/formatting.dart'; +import 'package:wger/features/measurements/charts/calendar.dart'; +import 'package:wger/features/measurements/charts/data.dart'; +import 'package:wger/features/measurements/charts/range.dart'; +import 'package:wger/features/measurements/charts/series.dart'; +import 'package:wger/features/measurements/charts/spark.dart'; +import 'package:wger/features/measurements/models/measurement_bucket.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; +import 'package:wger/features/measurements/models/measurement_entry.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/charts.dart'; +import 'package:wger/features/measurements/widgets/helpers.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Height of a tile in the overview grid, shared with the grid delegate. +const measurementTileExtent = 172.0; + +/// Height of the spark chart inside a tile. +const _sparkHeight = 40.0; + +/// Height of a heatmap spark: it has no axis row, its grid takes that room +/// instead, which is what makes the cells legible. +const _heatmapHeight = 58.0; + +/// One category of the overview grid: latest value as the hero, a spark chart +/// as context over the range the filter selects. A tap opens the category's +/// entries screen; everything beyond a glance lives there. +class MeasurementTile extends ConsumerWidget { + const MeasurementTile(this.category, {this.range = ChartRange.last3Months, super.key}); + + final MeasurementCategory category; + final ChartRange range; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final latest = ref.watch(latestMeasurementEntriesProvider).value ?? const {}; + + return Card( + margin: EdgeInsets.zero, + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () => Navigator.pushNamed( + context, + MeasurementEntriesScreen.routeName, + arguments: category.id, + ), + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + category.displayName(context), + style: Theme.of(context).textTheme.titleSmall, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + _heroValue(context, latest), + const Spacer(), + if (category.hasChildren) _groupSpark(latest) else _leafSpark(latest), + ], + ), + ), + ), + ); + } + + /// The latest reading, large: the one thing the tile exists to show. A + /// group is quoted through the shared rule, see [quoteGroupReading], so the + /// tile and the entries screen behind it read the same. + Widget _heroValue(BuildContext context, Map latest) { + String format(num value) => measurementValue( + context, + value, + category.unit, + decimals: category.metricType.displayDecimals, + ); + + final String value; + if (category.hasChildren) { + final values = { + for (final child in category.children) + if (latest[child.id] case final MeasurementEntry entry) + child.id!: entry.valueIn(child.unit, categoryUnit: child.unit), + }; + value = values.isEmpty ? '—' : quoteGroupReading(category, values, format); + } else { + final latestValue = latest[category.id]?.valueIn(category.unit, categoryUnit: category.unit); + value = latestValue == null ? '—' : format(latestValue); + } + + final theme = Theme.of(context); + return Text.rich( + TextSpan( + text: value, + style: theme.textTheme.headlineSmall, + children: [ + if (category.unit.isNotEmpty) + TextSpan( + text: ' ${measurementUnit(category.unit)}', + style: theme.textTheme.bodySmall, + ), + ], + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ); + } + + static const _emptySpark = [_SparkArea(child: SizedBox())]; + + /// The spark of a leaf category, honoring its chart type wherever the format + /// survives miniaturisation, see [sparkKindFor]. Keeps what it last drew + /// while another range loads, like the full-size charts. + Widget _leafSpark(Map latest) { + final kind = sparkKindFor(category.metricType, category.chartType); + final window = sparkWindowFor(kind, cutoff: range.countCutoff); + final level = kind == SparkKind.delta + ? MeasurementBucketLevel.week + : MeasurementBucketLevel.day; + + return MeasurementChartArea>( + identity: category.id!, + loading: const _SparkArea(child: SizedBox()), + watch: (ref) => ref + .watch(measurementChartBucketsProvider(category.id!, window.start, null, level)) + .whenData( + (buckets) => chartEntriesForBuckets( + buckets, + targetUnit: category.unit, + categoryUnit: category.unit, + summed: category.metricType.isSummedPerDay, + ), + ), + builder: (context, points) => _leafRows(context, kind, window, points, latest), + onError: (_, _) => _emptySpark, + ); + } + + List _leafRows( + BuildContext context, + SparkKind kind, + SparkWindow window, + List points, + Map latest, + ) { + switch (kind) { + case SparkKind.heatmap: + return [ + SizedBox( + height: _heatmapHeight, + width: double.infinity, + child: SparkHeatmap(points, weeks: window.slotCount!), + ), + // The same footer its kind would get elsewhere: a level for the + // summed types, a direction for the sample ones + if (category.metricType.isSummedPerDay) + _AverageChip( + points: points, + unit: category.unit, + decimals: category.metricType.displayDecimals, + ) + else + _TrendChip( + points: points, + unit: category.unit, + decimals: category.metricType.displayDecimals, + ), + ]; + + case SparkKind.delta: + return [ + _SparkArea( + child: SparkBarChart( + sparkDeltaBars( + weeklyDeltas(points, summed: category.metricType.isSummedPerDay), + start: window.start!, + slotCount: window.slotCount!, + ), + ), + ), + _MonthAxis(window.start!), + ]; + + case SparkKind.bars: + final data = window.weekly + ? sparkBars( + sparkWeeklyPoints(points), + start: window.start!, + slotCount: window.slotCount!, + slotDays: 7, + ) + : sparkBars(points, start: window.start!, slotCount: window.slotCount!); + return [ + _SparkArea(child: SparkBarChart(data)), + _axis(window.start!, window.days!, weekly: window.weekly), + _AverageChip( + points: points, + unit: category.unit, + decimals: category.metricType.displayDecimals, + ), + ]; + + case SparkKind.line: + // A full-history window has no fixed start; the data provides it + final start = window.start ?? dayOf(points.map((e) => e.date).minOrNull ?? DateTime.now()); + final days = window.days ?? daysBetween(start, DateTime.now()) + 1; + final sparse = sparkIsSparse(points); + return [ + _SparkArea( + child: SparkLineChart(points, start: start, days: days, dots: sparse), + ), + _axis(start, days, weekly: false), + // A handful of readings has no trend to quote, but a date is honest + if (sparse) + _LastMeasured(latest[category.id]) + else + _TrendChip( + points: points, + unit: category.unit, + decimals: category.metricType.displayDecimals, + ), + ]; + } + } + + /// The spark of a group, which keeps its structural form: sleep stacks, + /// blood pressure floats, anything else falls back to a line of its first + /// component with data. + Widget _groupSpark(Map latest) { + final window = sparkWindowFor(SparkKind.bars, cutoff: range.countCutoff); + + return MeasurementChartArea>>( + identity: category.id!, + loading: const _SparkArea(child: SizedBox()), + watch: (ref) => ref + .watch( + measurementGroupBucketsProvider(category.id!, window.start, MeasurementBucketLevel.day), + ) + .whenData((buckets) => groupComponentPoints(category, buckets)), + builder: (context, points) => _groupRows(context, window, points, latest), + onError: (_, _) => _emptySpark, + ); + } + + List _groupRows( + BuildContext context, + SparkWindow window, + Map> points, + Map latest, + ) { + final start = window.start!; + final slotCount = window.slotCount!; + + if (category.metricType.isSummedPerDay) { + final components = stackableComponents(category); + final stacked = groupStackedEntries(components, points); + final data = window.weekly + ? sparkStackedBars( + sparkWeeklyStacks(stacked), + start: start, + slotCount: slotCount, + slotDays: 7, + ) + : sparkStackedBars(stacked, start: start, slotCount: slotCount); + return [ + _SparkArea(child: SparkBarChart(data)), + _axis(start, window.days!, weekly: window.weekly), + _AverageChip( + points: [for (final day in stacked) MeasurementChartEntry(day.total, day.date)], + unit: category.unit, + decimals: category.metricType.displayDecimals, + ), + ]; + } + + final ranges = category.children.length == 2 + ? groupRangeEntries(points) + : const []; + if (ranges.isNotEmpty) { + final data = window.weekly + ? sparkFloatingBars( + sparkWeeklyPoints(ranges), + start: start, + slotCount: slotCount, + slotDays: 7, + ) + : sparkFloatingBars(ranges, start: start, slotCount: slotCount); + return [ + _SparkArea(child: SparkBarChart(data)), + _axis(start, window.days!, weekly: window.weekly), + _LastMeasured(_newestOf(category.children, latest)), + ]; + } + + final fallback = category.children + .map((c) => points[c.id]) + .firstWhereOrNull( + (p) => p != null && p.isNotEmpty, + ); + return [ + _SparkArea( + child: SparkLineChart(fallback ?? const [], start: start, days: window.days!), + ), + _axis(start, window.days!, weekly: window.weekly), + _LastMeasured(_newestOf(category.children, latest)), + ]; + } + + MeasurementEntry? _newestOf( + List children, + Map latest, + ) => children + .map((c) => latest[c.id]) + .nonNulls + .fold(null, (a, b) => a == null || b.date.isAfter(a.date) ? b : a); +} + +/// The axis row under a spark: one weekday letter per day where the window is +/// exactly one week of daily slots, the months it spans otherwise. +Widget _axis(DateTime start, int days, {required bool weekly}) => + !weekly && days == DateTime.daysPerWeek ? _WeekdayAxis(start) : _MonthAxis(start); + +/// One narrow letter per day of a one-week window, today highlighted. +class _WeekdayAxis extends StatelessWidget { + const _WeekdayAxis(this.start); + + final DateTime start; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final format = DateFormat('EEEEE', Localizations.localeOf(context).toString()); + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + + return Row( + children: [ + for (var day = 0; day < DateTime.daysPerWeek; day++) + Expanded( + child: Text( + format.format(DateTime(start.year, start.month, start.day + day)), + textAlign: TextAlign.center, + style: DateTime(start.year, start.month, start.day + day) == today + ? theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ) + : theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ); + } +} + +/// The fixed-height box every spark variant draws into, so the rows above and +/// below it line up across the grid. +class _SparkArea extends StatelessWidget { + const _SparkArea({required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return SizedBox(height: _sparkHeight, width: double.infinity, child: child); + } +} + +/// What stretch of the calendar the spark covers: its months or, over more +/// than a year, its years. Kept to a few labels, the tile is narrow. +class _MonthAxis extends StatelessWidget { + const _MonthAxis(this.start); + + final DateTime start; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final locale = Localizations.localeOf(context).languageCode; + final today = DateTime.now(); + + final monthFormat = DateFormat.MMM(locale); + final months = []; + var cursor = DateTime(start.year, start.month); + while (!cursor.isAfter(today)) { + months.add(monthFormat.format(cursor)); + cursor = DateTime(cursor.year, cursor.month + 1); + } + + final yearFormat = DateFormat.y(locale); + final labels = switch (months.length) { + > 12 => [ + for (var year = start.year; year <= today.year; year++) yearFormat.format(DateTime(year)), + ], + > 4 => [months.first, months[months.length ~/ 2], months.last], + _ => months, + }; + + return Text( + labels.join(' · '), + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.labelSmall?.copyWith(color: theme.colorScheme.onSurfaceVariant), + ); + } +} + +/// A neutral fact in chip form, see [_TrendChip] and [_AverageChip]. States +/// what the numbers do, never whether that is good: which direction is the +/// good one depends on the goal, and the tile should not assert one. +class _FooterChip extends StatelessWidget { + const _FooterChip(this.text); + + final String text; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(8), + ), + child: Text(text, style: theme.textTheme.labelSmall, maxLines: 1), + ); + } +} + +/// Which way the window's values go, as a weekly rate ("↘ 0.3 kg/week"), or +/// "stable" when the change is within noise of the value itself, or below +/// what [decimals] can even show: a chip claiming "0.0 kg/week" says stable, +/// only worse. +class _TrendChip extends StatelessWidget { + const _TrendChip({required this.points, required this.unit, required this.decimals}); + + final List points; + final String unit; + final int decimals; + + @override + Widget build(BuildContext context) { + if (points.length < 2) { + return const SizedBox.shrink(); + } + + final i18n = AppLocalizations.of(context); + final sorted = [...points]..sort((a, b) => a.date.compareTo(b.date)); + final first = sorted.first; + final last = sorted.last; + final days = daysBetween(first.date, last.date); + if (days == 0) { + return const SizedBox.shrink(); + } + + final perWeek = (last.value - first.value) / days * 7; + final scale = last.value.abs(); + final roundsToZero = perWeek.abs() < 0.5 / pow(10, decimals); + if (scale == 0 || roundsToZero || perWeek.abs() / scale < 0.01) { + return _FooterChip('→ ${i18n.sparkTrendStable}'); + } + + final arrow = perWeek < 0 ? '↘' : '↗'; + return _FooterChip( + '$arrow ' + '${i18n.sparkTrendPerWeek(measurementWithUnit(context, perWeek.abs(), unit, decimals: decimals))}', + ); + } +} + +/// The average over the window's measured days, for the summed types, whose +/// per-day totals have a typical level rather than a trend. +class _AverageChip extends StatelessWidget { + const _AverageChip({required this.points, required this.unit, required this.decimals}); + + final List points; + final String unit; + final int decimals; + + @override + Widget build(BuildContext context) { + if (points.isEmpty) { + return const SizedBox.shrink(); + } + + final mean = points.map((e) => e.value).average; + return _FooterChip( + AppLocalizations.of( + context, + ).sparkAverage(measurementWithUnit(context, mean, unit, decimals: decimals)), + ); + } +} + +/// When the category was last measured, the honest footer of a tile whose +/// chart says little about that (sparse dots, unpaired readings). +class _LastMeasured extends StatelessWidget { + const _LastMeasured(this.entry); + + final MeasurementEntry? entry; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + if (entry == null) { + return const SizedBox.shrink(); + } + + return Text( + localizedDate(context).format(entry!.date), + style: theme.textTheme.labelSmall?.copyWith(color: theme.colorScheme.onSurfaceVariant), + ); + } +} diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index a07305849..1e1c21dfc 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1185,5 +1185,10 @@ "healthConnectInstall": "Health Connect installieren", "healthConnectUpdate": "Health Connect aktualisieren", "healthConnectRequired": "Health Connect wird benötigt, um Körpermesswerte zu importieren", - "labelBottomNavBody": "Körper" + "labelBottomNavBody": "Körper", + "sparkAverage": "Ø {value}", + "sparkTrendPerWeek": "{value}/Woche", + "sparkTrendStable": "stabil", + "trackNewMetric": "Etwas Neues aufzeichnen", + "chartRangeWeeks": "{count, plural, one{1 Woche} other{{count} Wochen}}" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index cbb904ced..cacb529c6 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -537,6 +537,15 @@ "@chartRangeAll": { "description": "Label for the chart time-range selector option showing all data" }, + "chartRangeWeeks": "{count, plural, one{1 week} other{{count} weeks}}", + "@chartRangeWeeks": { + "description": "Chart time-range selector option covering a number of weeks", + "placeholders": { + "count": { + "type": "int" + } + } + }, "chartRangeMonths": "{count, plural, one{1 month} other{{count} months}}", "@chartRangeMonths": { "description": "Chart time-range selector option covering a number of months", @@ -658,6 +667,32 @@ } } }, + "sparkAverage": "avg {value}", + "@sparkAverage": { + "description": "Chip on an overview tile: the average over the charted days, e.g. 'avg 7:05' for sleep", + "placeholders": { + "value": { + "type": "String" + } + } + }, + "sparkTrendPerWeek": "{value}/week", + "@sparkTrendPerWeek": { + "description": "Chip on an overview tile: how much the value changes per week, shown after a direction arrow", + "placeholders": { + "value": { + "type": "String" + } + } + }, + "sparkTrendStable": "stable", + "@sparkTrendStable": { + "description": "Chip on an overview tile when the value barely changes, shown after a right arrow" + }, + "trackNewMetric": "Track something new", + "@trackNewMetric": { + "description": "Action in the overview's expanding + button that opens the sheet for starting a new measurement category" + }, "measurement": "Measurement", "@measurement": {}, "measurements": "Measurements", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 56b6d979c..47b01a306 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1224,5 +1224,10 @@ "healthConnectInstall": "Instalar Health Connect", "healthConnectUpdate": "Actualizar Health Connect", "healthConnectRequired": "Health Connect es necesario para importar medidas corporales", - "labelBottomNavBody": "Cuerpo" + "labelBottomNavBody": "Cuerpo", + "sparkAverage": "prom. {value}", + "sparkTrendPerWeek": "{value}/semana", + "sparkTrendStable": "estable", + "trackNewMetric": "Registrar algo nuevo", + "chartRangeWeeks": "{count, plural, one{1 semana} other{{count} semanas}}" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 1d50ce2d7..be9529194 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1195,5 +1195,10 @@ "healthConnectInstall": "Installer Health Connect", "healthConnectUpdate": "Mettre à jour Health Connect", "healthConnectRequired": "Health Connect est nécessaire pour importer les mensurations", - "labelBottomNavBody": "Corps" + "labelBottomNavBody": "Corps", + "sparkAverage": "moy. {value}", + "sparkTrendPerWeek": "{value}/semaine", + "sparkTrendStable": "stable", + "trackNewMetric": "Suivre autre chose", + "chartRangeWeeks": "{count, plural, one{1 semaine} other{{count} semaines}}" } diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 76cb9e16f..08f0ddbc3 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -2247,6 +2247,28 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get sparkTrendStable => + (super.noSuchMethod( + Invocation.getter(#sparkTrendStable), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#sparkTrendStable), + ), + ) + as String); + + @override + String get trackNewMetric => + (super.noSuchMethod( + Invocation.getter(#trackNewMetric), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#trackNewMetric), + ), + ) + as String); + @override String get measurement => (super.noSuchMethod( @@ -5380,6 +5402,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String chartRangeWeeks(int? count) => + (super.noSuchMethod( + Invocation.method(#chartRangeWeeks, [count]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#chartRangeWeeks, [count]), + ), + ) + as String); + @override String chartRangeMonths(int? count) => (super.noSuchMethod( @@ -5457,6 +5490,28 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String sparkAverage(String? value) => + (super.noSuchMethod( + Invocation.method(#sparkAverage, [value]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#sparkAverage, [value]), + ), + ) + as String); + + @override + String sparkTrendPerWeek(String? value) => + (super.noSuchMethod( + Invocation.method(#sparkTrendPerWeek, [value]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#sparkTrendPerWeek, [value]), + ), + ) + as String); + @override String minLengthRoutine(int? number) => (super.noSuchMethod( diff --git a/test/features/measurements/charts/range_test.dart b/test/features/measurements/charts/range_test.dart index b15636bda..3202d4443 100644 --- a/test/features/measurements/charts/range_test.dart +++ b/test/features/measurements/charts/range_test.dart @@ -21,12 +21,22 @@ import 'package:wger/features/measurements/charts/range.dart'; void main() { group('ChartRange', () { - test('the month is the shortest range, the full history the longest', () { + test('the week is the shortest range, the full history the longest', () { final now = DateTime.now(); expect(ChartRange.all.cutoff, isNull); expect(ChartRange.lastMonth.cutoff!.isAfter(ChartRange.last3Months.cutoff!), isTrue); - expect(ChartRange.lastMonth.cutoff!.isBefore(now), isTrue); + expect(ChartRange.lastWeek.cutoff!.isAfter(ChartRange.lastMonth.cutoff!), isTrue); + expect(ChartRange.lastWeek.cutoff!.isBefore(now), isTrue); + }); + + test('the week covers today plus the six days before it', () { + // Seven calendar days in all: the count cutoff sits at midnight six + // days back, so a weekday axis gets one letter per day + final count = ChartRange.lastWeek.countCutoff!; + final now = DateTime.now(); + + expect(DateTime(now.year, now.month, now.day - 6), count); }); test('the read cutoff leaves room for the widest average window', () { diff --git a/test/features/measurements/charts/spark_test.dart b/test/features/measurements/charts/spark_test.dart new file mode 100644 index 000000000..220a9d3bf --- /dev/null +++ b/test/features/measurements/charts/spark_test.dart @@ -0,0 +1,293 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/measurements/charts/series.dart'; +import 'package:wger/features/measurements/charts/spark.dart'; +import 'package:wger/features/measurements/models/measurement_category.dart'; + +void main() { + group('sparkKindFor', () { + test('honors the picked chart type where it survives miniaturisation', () { + expect(sparkKindFor(MetricType.restingHeartRate, ChartType.line), SparkKind.line); + expect(sparkKindFor(MetricType.steps, ChartType.bar), SparkKind.bars); + expect(sparkKindFor(MetricType.steps, ChartType.heatmap), SparkKind.heatmap); + expect(sparkKindFor(MetricType.restingHeartRate, ChartType.delta), SparkKind.delta); + }); + + test('auto derives the default spark from the metric type', () { + expect(sparkKindFor(MetricType.restingHeartRate, ChartType.auto), SparkKind.line); + expect(sparkKindFor(MetricType.steps, ChartType.auto), SparkKind.bars); + expect(sparkKindFor(MetricType.custom, ChartType.auto), SparkKind.line); + }); + + test('a distribution falls back to the default spark of the type', () { + expect(sparkKindFor(MetricType.restingHeartRate, ChartType.distribution), SparkKind.line); + expect(sparkKindFor(MetricType.steps, ChartType.distribution), SparkKind.bars); + }); + + test('a pick that does not fit the type falls back like the full chart', () { + // A summed type has no line chart to shrink, see resolveChartType + expect(sparkKindFor(MetricType.steps, ChartType.line), SparkKind.bars); + }); + }); + + group('sparkWindowFor', () { + // A Friday; its Monday is 2026-08-03 + final today = DateTime(2026, 8, 7); + + test('a line follows the filter cutoff as it is', () { + final window = sparkWindowFor( + SparkKind.line, + cutoff: DateTime(2026, 7, 8), + today: today, + ); + + expect(window.start, DateTime(2026, 7, 8)); + expect(window.days, 31); + expect(window.weekly, isFalse); + }); + + test('a full-history line has no fixed start, the data provides it', () { + final window = sparkWindowFor(SparkKind.line, cutoff: null, today: today); + + expect(window.start, isNull); + expect(window.days, isNull); + }); + + test('bars stay daily up to the weekly threshold', () { + final window = sparkWindowFor( + SparkKind.bars, + cutoff: DateTime(2026, 7, 8), + today: today, + ); + + expect(window.weekly, isFalse); + expect(window.slotCount, 31); + }); + + test('bars switch to Monday-aligned calendar weeks beyond it', () { + final window = sparkWindowFor( + SparkKind.bars, + cutoff: DateTime(2026, 5, 9), + today: today, + ); + + expect(window.weekly, isTrue); + expect(window.start!.weekday, DateTime.monday); + expect(window.slotCount, 13); + // 13 week columns, the newest being the running one + expect(window.start, DateTime(2026, 5, 11)); + }); + + test('the unlimited range is capped at a year of weekly slots', () { + final window = sparkWindowFor(SparkKind.bars, cutoff: null, today: today); + + expect(window.weekly, isTrue); + expect(window.slotCount, sparkMaxWeeks); + }); + + test('the delta window gets one slot beyond its weeks for the running week', () { + final window = sparkWindowFor( + SparkKind.delta, + cutoff: DateTime(2026, 5, 9), + today: today, + ); + + expect(window.start, DateTime(2026, 5, 4)); + expect(window.slotCount, 14); + }); + + test('the heatmap follows the filter within its legibility bounds', () { + // A month is five week columns, ending in the running week + final month = sparkWindowFor( + SparkKind.heatmap, + cutoff: DateTime(2026, 7, 8), + today: today, + ); + expect(month.slotCount, 5); + expect(month.start, DateTime(2026, 7, 6)); + + // A week is below what a heatmap says anything about + final week = sparkWindowFor( + SparkKind.heatmap, + cutoff: DateTime(2026, 8, 1), + today: today, + ); + expect(week.slotCount, sparkHeatmapMinWeeks); + + // The unlimited range is capped where the columns stop fitting + final all = sparkWindowFor(SparkKind.heatmap, cutoff: null, today: today); + expect(all.slotCount, sparkHeatmapMaxWeeks); + }); + }); + + group('sparkWeeklyPoints', () { + test('one point per calendar week, keeping the daily level', () { + final means = sparkWeeklyPoints([ + MeasurementChartEntry(8000, DateTime(2026, 8, 3)), + MeasurementChartEntry(6000, DateTime(2026, 8, 5)), + MeasurementChartEntry(10000, DateTime(2026, 7, 29)), + ]); + + expect(means.map((e) => e.date), [DateTime(2026, 7, 27), DateTime(2026, 8, 3)]); + expect(means.map((e) => e.value), [10000, 7000]); + }); + + test('carries the span of everything measured in the week', () { + final ranges = sparkWeeklyPoints([ + MeasurementChartEntry(100, DateTime(2026, 8, 3), min: 79, max: 122), + MeasurementChartEntry(105, DateTime(2026, 8, 5), min: 82, max: 128), + ]); + + final week = ranges.single; + expect(week.date, DateTime(2026, 8, 3)); + expect(week.min, 79); + expect(week.max, 128); + }); + }); + + group('sparkWeeklyStacks', () { + test('per component the mean over the days it reported', () { + final stacks = sparkWeeklyStacks([ + MeasurementStackedEntry(DateTime(2026, 8, 3), const [400, 90]), + MeasurementStackedEntry(DateTime(2026, 8, 4), const [440, null]), + ]); + + final week = stacks.single; + expect(week.date, DateTime(2026, 8, 3)); + expect(week.values, [420, 90]); + }); + }); + + group('sparkBars', () { + final start = DateTime(2026, 8, 1); + + test('lays each day into its slot, one segment from zero', () { + final data = sparkBars( + [ + MeasurementChartEntry(10, DateTime(2026, 8, 1)), + MeasurementChartEntry(20, DateTime(2026, 8, 3)), + ], + start: start, + slotCount: 7, + ); + + expect(data.bars.map((b) => b.slot), [0, 2]); + expect(data.bars.first.segments.single, (from: 0, to: 10, colorIndex: 0)); + expect(data.minValue, 0); + expect(data.maxValue, 20); + }); + + test('weekly slots hold a calendar week each', () { + final monday = DateTime(2026, 5, 11); + final data = sparkBars( + [ + MeasurementChartEntry(7000, DateTime(2026, 5, 11)), + MeasurementChartEntry(9000, DateTime(2026, 8, 3)), + ], + start: monday, + slotCount: 13, + slotDays: 7, + ); + + expect(data.bars.map((b) => b.slot), [0, 12]); + }); + + test('drops what falls outside the window instead of misplacing it', () { + final data = sparkBars( + [ + MeasurementChartEntry(10, DateTime(2026, 7, 31)), + MeasurementChartEntry(20, DateTime(2026, 8, 8)), + ], + start: start, + slotCount: 7, + ); + + expect(data.isEmpty, isTrue); + }); + }); + + group('sparkFloatingBars', () { + test('spans the reading, and holds a single value as a point-sized bar', () { + final data = sparkFloatingBars( + [ + MeasurementChartEntry(100, DateTime(2026, 8, 1), min: 79, max: 122), + MeasurementChartEntry(110, DateTime(2026, 8, 2)), + ], + start: DateTime(2026, 8, 1), + slotCount: 7, + ); + + expect(data.bars.first.segments.single, (from: 79, to: 122, colorIndex: 0)); + expect(data.bars.last.segments.single, (from: 110, to: 110, colorIndex: 0)); + // The bars float: the axis follows the readings, not zero + expect(data.minValue, 79); + }); + }); + + group('sparkStackedBars', () { + test('one segment per component, coloured by its position', () { + final data = sparkStackedBars( + [ + MeasurementStackedEntry(DateTime(2026, 8, 2), const [240, null, 60]), + ], + start: DateTime(2026, 8, 1), + slotCount: 7, + ); + + expect(data.bars.single.slot, 1); + expect(data.bars.single.segments, [ + (from: 0.0, to: 240.0, colorIndex: 0), + (from: 240.0, to: 300.0, colorIndex: 2), + ]); + }); + }); + + group('sparkDeltaBars', () { + test('one signed bar per week, slotted by its Monday', () { + final start = DateTime(2026, 6, 8); + final data = sparkDeltaBars( + [ + MeasurementChartEntry(-0.4, DateTime(2026, 6, 15)), + MeasurementChartEntry(0.2, DateTime(2026, 8, 3)), + ], + start: start, + slotCount: 9, + ); + + expect(data.signed, isTrue); + expect(data.bars.map((b) => b.slot), [1, 8]); + // Signed bars hang off zero, so the bounds always include it + expect(data.minValue, -0.4); + expect(data.maxValue, 0.2); + }); + }); + + group('sparkIsSparse', () { + test('below the minimum the line spark switches to dots', () { + final days = [ + MeasurementChartEntry(1, DateTime(2026, 8, 1)), + MeasurementChartEntry(2, DateTime(2026, 8, 2)), + ]; + + expect(sparkIsSparse(days), isTrue); + expect(sparkIsSparse([...days, MeasurementChartEntry(3, DateTime(2026, 8, 3))]), isFalse); + }); + }); +} diff --git a/test/features/measurements/models/measurement_category_test.dart b/test/features/measurements/models/measurement_category_test.dart index f181831d2..4213b2fb3 100644 --- a/test/features/measurements/models/measurement_category_test.dart +++ b/test/features/measurements/models/measurement_category_test.dart @@ -142,6 +142,18 @@ void main() { }); }); + group('displayDecimals', () { + test('follows the resolution the metric is measured at', () { + expect(MetricType.restingHeartRate.displayDecimals, 0); + expect(MetricType.bloodPressureSystolic.displayDecimals, 0); + expect(MetricType.energy.displayDecimals, 0); + expect(MetricType.bodyWeight.displayDecimals, 1); + expect(MetricType.bodyFat.displayDecimals, 1); + expect(MetricType.custom.displayDecimals, 1); + expect(MetricType.distance.displayDecimals, 2); + }); + }); + group('MetricType', () { test('fromWire maps a known wire value to its enum case', () { expect(MetricType.fromWire('body_fat'), MetricType.bodyFat); diff --git a/test/features/measurements/screens/measurement_categories_screen_test.dart b/test/features/measurements/screens/measurement_categories_screen_test.dart index 3347d256b..206a6d82d 100644 --- a/test/features/measurements/screens/measurement_categories_screen_test.dart +++ b/test/features/measurements/screens/measurement_categories_screen_test.dart @@ -23,7 +23,8 @@ import 'package:mockito/annotations.dart'; import 'package:wger/features/measurements/providers/measurement_notifier.dart'; import 'package:wger/features/measurements/providers/measurement_repository.dart'; import 'package:wger/features/measurements/screens/measurement_categories_screen.dart'; -import 'package:wger/features/measurements/widgets/charts.dart'; +import 'package:wger/features/measurements/widgets/measurement_fab.dart'; +import 'package:wger/features/measurements/widgets/measurement_tile.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import '../../../../test_data/measurements.dart'; @@ -63,12 +64,12 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Body'), findsOneWidget); - expect(find.text('Body fat'), findsOneWidget); - expect(find.text('Biceps'), findsOneWidget); - expect(find.text('Blood pressure'), findsOneWidget); - expect(find.text('Systolic'), findsOneWidget); - expect(find.text('Diastolic'), findsOneWidget); - expect(find.byType(ListTile), findsNWidgets(2)); // Systolic , Diastolic - expect(find.byType(MeasurementChartWidgetFl), findsNWidgets(2)); // Body fat, Biceps + // One tile per top-level category; the components live behind the group's. + // hitTestable: the closed FAB menu holds the same names, invisibly. + expect(find.byType(MeasurementTile), findsNWidgets(3)); + expect(find.text('Body fat').hitTestable(), findsOneWidget); + expect(find.text('Biceps').hitTestable(), findsOneWidget); + expect(find.text('Blood pressure').hitTestable(), findsOneWidget); + expect(find.byType(MeasurementsFab), findsOneWidget); }); } diff --git a/test/features/measurements/widgets/categories_test.dart b/test/features/measurements/widgets/categories_test.dart index 64ff24e43..e92c4e06f 100644 --- a/test/features/measurements/widgets/categories_test.dart +++ b/test/features/measurements/widgets/categories_test.dart @@ -28,6 +28,7 @@ import 'package:wger/features/measurements/providers/measurement_notifier.dart'; import 'package:wger/features/measurements/providers/measurement_repository.dart'; import 'package:wger/features/measurements/widgets/categories.dart'; import 'package:wger/features/measurements/widgets/categories_card.dart'; +import 'package:wger/features/measurements/widgets/measurement_tile.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import '../../../../test_data/body_weight.dart'; @@ -72,7 +73,7 @@ void main() { }); group('CategoriesList', () { - testWidgets('two top-level categories render two CategoriesCard widgets', (tester) async { + testWidgets('two top-level categories render two grid tiles', (tester) async { stubMeasurementReads(mockRepo, getMeasurementCategories(), getMeasurementEntries()); await tester.pumpWidget( @@ -84,13 +85,13 @@ void main() { ); await tester.pumpAndSettle(); - expect(find.byType(CategoriesCard), findsNWidgets(2)); + expect(find.byType(MeasurementTile), findsNWidgets(2)); }); - testWidgets('children of multi-value groups are not rendered as own list items', ( + testWidgets('children of multi-value groups are not rendered as own tiles', ( tester, ) async { - // Only 'bp' should produce a CategoriesCard; children stay inside it. + // Only 'bp' should produce a tile; the components live behind it. stubMeasurementReads(mockRepo, getBloodPressureGroup(), getBloodPressureEntries()); await tester.pumpWidget( @@ -102,18 +103,17 @@ void main() { ); await tester.pumpAndSettle(); - expect(find.byType(CategoriesCard), findsOneWidget); - expect(find.text('Systolic'), findsOneWidget); - expect(find.text('Diastolic'), findsOneWidget); + expect(find.byType(MeasurementTile), findsOneWidget); + expect(find.text('Blood pressure'), findsOneWidget); }); - testWidgets('body weight leads the list, wherever it is sorted', (tester) async { - // The card is the way into the weight screen, so it stays on top rather - // than taking the position the category order gives it + testWidgets('body weight keeps its full card on top of the grid', (tester) async { + // The card is the way into the weight screen and stays a card, the one + // format decision the grid does not touch final categories = [...getMeasurementCategories(), getBodyWeightCategory()]; final entries = {...getMeasurementEntries(), ...bodyWeightEntries()}; stubMeasurementReads(mockRepo, categories, entries); - // Tall enough for all three cards; the list builds only what it shows + // Tall enough for the card and the grid together tester.view.physicalSize = const Size(800, 2200); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); @@ -121,8 +121,9 @@ void main() { await tester.pumpWidget(_wrap(mockRepo, categories: categories, entries: entries)); await tester.pumpAndSettle(); - // Once, at the top: the official category is left out of the list below - expect(find.byType(CategoriesCard), findsNWidgets(3)); + // Once, on top: the official category is left out of the grid below + expect(find.byType(CategoriesCard), findsOneWidget); + expect(find.byType(MeasurementTile), findsNWidgets(2)); expect(find.text('Weight'), findsOneWidget); expect( tester.getTopLeft(find.text('Weight')).dy, @@ -130,13 +131,14 @@ void main() { ); }); - testWidgets('empty list renders no CategoriesCard', (tester) async { + testWidgets('empty list renders neither card nor tiles', (tester) async { stubMeasurementReads(mockRepo, []); await tester.pumpWidget(_wrap(mockRepo)); await tester.pumpAndSettle(); expect(find.byType(CategoriesCard), findsNothing); + expect(find.byType(MeasurementTile), findsNothing); }); }); } diff --git a/test/features/measurements/widgets/charts/spark_charts_test.dart b/test/features/measurements/widgets/charts/spark_charts_test.dart new file mode 100644 index 000000000..4a17dbc8b --- /dev/null +++ b/test/features/measurements/widgets/charts/spark_charts_test.dart @@ -0,0 +1,137 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/measurements/charts/series.dart'; +import 'package:wger/features/measurements/charts/spark.dart'; +import 'package:wger/features/measurements/widgets/charts/spark_charts.dart'; + +Widget _wrap(Widget spark) => MaterialApp( + home: Scaffold(body: SizedBox(width: 150, height: 40, child: spark)), +); + +void main() { + final start = DateTime(2026, 8, 1); + + group('SparkLineChart', () { + testWidgets('paints a line for a series, and nothing for an empty one', (tester) async { + final entries = [ + MeasurementChartEntry(80, DateTime(2026, 8, 1)), + MeasurementChartEntry(81, DateTime(2026, 8, 3)), + MeasurementChartEntry(80.5, DateTime(2026, 8, 7)), + ]; + + await tester.pumpWidget(_wrap(SparkLineChart(entries, start: start, days: 7))); + expect(find.byType(SparkLineChart), findsOneWidget); + + // An empty series paints nothing, but the widget itself never fails + await tester.pumpWidget(_wrap(SparkLineChart(const [], start: start, days: 7))); + expect(tester.takeException(), isNull); + }); + + testWidgets('a flat series stays paintable instead of dividing by zero', (tester) async { + final entries = [ + MeasurementChartEntry(80, DateTime(2026, 8, 1)), + MeasurementChartEntry(80, DateTime(2026, 8, 5)), + ]; + + await tester.pumpWidget(_wrap(SparkLineChart(entries, start: start, days: 7))); + + expect(tester.takeException(), isNull); + }); + + testWidgets('dots mode renders for a sparse series', (tester) async { + final entries = [MeasurementChartEntry(38.5, DateTime(2026, 8, 1))]; + + await tester.pumpWidget( + _wrap(SparkLineChart(entries, start: start, days: 91, dots: true)), + ); + + expect(tester.takeException(), isNull); + }); + }); + + group('SparkBarChart', () { + testWidgets('paints plain, floating, stacked and signed data', (tester) async { + final variants = [ + sparkBars( + [ + MeasurementChartEntry(8000, DateTime(2026, 8, 2)), + ], + start: start, + slotCount: 7, + ), + sparkFloatingBars( + [ + MeasurementChartEntry(100, DateTime(2026, 8, 2), min: 79, max: 122), + ], + start: start, + slotCount: 7, + ), + sparkStackedBars( + [ + MeasurementStackedEntry(DateTime(2026, 8, 2), const [240, 60]), + ], + start: start, + slotCount: 7, + ), + sparkDeltaBars( + [ + MeasurementChartEntry(-0.4, DateTime(2026, 8, 3)), + ], + start: start, + slotCount: 9, + ), + ]; + + for (final data in variants) { + await tester.pumpWidget(_wrap(SparkBarChart(data))); + expect(tester.takeException(), isNull); + } + }); + + testWidgets('an empty spark paints nothing without failing', (tester) async { + await tester.pumpWidget( + _wrap(SparkBarChart(sparkBars(const [], start: start, slotCount: 7))), + ); + + expect(tester.takeException(), isNull); + }); + }); + + group('SparkHeatmap', () { + testWidgets('paints the four-week strip', (tester) async { + final today = DateTime(2026, 8, 7); + final days = [ + for (var day = 0; day < 14; day++) + MeasurementChartEntry(day.isEven ? 8000 : 0, DateTime(2026, 8, 7 - day)), + ]; + + await tester.pumpWidget(_wrap(SparkHeatmap(days, weeks: 4, today: today))); + + expect(tester.takeException(), isNull); + }); + + testWidgets('an empty history paints the empty grid', (tester) async { + await tester.pumpWidget(_wrap(SparkHeatmap(const [], weeks: 4, today: DateTime(2026, 8, 7)))); + + expect(tester.takeException(), isNull); + }); + }); +} diff --git a/test/features/measurements/widgets/measurement_fab_test.dart b/test/features/measurements/widgets/measurement_fab_test.dart new file mode 100644 index 000000000..1ac29858a --- /dev/null +++ b/test/features/measurements/widgets/measurement_fab_test.dart @@ -0,0 +1,128 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:wger/core/form_screen.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/measurement_fab.dart'; +import 'package:wger/features/measurements/widgets/metric_picker.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../helpers/measurement_repository_stubs.dart'; +import 'measurement_fab_test.mocks.dart'; + +MeasurementEntry _entry(String categoryId, {required String source}) => MeasurementEntry( + id: '$categoryId-1', + categoryId: categoryId, + date: DateTime(2026, 8, 1), + value: 1, + notes: '', + source: source, +); + +Widget _wrap( + List categories, + Map> entries, +) { + final mockRepo = MockMeasurementRepository(); + stubMeasurementReads(mockRepo, categories, entries); + + return ProviderScope( + overrides: [measurementRepositoryProvider.overrideWithValue(mockRepo)], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + routes: {FormScreen.routeName: (_) => const Text('form-screen')}, + home: const Scaffold(floatingActionButton: MeasurementsFab()), + ), + ); +} + +@GenerateMocks([MeasurementRepository]) +void main() { + final biceps = MeasurementCategory(id: 'biceps', name: 'Biceps', unit: 'cm'); + final restingHeartRate = MeasurementCategory( + id: 'rhr', + name: 'Resting heart rate', + unit: 'bpm', + metricType: MetricType.restingHeartRate, + ); + + final categories = [biceps, restingHeartRate]; + final entries = { + 'biceps': [_entry('biceps', source: 'user')], + 'rhr': [_entry('rhr', source: 'google')], + }; + + group('MeasurementsFab', () { + testWidgets('opens into the hand-kept categories and the picker action', (tester) async { + await tester.pumpWidget(_wrap(categories, entries)); + await tester.pumpAndSettle(); + + // Closed: the menu is not tappable + expect(find.text('Biceps').hitTestable(), findsNothing); + + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + + expect(find.text('Biceps').hitTestable(), findsOneWidget); + expect(find.text('Track something new').hitTestable(), findsOneWidget); + // Machine-fed by its newest reading, so logging by hand is not offered + expect(find.text('Resting heart rate').hitTestable(), findsNothing); + }); + + testWidgets('a category action opens its entry form', (tester) async { + await tester.pumpWidget(_wrap(categories, entries)); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Biceps')); + await tester.pumpAndSettle(); + + expect(find.text('form-screen'), findsOneWidget); + }); + + testWidgets('the picker action opens the metric picker sheet', (tester) async { + await tester.pumpWidget(_wrap(categories, entries)); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Track something new')); + await tester.pumpAndSettle(); + + expect(find.byType(MetricPickerSheet), findsOneWidget); + }); + + testWidgets('a category without entries counts as hand-kept', (tester) async { + await tester.pumpWidget(_wrap([restingHeartRate], const {})); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + + expect(find.text('Resting heart rate').hitTestable(), findsOneWidget); + }); + }); +} diff --git a/test/features/measurements/widgets/measurement_fab_test.mocks.dart b/test/features/measurements/widgets/measurement_fab_test.mocks.dart new file mode 100644 index 000000000..6e91c093c --- /dev/null +++ b/test/features/measurements/widgets/measurement_fab_test.mocks.dart @@ -0,0 +1,281 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/features/measurements/widgets/measurement_fab_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/measurements/models/measurement_bucket.dart' as _i6; +import 'package:wger/features/measurements/models/measurement_category.dart' as _i4; +import 'package:wger/features/measurements/models/measurement_entry.dart' as _i5; +import 'package:wger/features/measurements/providers/measurement_repository.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [MeasurementRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepository { + MockMeasurementRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchAllWithoutEntries() => + (super.noSuchMethod( + Invocation.method(#watchAllWithoutEntries, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream<_i4.MeasurementCategory?> watchCategoryWithoutEntries( + String? id, + ) => + (super.noSuchMethod( + Invocation.method(#watchCategoryWithoutEntries, [id]), + returnValue: _i3.Stream<_i4.MeasurementCategory?>.empty(), + ) + as _i3.Stream<_i4.MeasurementCategory?>); + + @override + _i3.Stream<_i4.MeasurementCategory?> watchOfficialBodyWeightCategory() => + (super.noSuchMethod( + Invocation.method(#watchOfficialBodyWeightCategory, []), + returnValue: _i3.Stream<_i4.MeasurementCategory?>.empty(), + ) + as _i3.Stream<_i4.MeasurementCategory?>); + + @override + _i3.Stream> watchEntries( + String? categoryId, { + required int? limit, + }) => + (super.noSuchMethod( + Invocation.method(#watchEntries, [categoryId], {#limit: limit}), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream> watchGroupEntries( + String? parentId, { + required int? limit, + }) => + (super.noSuchMethod( + Invocation.method(#watchGroupEntries, [parentId], {#limit: limit}), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream> watchLatestEntries() => + (super.noSuchMethod( + Invocation.method(#watchLatestEntries, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream> watchEntryBuckets( + String? categoryId, { + DateTime? since, + DateTime? until, + _i6.MeasurementBucketLevel? level = _i6.MeasurementBucketLevel.auto, + int? maxPoints = 200, + }) => + (super.noSuchMethod( + Invocation.method( + #watchEntryBuckets, + [categoryId], + { + #since: since, + #until: until, + #level: level, + #maxPoints: maxPoints, + }, + ), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream>> watchGroupBuckets( + String? parentId, { + DateTime? since, + _i6.MeasurementBucketLevel? level = _i6.MeasurementBucketLevel.auto, + int? maxPoints = 200, + }) => + (super.noSuchMethod( + Invocation.method( + #watchGroupBuckets, + [parentId], + {#since: since, #level: level, #maxPoints: maxPoints}, + ), + returnValue: _i3.Stream>>.empty(), + ) + as _i3.Stream>>); + + @override + _i3.Stream>> watchDailyBuckets() => + (super.noSuchMethod( + Invocation.method(#watchDailyBuckets, []), + returnValue: _i3.Stream>>.empty(), + ) + as _i3.Stream>>); + + @override + _i3.Stream> watchValueCounts( + String? categoryId, { + DateTime? since, + bool? summedPerDay = false, + }) => + (super.noSuchMethod( + Invocation.method( + #watchValueCounts, + [categoryId], + {#since: since, #summedPerDay: summedPerDay}, + ), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Future> getCategoriesOnce() => + (super.noSuchMethod( + Invocation.method(#getCategoriesOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + + @override + _i3.Future> getExternalIds(String? categoryId) => + (super.noSuchMethod( + Invocation.method(#getExternalIds, [categoryId]), + returnValue: _i3.Future>.value({}), + ) + as _i3.Future>); + + @override + _i3.Future> getEntriesByExternalId( + String? categoryId, + ) => + (super.noSuchMethod( + Invocation.method(#getEntriesByExternalId, [categoryId]), + returnValue: _i3.Future>.value( + {}, + ), + ) + as _i3.Future>); + + @override + _i3.Future hasEntries(String? categoryId) => + (super.noSuchMethod( + Invocation.method(#hasEntries, [categoryId]), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftGroupEntries( + List<_i5.MeasurementEntry>? entries, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftGroupEntries, [entries]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteLocalDriftCategory(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDriftCategory, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDriftCategory( + _i4.MeasurementCategory? category, + ) => + (super.noSuchMethod( + Invocation.method(#updateLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftCategory(_i4.MeasurementCategory? category) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftCategoryGroup( + List<_i4.MeasurementCategory>? categories, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftCategoryGroup, [categories]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/features/measurements/widgets/measurement_tile_test.dart b/test/features/measurements/widgets/measurement_tile_test.dart new file mode 100644 index 000000000..07dec7971 --- /dev/null +++ b/test/features/measurements/widgets/measurement_tile_test.dart @@ -0,0 +1,302 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:intl/intl.dart'; +import 'package:mockito/annotations.dart'; +import 'package:wger/features/measurements/charts/range.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_notifier.dart'; +import 'package:wger/features/measurements/providers/measurement_repository.dart'; +import 'package:wger/features/measurements/screens/measurement_entries_screen.dart'; +import 'package:wger/features/measurements/widgets/charts.dart'; +import 'package:wger/features/measurements/widgets/measurement_tile.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../helpers/measurement_chart_buckets.dart'; +import '../../../helpers/measurement_repository_stubs.dart'; +import 'measurement_tile_test.mocks.dart'; + +/// The calendar day [daysAgo] days back, at midnight like a day bucket. +DateTime _day(int daysAgo) { + final now = DateTime.now(); + return DateTime(now.year, now.month, now.day - daysAgo); +} + +MeasurementEntry _entry(String categoryId, num value, DateTime date, {String source = 'user'}) => + MeasurementEntry( + id: '$categoryId-$date', + categoryId: categoryId, + date: date, + value: value, + notes: '', + source: source, + ); + +Widget _wrap( + MeasurementCategory category, { + List categories = const [], + Map> entries = const {}, + ChartRange range = ChartRange.last3Months, +}) { + final mockRepo = MockMeasurementRepository(); + stubMeasurementReads(mockRepo, categories.isEmpty ? [category] : categories, entries); + + return ProviderScope( + overrides: [ + measurementRepositoryProvider.overrideWithValue(mockRepo), + measurementChartBucketsProvider.overrideWith(chartBucketsFrom(entries)), + measurementGroupBucketsProvider.overrideWith( + groupBucketsFrom(categories.isEmpty ? [category] : categories, entries), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + routes: { + MeasurementEntriesScreen.routeName: (_) => const Text('entries-screen'), + }, + home: Scaffold( + body: Center( + child: SizedBox( + width: 180, + height: measurementTileExtent, + child: MeasurementTile(category, range: range), + ), + ), + ), + ), + ); +} + +@GenerateMocks([MeasurementRepository]) +void main() { + final restingHeartRate = MeasurementCategory( + id: 'rhr', + name: 'Resting heart rate', + unit: 'bpm', + metricType: MetricType.restingHeartRate, + ); + + group('MeasurementTile', () { + testWidgets('daily tile: latest value, weekday axis and a stable trend', (tester) async { + final entries = { + 'rhr': [for (var day = 6; day >= 0; day--) _entry('rhr', 61, _day(day))], + }; + + await tester.pumpWidget(_wrap(restingHeartRate, entries: entries)); + await tester.pumpAndSettle(); + + expect(find.text('Resting heart rate'), findsOneWidget); + expect(find.text('61 bpm'), findsOneWidget); + expect(find.byType(SparkLineChart), findsOneWidget); + expect(find.textContaining('stable'), findsOneWidget); + }); + + testWidgets('a moving value quotes its weekly rate instead', (tester) async { + final entries = { + 'rhr': [for (var day = 6; day >= 0; day--) _entry('rhr', 70 - day * 2, _day(day))], + }; + + await tester.pumpWidget(_wrap(restingHeartRate, entries: entries)); + await tester.pumpAndSettle(); + + expect(find.textContaining('/week'), findsOneWidget); + expect(find.textContaining('↗'), findsOneWidget); + }); + + testWidgets('sparse tile: dots, months and the last-measured date', (tester) async { + final lastMeasured = _day(21); + final entries = { + 'biceps': [_entry('biceps', 38.5, lastMeasured)], + }; + final biceps = MeasurementCategory(id: 'biceps', name: 'Biceps', unit: 'cm'); + + await tester.pumpWidget(_wrap(biceps, entries: entries)); + await tester.pumpAndSettle(); + + expect(find.text('38.5 cm'), findsOneWidget); + final dots = tester.widget(find.byType(SparkLineChart)); + expect(dots.dots, isTrue); + expect(find.text(DateFormat.yMd('en').format(lastMeasured)), findsOneWidget); + }); + + testWidgets('summed tile: bars and the window average', (tester) async { + final steps = MeasurementCategory( + id: 'steps', + name: 'Steps', + metricType: MetricType.steps, + ); + final entries = { + 'steps': [_entry('steps', 8000, _day(1)), _entry('steps', 6000, _day(2))], + }; + + await tester.pumpWidget(_wrap(steps, entries: entries)); + await tester.pumpAndSettle(); + + expect(find.byType(SparkBarChart), findsOneWidget); + expect(find.textContaining('avg'), findsOneWidget); + }); + + testWidgets('the range filter decides between daily and weekly slots', (tester) async { + final steps = MeasurementCategory( + id: 'steps', + name: 'Steps', + metricType: MetricType.steps, + ); + final entries = { + 'steps': [_entry('steps', 8000, _day(1)), _entry('steps', 6000, _day(2))], + }; + + // A week is seven daily slots and a month one per day; three months + // come as calendar weeks + await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.lastWeek)); + await tester.pumpAndSettle(); + var chart = tester.widget(find.byType(SparkBarChart)); + expect(chart.data.slotCount, 7); + + await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.lastMonth)); + await tester.pumpAndSettle(); + chart = tester.widget(find.byType(SparkBarChart)); + expect(chart.data.slotCount, 31); + + await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.last3Months)); + await tester.pumpAndSettle(); + chart = tester.widget(find.byType(SparkBarChart)); + expect(chart.data.slotCount, 13); + }); + + testWidgets('blood pressure tile: the reading quoted high over low', (tester) async { + final group = MeasurementCategory( + id: 'bp', + name: 'Blood pressure', + unit: 'mmHg', + metricType: MetricType.bloodPressure, + children: [ + MeasurementCategory(id: 'sys', name: 'Systolic', unit: 'mmHg', parentId: 'bp'), + MeasurementCategory(id: 'dia', name: 'Diastolic', unit: 'mmHg', parentId: 'bp'), + ], + ); + final entries = { + 'sys': [_entry('sys', 122, _day(0))], + 'dia': [_entry('dia', 79, _day(0))], + }; + + await tester.pumpWidget( + _wrap(group, categories: [group, ...group.children], entries: entries), + ); + await tester.pumpAndSettle(); + + expect(find.text('122/79 mmHg'), findsOneWidget); + expect(find.byType(SparkBarChart), findsOneWidget); + }); + + testWidgets('sleep tile: the total leads, stacked bars behind it', (tester) async { + final group = MeasurementCategory( + id: 'sleep', + name: 'Sleep', + unit: 'min', + metricType: MetricType.sleep, + children: [ + MeasurementCategory( + id: 'total', + name: 'Total sleep', + unit: 'min', + metricType: MetricType.sleepTotal, + parentId: 'sleep', + ), + MeasurementCategory( + id: 'deep', + name: 'Deep sleep', + unit: 'min', + metricType: MetricType.sleepDeep, + parentId: 'sleep', + ), + ], + ); + final entries = { + 'total': [_entry('total', 432, _day(1))], + 'deep': [_entry('deep', 90, _day(1))], + }; + + await tester.pumpWidget( + _wrap(group, categories: [group, ...group.children], entries: entries), + ); + await tester.pumpAndSettle(); + + expect(find.text('7:12 h'), findsOneWidget); + expect(find.byType(SparkBarChart), findsOneWidget); + }); + + testWidgets('heatmap tile: the grid plus the footer of its kind', (tester) async { + final steps = MeasurementCategory( + id: 'steps', + name: 'Steps', + metricType: MetricType.steps, + chartType: ChartType.heatmap, + ); + final entries = { + 'steps': [_entry('steps', 8000, _day(1)), _entry('steps', 6000, _day(2))], + }; + + await tester.pumpWidget(_wrap(steps, entries: entries)); + await tester.pumpAndSettle(); + + final heatmap = tester.widget(find.byType(SparkHeatmap)); + // Three months of filter come as 13 week columns + expect(heatmap.weeks, 13); + expect(find.textContaining('avg'), findsOneWidget); + }); + + testWidgets('the hero rounds to the decimals the type is measured at', (tester) async { + // A pulse has no meaningful tenths; the stored value stays exact and is + // shown in full on the detail screens + final entries = { + 'rhr': [_entry('rhr', 61.44, _day(0))], + }; + + await tester.pumpWidget(_wrap(restingHeartRate, entries: entries)); + await tester.pumpAndSettle(); + + expect(find.text('61 bpm'), findsOneWidget); + }); + + testWidgets('a tile without entries still stands, value dashed out', (tester) async { + await tester.pumpWidget(_wrap(restingHeartRate)); + await tester.pumpAndSettle(); + + expect(find.text('— bpm'), findsOneWidget); + }); + + testWidgets('tapping the tile opens the entries screen', (tester) async { + final entries = { + 'rhr': [_entry('rhr', 61, _day(0))], + }; + + await tester.pumpWidget(_wrap(restingHeartRate, entries: entries)); + await tester.pumpAndSettle(); + await tester.tap(find.byType(MeasurementTile)); + await tester.pumpAndSettle(); + + expect(find.text('entries-screen'), findsOneWidget); + }); + }); +} diff --git a/test/features/measurements/widgets/measurement_tile_test.mocks.dart b/test/features/measurements/widgets/measurement_tile_test.mocks.dart new file mode 100644 index 000000000..b417f3393 --- /dev/null +++ b/test/features/measurements/widgets/measurement_tile_test.mocks.dart @@ -0,0 +1,281 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/features/measurements/widgets/measurement_tile_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/measurements/models/measurement_bucket.dart' as _i6; +import 'package:wger/features/measurements/models/measurement_category.dart' as _i4; +import 'package:wger/features/measurements/models/measurement_entry.dart' as _i5; +import 'package:wger/features/measurements/providers/measurement_repository.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [MeasurementRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepository { + MockMeasurementRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchAllWithoutEntries() => + (super.noSuchMethod( + Invocation.method(#watchAllWithoutEntries, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream<_i4.MeasurementCategory?> watchCategoryWithoutEntries( + String? id, + ) => + (super.noSuchMethod( + Invocation.method(#watchCategoryWithoutEntries, [id]), + returnValue: _i3.Stream<_i4.MeasurementCategory?>.empty(), + ) + as _i3.Stream<_i4.MeasurementCategory?>); + + @override + _i3.Stream<_i4.MeasurementCategory?> watchOfficialBodyWeightCategory() => + (super.noSuchMethod( + Invocation.method(#watchOfficialBodyWeightCategory, []), + returnValue: _i3.Stream<_i4.MeasurementCategory?>.empty(), + ) + as _i3.Stream<_i4.MeasurementCategory?>); + + @override + _i3.Stream> watchEntries( + String? categoryId, { + required int? limit, + }) => + (super.noSuchMethod( + Invocation.method(#watchEntries, [categoryId], {#limit: limit}), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream> watchGroupEntries( + String? parentId, { + required int? limit, + }) => + (super.noSuchMethod( + Invocation.method(#watchGroupEntries, [parentId], {#limit: limit}), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream> watchLatestEntries() => + (super.noSuchMethod( + Invocation.method(#watchLatestEntries, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream> watchEntryBuckets( + String? categoryId, { + DateTime? since, + DateTime? until, + _i6.MeasurementBucketLevel? level = _i6.MeasurementBucketLevel.auto, + int? maxPoints = 200, + }) => + (super.noSuchMethod( + Invocation.method( + #watchEntryBuckets, + [categoryId], + { + #since: since, + #until: until, + #level: level, + #maxPoints: maxPoints, + }, + ), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Stream>> watchGroupBuckets( + String? parentId, { + DateTime? since, + _i6.MeasurementBucketLevel? level = _i6.MeasurementBucketLevel.auto, + int? maxPoints = 200, + }) => + (super.noSuchMethod( + Invocation.method( + #watchGroupBuckets, + [parentId], + {#since: since, #level: level, #maxPoints: maxPoints}, + ), + returnValue: _i3.Stream>>.empty(), + ) + as _i3.Stream>>); + + @override + _i3.Stream>> watchDailyBuckets() => + (super.noSuchMethod( + Invocation.method(#watchDailyBuckets, []), + returnValue: _i3.Stream>>.empty(), + ) + as _i3.Stream>>); + + @override + _i3.Stream> watchValueCounts( + String? categoryId, { + DateTime? since, + bool? summedPerDay = false, + }) => + (super.noSuchMethod( + Invocation.method( + #watchValueCounts, + [categoryId], + {#since: since, #summedPerDay: summedPerDay}, + ), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Future> getCategoriesOnce() => + (super.noSuchMethod( + Invocation.method(#getCategoriesOnce, []), + returnValue: _i3.Future>.value( + <_i4.MeasurementCategory>[], + ), + ) + as _i3.Future>); + + @override + _i3.Future> getExternalIds(String? categoryId) => + (super.noSuchMethod( + Invocation.method(#getExternalIds, [categoryId]), + returnValue: _i3.Future>.value({}), + ) + as _i3.Future>); + + @override + _i3.Future> getEntriesByExternalId( + String? categoryId, + ) => + (super.noSuchMethod( + Invocation.method(#getEntriesByExternalId, [categoryId]), + returnValue: _i3.Future>.value( + {}, + ), + ) + as _i3.Future>); + + @override + _i3.Future hasEntries(String? categoryId) => + (super.noSuchMethod( + Invocation.method(#hasEntries, [categoryId]), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDrift(_i5.MeasurementEntry? entry) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [entry]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftGroupEntries( + List<_i5.MeasurementEntry>? entries, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftGroupEntries, [entries]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteLocalDriftCategory(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDriftCategory, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDriftCategory( + _i4.MeasurementCategory? category, + ) => + (super.noSuchMethod( + Invocation.method(#updateLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftCategory(_i4.MeasurementCategory? category) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftCategory, [category]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDriftCategoryGroup( + List<_i4.MeasurementCategory>? categories, + ) => + (super.noSuchMethod( + Invocation.method(#addLocalDriftCategoryGroup, [categories]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future reorderCategories(List? orderedIds) => + (super.noSuchMethod( + Invocation.method(#reorderCategories, [orderedIds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +}