diff --git a/app/lib/features/chat/ui/sessions/session_row_content.dart b/app/lib/features/chat/ui/sessions/session_row_content.dart index 88e2a4e8..fa775be0 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import '../../../../core/api_gateway.dart'; import '../../../../ui/layout/app_list_avatar.dart'; import '../../../../ui/layout/app_list_row.dart'; +import '../../../../ui/text/relative_time_label.dart'; import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; import 'session_actions.dart'; @@ -48,6 +49,7 @@ class ChatSessionRow extends StatelessWidget { ? CupertinoTheme.of(context).primaryColor : Theme.of(context).colorScheme.primary; final text = chatSessionSubtitle(session); + final updatedAt = _chatSessionInstant(session['updated_at']); return AppListRow( key: Key('chat-row-$id'), cupertino: cupertino, @@ -78,7 +80,9 @@ class ChatSessionRow extends StatelessWidget { ], ), ), - time: relativeChatSessionTime(session['updated_at']), + timeWidget: updatedAt == null + ? null + : RelativeTimeLabel(instant: updatedAt), // `Closed` leads the line of a closed chat, then the model and folder. subtitle: Text.rich( TextSpan( @@ -111,6 +115,11 @@ class ChatSessionRow extends StatelessWidget { } } +DateTime? _chatSessionInstant(Object? updatedAt) { + final millis = chatSessionMillis(updatedAt); + return millis <= 0 ? null : DateTime.fromMillisecondsSinceEpoch(millis); +} + /// As tall as the title's text, so it follows text scaling. class _Star extends StatelessWidget { const _Star({required this.cupertino, required this.color}); diff --git a/app/lib/features/runs/ui/run_list_row.dart b/app/lib/features/runs/ui/run_list_row.dart index ec7815b1..b905802f 100644 --- a/app/lib/features/runs/ui/run_list_row.dart +++ b/app/lib/features/runs/ui/run_list_row.dart @@ -6,7 +6,7 @@ import '../../../ui/adaptive/host.dart'; import '../../../ui/layout/app_list_avatar.dart'; import '../../../ui/layout/app_list_row.dart'; import '../../../ui/status/run_status_icon.dart'; -import '../../../ui/text/relative_time.dart'; +import '../../../ui/text/relative_time_label.dart'; import '../domain/run_deletion.dart'; import '../domain/run_models.dart'; import 'run_more_menu.dart'; @@ -77,6 +77,7 @@ class RunListRow extends StatelessWidget { final scheduled = run['scheduled'] == true; final bytes = runSizeBytes(run); final size = bytes == null ? null : formatByteSize(bytes); + final createdAt = DateTime.tryParse('${run['created_at'] ?? ''}'); final subtitle = [ ?pipelineLabel, if (scheduled) 'Scheduled', @@ -107,7 +108,9 @@ class RunListRow extends StatelessWidget { child: RunStatusIcon(state: state, label: runStatusLabel(run)), ), title: Text(title), - time: formatRelativeTimestamp('${run['created_at'] ?? ''}', now: now), + timeWidget: createdAt == null + ? null + : RelativeTimeLabel(instant: createdAt, now: now), subtitle: Text(subtitle), compactSubtitle: Text(compactSubtitle), // A narrow list pane beside the open run leaves the row no room for a diff --git a/app/lib/ui/layout/app_list_row.dart b/app/lib/ui/layout/app_list_row.dart index 86f06f58..e9f9d026 100644 --- a/app/lib/ui/layout/app_list_row.dart +++ b/app/lib/ui/layout/app_list_row.dart @@ -39,6 +39,7 @@ class AppListRow extends StatelessWidget { required this.title, this.leading, this.time, + this.timeWidget, this.subtitle, this.compactSubtitle, this.subtitleLeading, @@ -59,6 +60,7 @@ class AppListRow extends StatelessWidget { final Widget title; final Widget? leading; final String? time; + final Widget? timeWidget; final Widget? subtitle; /// Replaces [subtitle] in a compact row, which has less room for facts. @@ -204,17 +206,25 @@ class AppListRow extends StatelessWidget { child: title, ), ), - if (!compact && time != null && time!.isNotEmpty) + if (!compact && + (timeWidget != null || (time != null && time!.isNotEmpty))) ConstrainedBox( constraints: BoxConstraints(maxWidth: constraints.maxWidth * 0.4), child: Padding( padding: const EdgeInsetsDirectional.only(start: 8), - child: Text( - time!, - style: styles.time, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), + child: timeWidget == null + ? Text( + time!, + style: styles.time, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ) + : DefaultTextStyle( + style: styles.time, + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: timeWidget!, + ), ), ), ], diff --git a/app/lib/ui/text/relative_time_label.dart b/app/lib/ui/text/relative_time_label.dart new file mode 100644 index 00000000..8851e300 --- /dev/null +++ b/app/lib/ui/text/relative_time_label.dart @@ -0,0 +1,109 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import 'relative_time.dart'; + +/// A relative-time label that rebuilds only itself when its formatter can +/// change. It stops its timer while the app is backgrounded. +class RelativeTimeLabel extends StatefulWidget { + const RelativeTimeLabel({super.key, required this.instant, this.now}); + + final DateTime? instant; + final DateTime? now; + + @override + State createState() => _RelativeTimeLabelState(); +} + +class _RelativeTimeLabelState extends State + with WidgetsBindingObserver { + Timer? _timer; + DateTime _now = DateTime.now(); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _schedule(); + } + + @override + void didUpdateWidget(RelativeTimeLabel oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.instant != widget.instant) _schedule(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + _now = DateTime.now(); + if (mounted) setState(() {}); + _schedule(current: _now); + } else if (state == AppLifecycleState.hidden || + // Not inactive: a desktop window that lost focus is still visible. + state == AppLifecycleState.paused || + state == AppLifecycleState.detached) { + _timer?.cancel(); + _timer = null; + } + } + + void _schedule({DateTime? current}) { + _timer?.cancel(); + final instant = widget.instant; + if (instant == null) return; + final now = current ?? widget.now ?? DateTime.now(); + _now = now; + final next = _nextBoundary(instant, now); + final delay = next.difference(now); + _timer = Timer(delay.isNegative ? Duration.zero : delay, () { + if (!mounted) return; + _now = _now.add(delay); + setState(() {}); + _schedule(current: _now); + }); + } + + DateTime _nextBoundary(DateTime instant, DateTime now) { + final difference = now.difference(instant); + final age = difference.abs(); + final unit = age < const Duration(hours: 1) + ? const Duration(minutes: 1) + : age < const Duration(days: 1) + ? const Duration(hours: 1) + : age < const Duration(days: 7) + ? const Duration(days: 1) + : null; + if (unit != null) { + final units = age.inMilliseconds ~/ unit.inMilliseconds; + final boundary = difference.isNegative + // Future labels use a decreasing count. Add a second so an exact + // boundary does not immediately schedule another zero-delay timer. + ? instant.subtract(unit * units).add(const Duration(seconds: 1)) + : instant.add(unit * (units + 1)); + if (boundary.isAfter(now)) return boundary; + } + final midnight = DateTime(now.year, now.month, now.day + 1); + return midnight.isAfter(now) + ? midnight + : now.add(const Duration(minutes: 1)); + } + + @override + Widget build(BuildContext context) { + // The row's time style (an unread row's accent) stays on the label + // itself, as on the plain Text this replaces. + return Text( + formatRelativeTime(widget.instant, now: _now) ?? '', + style: DefaultTextStyle.of(context).style, + ); + } + + @override + void dispose() { + _timer?.cancel(); + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } +} diff --git a/app/test/ui/text/relative_time_label_test.dart b/app/test/ui/text/relative_time_label_test.dart new file mode 100644 index 00000000..70c8474a --- /dev/null +++ b/app/test/ui/text/relative_time_label_test.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/text/relative_time_label.dart'; + +void main() { + testWidgets('updates at the next relative-time boundary', (tester) async { + final instant = DateTime.now().subtract(const Duration(minutes: 4)); + await tester.pumpWidget( + MaterialApp(home: RelativeTimeLabel(instant: instant)), + ); + expect(find.text('4m'), findsOneWidget); + + await tester.pump(const Duration(minutes: 1, seconds: 1)); + expect(find.text('5m'), findsOneWidget); + }); + + testWidgets('future labels schedule their next boundary', (tester) async { + final instant = DateTime.now().add(const Duration(minutes: 4)); + await tester.pumpWidget( + MaterialApp(home: RelativeTimeLabel(instant: instant)), + ); + expect(find.text('in 3m'), findsOneWidget); + + await tester.pump(const Duration(minutes: 1, seconds: 1)); + expect(find.text('in 2m'), findsOneWidget); + }); + + testWidgets('cancels its timer when disposed', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: RelativeTimeLabel( + instant: DateTime.now().subtract(const Duration(minutes: 4)), + ), + ), + ); + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + await tester.pump(const Duration(hours: 1)); + }); + + testWidgets('keeps ticking while inactive, pauses while hidden and ' + 'refreshes on resume', (tester) async { + final instant = DateTime.now().subtract(const Duration(minutes: 4)); + await tester.pumpWidget( + MaterialApp(home: RelativeTimeLabel(instant: instant)), + ); + expect(find.text('4m'), findsOneWidget); + + // A desktop window that lost focus is still on screen: keep ticking. + WidgetsBinding.instance.handleAppLifecycleStateChanged( + AppLifecycleState.inactive, + ); + await tester.pump(const Duration(minutes: 1, seconds: 1)); + expect(find.text('5m'), findsOneWidget); + + WidgetsBinding.instance.handleAppLifecycleStateChanged( + AppLifecycleState.hidden, + ); + await tester.pump(const Duration(minutes: 1, seconds: 1)); + expect(find.text('5m'), findsOneWidget); + + WidgetsBinding.instance.handleAppLifecycleStateChanged( + AppLifecycleState.inactive, + ); + WidgetsBinding.instance.handleAppLifecycleStateChanged( + AppLifecycleState.resumed, + ); + await tester.pump(); + await tester.pump(const Duration(minutes: 1, seconds: 1)); + expect(find.text('5m'), findsOneWidget); + }); +}