From bb7ed8fa239652c1d75ba666770140ab6347706b Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 9 Aug 2026 15:19:23 +0200 Subject: [PATCH] Say how long ago a tile's value was measured --- lib/core/formatting/formatting.dart | 37 +++++++++ .../widgets/measurement_tile.dart | 83 ++++++++++++------- lib/l10n/app_de.arb | 6 +- lib/l10n/app_en.arb | 36 ++++++++ lib/l10n/app_es.arb | 6 +- lib/l10n/app_fr.arb | 6 +- test/core/formatting_test.dart | 79 ++++++++++++++++++ .../widgets/measurement_tile_test.dart | 37 +++++++-- 8 files changed, 254 insertions(+), 36 deletions(-) diff --git a/lib/core/formatting/formatting.dart b/lib/core/formatting/formatting.dart index ba08515fc..2f7d008cc 100644 --- a/lib/core/formatting/formatting.dart +++ b/lib/core/formatting/formatting.dart @@ -16,8 +16,11 @@ * along with this program. If not, see . */ +import 'dart:math'; + import 'package:flutter/widgets.dart'; import 'package:intl/intl.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; /// A short date format (`DateFormat.yMd`) bound to the current locale's /// language. Chain further patterns (e.g. `.add_Hm()`) as needed. @@ -28,6 +31,40 @@ DateFormat localizedDate(BuildContext context) => NumberFormat localizedNumberFormat(BuildContext context) => NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); +/// A date in the past as a relative phrase ("today", "3 weeks ago"). +/// +/// Counts calendar days rather than elapsed hours, so an entry from late +/// yesterday still reads as yesterday this morning. The unit grows with the +/// distance: days within a week, then weeks, months, years. Matches react's +/// dateToRelative for past dates, which reaches the same output through Intl. +/// +/// A date ahead of [now] reads as today: the pickers do not offer one, so it +/// only ever arrives through clock skew between devices, and the phrases for +/// it (react has them from Intl) would be four more strings to translate for +/// a case nobody is looking at. +String relativeDate(BuildContext context, DateTime date, {DateTime? now}) { + final today = now ?? DateTime.now(); + // Calendar arithmetic in UTC, so a DST day is not 23 or 25 hours long + final elapsed = DateTime.utc( + today.year, + today.month, + today.day, + ).difference(DateTime.utc(date.year, date.month, date.day)).inDays; + final days = max(0, elapsed); + + final i18n = AppLocalizations.of(context); + if (days < DateTime.daysPerWeek) { + return i18n.relativeDaysAgo(days); + } + if (days < 31) { + return i18n.relativeWeeksAgo((days / 7).round()); + } + if (days < 365) { + return i18n.relativeMonthsAgo((days / 30).round()); + } + return i18n.relativeYearsAgo((days / 365).round()); +} + /// The unit a duration is stored in, which is what the health platforms deliver. const durationUnit = 'min'; diff --git a/lib/features/measurements/widgets/measurement_tile.dart b/lib/features/measurements/widgets/measurement_tile.dart index aa1bc6c9c..2afcca01c 100644 --- a/lib/features/measurements/widgets/measurement_tile.dart +++ b/lib/features/measurements/widgets/measurement_tile.dart @@ -39,6 +39,11 @@ 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. +/// +/// Holds the rows a tile stacks (name, value, spark, axis, chip) with room to +/// spare: they are laid out at their natural heights, so a tile sized to +/// exactly fit them overflows as soon as the text does not render at the size +/// it was measured at. const measurementTileExtent = 172.0; /// Height of the spark chart inside a tile. @@ -75,11 +80,26 @@ class MeasurementTile extends ConsumerWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - category.displayName(context), - style: Theme.of(context).textTheme.titleSmall, - maxLines: 1, - overflow: TextOverflow.ellipsis, + // How old the reading is rides on the name's line: it qualifies + // the value below, but a row of its own costs the tile more + // height than it can spare, and next to the value it would push + // a wide reading (a blood pressure) into an ellipsis + Row( + children: [ + // Expanded, not Flexible: the name keeps the width the date + // leaves, which pushes the date to the far edge instead of + // crowding it against the name + Expanded( + child: Text( + category.displayName(context), + style: Theme.of(context).textTheme.titleSmall, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 6), + _MeasuredAt(_newestOf(latest)), + ], ), _heroValue(context, latest), const Spacer(), @@ -237,15 +257,11 @@ class MeasurementTile extends ConsumerWidget { 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, - ), + _TrendChip( + points: points, + unit: category.unit, + decimals: category.metricType.displayDecimals, + ), ]; } } @@ -315,7 +331,9 @@ class MeasurementTile extends ConsumerWidget { return [ _SparkArea(child: SparkBarChart(data)), _axis(start, window.days!, weekly: window.weekly), - _LastMeasured(_newestOf(category.children, latest)), + // A range spans a reading rather than tracking a level, so the spread + // is what a chip could quote; the hero already says how recent it is + const SizedBox.shrink(), ]; } @@ -329,17 +347,22 @@ class MeasurementTile extends ConsumerWidget { child: SparkLineChart(fallback ?? const [], start: start, days: window.days!), ), _axis(start, window.days!, weekly: window.weekly), - _LastMeasured(_newestOf(category.children, latest)), + const SizedBox.shrink(), ]; } - 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 entry the hero value comes from: the category's own for a leaf, the + /// newest of the components for a group. + MeasurementEntry? _newestOf(Map latest) { + final candidates = category.hasChildren + ? category.children.map((child) => latest[child.id]) + : [latest[category.id]]; + + return candidates.nonNulls.fold( + null, + (newest, entry) => newest == null || entry.date.isAfter(newest.date) ? entry : newest, + ); + } } /// The axis row under a spark: one weekday letter per day where the window is @@ -523,10 +546,14 @@ class _AverageChip extends StatelessWidget { } } -/// 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); +/// How long ago the value below was measured: for a category the health sync +/// feeds every now and then, this is what says an old-looking chart is not a +/// broken one. +/// +/// Sizes to its text, so the row it sits in decides what happens when the +/// two do not fit; it cannot ellipsify itself. +class _MeasuredAt extends StatelessWidget { + const _MeasuredAt(this.entry); final MeasurementEntry? entry; @@ -538,7 +565,7 @@ class _LastMeasured extends StatelessWidget { } return Text( - localizedDate(context).format(entry!.date), + relativeDate(context, 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 1e1c21dfc..a208eada1 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1190,5 +1190,9 @@ "sparkTrendPerWeek": "{value}/Woche", "sparkTrendStable": "stabil", "trackNewMetric": "Etwas Neues aufzeichnen", - "chartRangeWeeks": "{count, plural, one{1 Woche} other{{count} Wochen}}" + "chartRangeWeeks": "{count, plural, one{1 Woche} other{{count} Wochen}}", + "relativeDaysAgo": "{count, plural, =0{heute} =1{gestern} other{vor {count} Tagen}}", + "relativeWeeksAgo": "{count, plural, one{vor 1 Woche} other{vor {count} Wochen}}", + "relativeMonthsAgo": "{count, plural, one{vor 1 Monat} other{vor {count} Monaten}}", + "relativeYearsAgo": "{count, plural, one{vor 1 Jahr} other{vor {count} Jahren}}" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index cacb529c6..c035f0d42 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -667,6 +667,42 @@ } } }, + "relativeDaysAgo": "{count, plural, =0{today} =1{yesterday} other{{count} days ago}}", + "@relativeDaysAgo": { + "description": "How long ago something was measured, for distances below a week", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "relativeWeeksAgo": "{count, plural, one{1 week ago} other{{count} weeks ago}}", + "@relativeWeeksAgo": { + "description": "How long ago something was measured, for distances below a month", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "relativeMonthsAgo": "{count, plural, one{1 month ago} other{{count} months ago}}", + "@relativeMonthsAgo": { + "description": "How long ago something was measured, for distances below a year", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "relativeYearsAgo": "{count, plural, one{1 year ago} other{{count} years ago}}", + "@relativeYearsAgo": { + "description": "How long ago something was measured, for distances of a year and more", + "placeholders": { + "count": { + "type": "int" + } + } + }, "sparkAverage": "avg {value}", "@sparkAverage": { "description": "Chip on an overview tile: the average over the charted days, e.g. 'avg 7:05' for sleep", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 47b01a306..70e9f46bd 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1229,5 +1229,9 @@ "sparkTrendPerWeek": "{value}/semana", "sparkTrendStable": "estable", "trackNewMetric": "Registrar algo nuevo", - "chartRangeWeeks": "{count, plural, one{1 semana} other{{count} semanas}}" + "chartRangeWeeks": "{count, plural, one{1 semana} other{{count} semanas}}", + "relativeDaysAgo": "{count, plural, =0{hoy} =1{ayer} other{hace {count} días}}", + "relativeWeeksAgo": "{count, plural, one{hace 1 semana} other{hace {count} semanas}}", + "relativeMonthsAgo": "{count, plural, one{hace 1 mes} other{hace {count} meses}}", + "relativeYearsAgo": "{count, plural, one{hace 1 año} other{hace {count} años}}" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index be9529194..3e7df2351 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1200,5 +1200,9 @@ "sparkTrendPerWeek": "{value}/semaine", "sparkTrendStable": "stable", "trackNewMetric": "Suivre autre chose", - "chartRangeWeeks": "{count, plural, one{1 semaine} other{{count} semaines}}" + "chartRangeWeeks": "{count, plural, one{1 semaine} other{{count} semaines}}", + "relativeDaysAgo": "{count, plural, =0{aujourd'hui} =1{hier} other{il y a {count} jours}}", + "relativeWeeksAgo": "{count, plural, one{il y a 1 semaine} other{il y a {count} semaines}}", + "relativeMonthsAgo": "{count, plural, one{il y a 1 mois} other{il y a {count} mois}}", + "relativeYearsAgo": "{count, plural, one{il y a 1 an} other{il y a {count} ans}}" } diff --git a/test/core/formatting_test.dart b/test/core/formatting_test.dart index 447b23ff2..288ac9ee5 100644 --- a/test/core/formatting_test.dart +++ b/test/core/formatting_test.dart @@ -16,8 +16,10 @@ * along with this program. If not, see . */ +import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:wger/core/formatting/formatting.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; void main() { group('hoursAndMinutes', () { @@ -81,4 +83,81 @@ void main() { expect(measurementUnit('kg'), 'kg'); }); }); + + group('relativeDate', () { + final today = DateTime(2026, 8, 8, 14, 30); + + /// [relativeDate] for a date [daysAgo] days back, read in [locale]. + Future phraseFor(WidgetTester tester, int daysAgo, {String locale = 'en'}) async { + late String phrase; + await tester.pumpWidget( + MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) { + phrase = relativeDate( + context, + DateTime(today.year, today.month, today.day - daysAgo, 6), + now: today, + ); + return const SizedBox(); + }, + ), + ), + ); + await tester.pumpAndSettle(); + return phrase; + } + + testWidgets('names the days close by instead of counting them', (tester) async { + expect(await phraseFor(tester, 0), 'today'); + expect(await phraseFor(tester, 1), 'yesterday'); + expect(await phraseFor(tester, 3), '3 days ago'); + }); + + testWidgets('the unit grows with the distance', (tester) async { + expect(await phraseFor(tester, 21), '3 weeks ago'); + expect(await phraseFor(tester, 60), '2 months ago'); + expect(await phraseFor(tester, 400), '1 year ago'); + }); + + testWidgets('counts calendar days, so this morning still reads as yesterday', (tester) async { + // The entry is 20 hours old but fell on yesterday's calendar day + late String phrase; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) { + phrase = relativeDate( + context, + DateTime(2026, 8, 7, 18), + now: DateTime(2026, 8, 8, 9), + ); + return const SizedBox(); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(phrase, 'yesterday'); + }); + + testWidgets('a date ahead of now reads as today rather than counting down', (tester) async { + // Only reachable through clock skew between devices, and the plural + // messages have no phrases for it: "-1 days ago" is what it used to say + expect(await phraseFor(tester, -1), 'today'); + expect(await phraseFor(tester, -10), 'today'); + expect(await phraseFor(tester, -400), 'today'); + }); + + testWidgets('speaks the locale it is read in', (tester) async { + expect(await phraseFor(tester, 0, locale: 'de'), 'heute'); + expect(await phraseFor(tester, 21, locale: 'de'), 'vor 3 Wochen'); + }); + }); } diff --git a/test/features/measurements/widgets/measurement_tile_test.dart b/test/features/measurements/widgets/measurement_tile_test.dart index 07dec7971..4673065a9 100644 --- a/test/features/measurements/widgets/measurement_tile_test.dart +++ b/test/features/measurements/widgets/measurement_tile_test.dart @@ -19,7 +19,6 @@ 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'; @@ -123,10 +122,9 @@ void main() { expect(find.textContaining('↗'), findsOneWidget); }); - testWidgets('sparse tile: dots, months and the last-measured date', (tester) async { - final lastMeasured = _day(21); + testWidgets('sparse tile: dots and the month axis', (tester) async { final entries = { - 'biceps': [_entry('biceps', 38.5, lastMeasured)], + 'biceps': [_entry('biceps', 38.5, _day(21))], }; final biceps = MeasurementCategory(id: 'biceps', name: 'Biceps', unit: 'cm'); @@ -136,7 +134,36 @@ void main() { 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('the hero says how long ago it was measured', (tester) async { + // Right under the value, since it qualifies the value rather than the + // chart; a stale-looking spark is then readable as "not measured since" + await tester.pumpWidget( + _wrap( + restingHeartRate, + entries: { + 'rhr': [_entry('rhr', 61, _day(0))], + }, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('today'), findsOneWidget); + }); + + testWidgets('a value measured a while back says so in weeks', (tester) async { + await tester.pumpWidget( + _wrap( + restingHeartRate, + entries: { + 'rhr': [_entry('rhr', 61, _day(21))], + }, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('3 weeks ago'), findsOneWidget); }); testWidgets('summed tile: bars and the window average', (tester) async {