diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index c491a935..3cad7eb1 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -238,6 +238,7 @@ class _RunsScreenState extends State { builder: (context, _) => Offstage( offstage: selected, child: RunsList( + active: !selected, controller: controller, onSelected: _select, syncToken: widget.syncToken, diff --git a/app/lib/features/runs/ui/runs_filters.dart b/app/lib/features/runs/ui/runs_filters.dart index a3f333e3..36eebedb 100644 --- a/app/lib/features/runs/ui/runs_filters.dart +++ b/app/lib/features/runs/ui/runs_filters.dart @@ -20,264 +20,24 @@ class RunsFilters extends StatelessWidget { @override Widget build(BuildContext context) { final count = controller.activeFilterCount; + // Filter and sort live in the app bar; this row keeps the Needs-you + // control and the applied filters, each clearable. return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - SingleChildScrollView( - scrollDirection: Axis.horizontal, - padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), - child: usesCupertinoHost(context) - ? _cupertinoToolbar(context, count) - : _materialToolbar(count), - ), + if (action case final action?) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: action, + ), + ), if (count > 0) _appliedFilters(context), ], ); } - Widget _materialToolbar(int count) => Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (action case final action?) ...[action, const SizedBox(width: 4)], - PopupMenuButton<_FilterChoice>( - tooltip: count > 0 - ? '$count active ${count == 1 ? 'filter' : 'filters'}' - : 'Filter runs', - onSelected: _apply, - itemBuilder: (context) => _materialMenuItems(), - child: _materialButton( - count > 0 ? Icons.filter_alt : Icons.filter_alt_outlined, - count > 0 ? 'Filter ($count)' : 'Filter', - ), - ), - PopupMenuButton( - tooltip: 'Sort runs', - onSelected: controller.setSort, - itemBuilder: (context) => [ - for (final sort in _sorts) - CheckedPopupMenuItem( - value: sort.$1, - checked: controller.sort == sort.$1, - child: Text(sort.$2), - ), - const PopupMenuDivider(), - const PopupMenuItem(value: 'newest_first', child: Text('Reset')), - ], - child: _materialButton( - Icons.sort, - 'Sort: ${_sortLabel(controller.sort)}', - ), - ), - ], - ); - - Widget _materialButton(IconData icon, String label) => Semantics( - button: true, - child: Padding( - padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 8), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [Icon(icon), const SizedBox(width: 6), Text(label)], - ), - ), - ); - - List> _materialMenuItems() => [ - const PopupMenuItem(enabled: false, child: Text('Status')), - for (final status in runStates) - CheckedPopupMenuItem( - value: (kind: 'status', value: status), - checked: controller.statuses.contains(status), - child: Text(status), - ), - const PopupMenuDivider(), - const PopupMenuItem(enabled: false, child: Text('Pipeline')), - CheckedPopupMenuItem( - value: (kind: 'pipeline', value: ''), - checked: controller.pipelineId == null, - child: const Text('Any pipeline'), - ), - for (final pipeline in _pipelines(controller)) - CheckedPopupMenuItem( - value: (kind: 'pipeline', value: '${pipeline.id}'), - checked: controller.pipelineId == pipeline.id, - child: Text(pipeline.name), - ), - const PopupMenuDivider(), - const PopupMenuItem(enabled: false, child: Text('Time range')), - for (final range in _timeRanges) - CheckedPopupMenuItem( - value: (kind: 'time', value: range.$1), - checked: controller.timeRange == range.$1, - child: Text(range.$2), - ), - const PopupMenuDivider(), - const PopupMenuItem(enabled: false, child: Text('Trigger')), - for (final schedule in _schedules) - CheckedPopupMenuItem( - value: (kind: 'schedule', value: schedule.$1), - checked: controller.scheduled == schedule.$1, - child: Text(schedule.$2), - ), - if (controller.activeFilterCount > 0) ...[ - const PopupMenuDivider(), - const PopupMenuItem( - value: (kind: 'clear', value: ''), - child: Text('Clear filters'), - ), - ], - if (_hasUnclassifiedRuns(controller)) ...[ - const PopupMenuDivider(), - const PopupMenuItem( - enabled: false, - child: Text( - 'Some records have no scheduling provenance; they stay unclassified.', - ), - ), - ], - ]; - - void _apply(_FilterChoice choice) { - if (choice.kind == 'status') { - controller.setStatus(choice.value); - } else if (choice.kind == 'schedule') { - controller.setScheduled(choice.value); - } else if (choice.kind == 'pipeline') { - controller.setPipeline( - choice.value.isEmpty ? null : int.tryParse(choice.value), - ); - } else if (choice.kind == 'time') { - controller.setTimeRange(choice.value); - } else { - controller.clearFilters(); - } - } - - Widget _cupertinoToolbar(BuildContext context, int count) => Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (action case final action?) ...[action, const SizedBox(width: 4)], - CupertinoButton( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - minimumSize: Size.zero, - onPressed: () => _showCupertinoFilter(context), - child: Text(count > 0 ? 'Filter ($count)' : 'Filter'), - ), - const SizedBox(width: 4), - CupertinoButton( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - minimumSize: Size.zero, - onPressed: () => _choose( - context, - 'Sort runs', - _sortChoices, - controller.sort, - controller.setSort, - ), - child: Text('Sort: ${_sortLabel(controller.sort)}'), - ), - ], - ); - - /// One sheet for both facets, mirroring the browser's filter menu. Tapping an - /// option keeps the sheet open so several statuses can be toggled; the check - /// marks redraw from the controller and `Done` dismisses it. - Future _showCupertinoFilter( - BuildContext context, - ) => showCupertinoModalPopup( - context: context, - builder: (sheetContext) => ListenableBuilder( - listenable: controller, - builder: (context, _) => CupertinoActionSheet( - title: const Text('Filter runs'), - actions: [ - _cupertinoSection('Status'), - for (final status in runStates) - CupertinoActionSheetAction( - onPressed: () => controller.setStatus(status), - child: Text( - '${controller.statuses.contains(status) ? '✓ ' : ''}$status', - ), - ), - _cupertinoSection('Pipeline'), - CupertinoActionSheetAction( - onPressed: () => controller.setPipeline(null), - child: Text( - '${controller.pipelineId == null ? '✓ ' : ''}Any pipeline', - ), - ), - for (final pipeline in _pipelines(controller)) - CupertinoActionSheetAction( - onPressed: () => controller.setPipeline(pipeline.id), - child: Text( - '${controller.pipelineId == pipeline.id ? '✓ ' : ''}${pipeline.name}', - ), - ), - _cupertinoSection('Time range'), - for (final range in _timeRanges) - CupertinoActionSheetAction( - onPressed: () => controller.setTimeRange(range.$1), - child: Text( - '${controller.timeRange == range.$1 ? '✓ ' : ''}${range.$2}', - ), - ), - _cupertinoSection('Trigger'), - for (final schedule in _schedules) - CupertinoActionSheetAction( - onPressed: () => controller.setScheduled(schedule.$1), - child: Text( - '${controller.scheduled == schedule.$1 ? '✓ ' : ''}' - '${schedule.$2}', - ), - ), - if (_hasUnclassifiedRuns(controller)) - CupertinoActionSheetAction( - onPressed: () {}, - child: const Text( - 'Some records have no scheduling provenance; they stay unclassified.', - ), - ), - if (controller.activeFilterCount > 0) - CupertinoActionSheetAction( - onPressed: controller.clearFilters, - child: const Text('Clear filters'), - ), - ], - cancelButton: CupertinoActionSheetAction( - onPressed: () => Navigator.pop(context), - child: const Text('Done'), - ), - ), - ), - ); - - Future _choose( - BuildContext context, - String title, - List<(String, String)> values, - String selected, - ValueChanged onSelected, - ) async { - final value = await showCupertinoModalPopup( - context: context, - builder: (context) => CupertinoActionSheet( - title: Text(title), - actions: [ - for (final option in values) - CupertinoActionSheetAction( - onPressed: () => Navigator.pop(context, option.$1), - child: Text(option.$2), - ), - ], - cancelButton: CupertinoActionSheetAction( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel'), - ), - ), - ); - if (value != null && value != selected) onSelected(value); - } - Widget _appliedFilters(BuildContext context) { final applied = _applied(); return Semantics( @@ -367,8 +127,6 @@ class RunsFilters extends StatelessWidget { } } -typedef _FilterChoice = ({String kind, String value}); - const _sorts = [ ('newest_first', 'Newest first'), ('oldest_first', 'Oldest first'), @@ -377,7 +135,6 @@ const _sorts = [ ('pipeline_name', 'Pipeline name'), ('status', 'Status'), ]; -const _sortChoices = [..._sorts, ('newest_first', 'Reset')]; const _schedules = [ ('any', 'Any trigger'), ('scheduled', 'Scheduled runs'), @@ -416,11 +173,6 @@ bool _hasUnclassifiedRuns(RunsController controller) => return run['scheduled'] is! bool && !(id is num && id > 0); }); -Widget _cupertinoSection(String title) => Padding( - padding: const EdgeInsetsDirectional.only(top: 8), - child: Text(title, style: const TextStyle(fontWeight: FontWeight.bold)), -); - String _timeRangeLabel(String value) => _timeRanges .firstWhere((entry) => entry.$1 == value, orElse: () => _timeRanges.first) .$2; @@ -429,3 +181,294 @@ String _sortLabel(String value) => String _scheduleLabel(String value) => _schedules .firstWhere((e) => e.$1 == value, orElse: () => _schedules.first) .$2; + +/// The Runs list's app-bar actions: usage and charts, filter (with the search +/// field inside) and sort, as icons. +class RunsBarActions { + const RunsBarActions(this.controller); + + final RunsController controller; + + List build(BuildContext context, {required VoidCallback onStats}) { + final cupertino = usesCupertinoHost(context); + final count = + controller.activeFilterCount + (controller.query.isEmpty ? 0 : 1); + final filterLabel = count > 0 + ? '$count active ${count == 1 ? 'filter' : 'filters'}' + : 'Filter runs'; + Widget icon( + Key key, + IconData material, + IconData ios, + String label, + VoidCallback onPressed, { + bool active = false, + }) { + if (cupertino) { + return Semantics( + button: true, + label: label, + excludeSemantics: true, + child: CupertinoButton( + key: key, + padding: const EdgeInsets.symmetric(horizontal: 6), + minimumSize: Size.zero, + onPressed: onPressed, + child: Icon(ios), + ), + ); + } + return IconButton( + key: key, + tooltip: label, + isSelected: active, + onPressed: onPressed, + icon: Icon(material), + ); + } + + return [ + icon( + const ValueKey('runs.stats'), + Icons.insert_chart_outlined, + CupertinoIcons.chart_pie, + 'Usage and charts', + onStats, + ), + icon( + const ValueKey('runs.filter'), + count > 0 ? Icons.filter_alt : Icons.filter_alt_outlined, + count > 0 + ? CupertinoIcons.line_horizontal_3_decrease_circle_fill + : CupertinoIcons.line_horizontal_3_decrease_circle, + filterLabel, + () => showRunsFilterSheet(context, controller), + active: count > 0, + ), + icon( + const ValueKey('runs.sort'), + Icons.sort, + CupertinoIcons.arrow_up_arrow_down, + 'Sort runs: ${_sortLabel(controller.sort)}', + () => _chooseSort(context), + ), + ]; + } + + Future _chooseSort(BuildContext context) async { + final cupertino = usesCupertinoHost(context); + String? value; + if (cupertino) { + value = await showCupertinoModalPopup( + context: context, + builder: (sheet) => CupertinoActionSheet( + title: const Text('Sort runs'), + actions: [ + for (final option in _sorts) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheet, option.$1), + child: Text( + '${controller.sort == option.$1 ? '✓ ' : ''}${option.$2}', + ), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheet), + child: const Text('Cancel'), + ), + ), + ); + } else { + value = await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (sheet) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + const ListTile(title: Text('Sort runs')), + for (final option in _sorts) + ListTile( + title: Text(option.$2), + trailing: controller.sort == option.$1 + ? const Icon(Icons.check) + : null, + onTap: () => Navigator.pop(sheet, option.$1), + ), + ], + ), + ), + ); + } + if (value != null && value != controller.sort) controller.setSort(value); + } +} + +/// The filter sheet: the text filter first, then status, pipeline, time range +/// and trigger, each choice applied as it is picked. +Future showRunsFilterSheet( + BuildContext context, + RunsController controller, +) { + final cupertino = usesCupertinoHost(context); + final sheet = _RunsFilterSheet(controller: controller, cupertino: cupertino); + if (cupertino) { + return showCupertinoModalPopup( + context: context, + builder: (_) => CupertinoPopupSurface(child: SafeArea(child: sheet)), + ); + } + return showModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + useSafeArea: true, + builder: (_) => sheet, + ); +} + +class _RunsFilterSheet extends StatefulWidget { + const _RunsFilterSheet({required this.controller, required this.cupertino}); + + final RunsController controller; + final bool cupertino; + + @override + State<_RunsFilterSheet> createState() => _RunsFilterSheetState(); +} + +class _RunsFilterSheetState extends State<_RunsFilterSheet> { + late final TextEditingController _text = TextEditingController( + text: widget.controller.query, + ); + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + Widget _section(String title) => Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 4), + child: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)), + ); + + Widget _choice(String label, bool checked, VoidCallback onTap) { + if (widget.cupertino) { + return CupertinoListTile( + title: Text(label), + trailing: checked ? const Icon(CupertinoIcons.check_mark) : null, + onTap: onTap, + ); + } + return CheckboxListTile( + dense: true, + title: Text(label), + value: checked, + onChanged: (_) => onTap(), + ); + } + + @override + Widget build(BuildContext context) { + final controller = widget.controller; + final field = widget.cupertino + ? CupertinoSearchTextField( + key: const ValueKey('runs.filter.query'), + controller: _text, + placeholder: 'Filter runs', + onChanged: controller.setQuery, + ) + : TextField( + key: const ValueKey('runs.filter.query'), + controller: _text, + decoration: const InputDecoration( + hintText: 'Filter runs', + prefixIcon: Icon(Icons.search), + isDense: true, + ), + onChanged: controller.setQuery, + ); + return ListenableBuilder( + listenable: controller, + builder: (context, _) => ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.85, + ), + child: ListView( + key: const ValueKey('runs.filter.sheet'), + shrinkWrap: true, + padding: const EdgeInsets.only(bottom: 16), + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: field, + ), + _section('Status'), + for (final status in runStates) + _choice( + status, + controller.statuses.contains(status), + () => controller.setStatus(status), + ), + _section('Pipeline'), + _choice( + 'Any pipeline', + controller.pipelineId == null, + () => controller.setPipeline(null), + ), + for (final pipeline in _pipelines(controller)) + _choice( + pipeline.name, + controller.pipelineId == pipeline.id, + () => controller.setPipeline(pipeline.id), + ), + _section('Time range'), + for (final range in _timeRanges) + _choice( + range.$2, + controller.timeRange == range.$1, + () => controller.setTimeRange(range.$1), + ), + _section('Trigger'), + for (final schedule in _schedules) + _choice( + schedule.$2, + controller.scheduled == schedule.$1, + () => controller.setScheduled(schedule.$1), + ), + if (_hasUnclassifiedRuns(controller)) + const Padding( + padding: EdgeInsets.fromLTRB(16, 4, 16, 0), + child: Text( + 'Some records have no scheduling provenance; they stay ' + 'unclassified.', + ), + ), + if (controller.activeFilterCount > 0 || controller.query.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), + child: widget.cupertino + ? CupertinoButton( + onPressed: () { + _text.clear(); + controller.setQuery(''); + controller.clearFilters(); + }, + child: const Text('Clear filters'), + ) + : TextButton( + onPressed: () { + _text.clear(); + controller.setQuery(''); + controller.clearFilters(); + }, + child: const Text('Clear filters'), + ), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index e237d118..811039ea 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -9,7 +9,9 @@ import '../../attention/runtime/attention_controller.dart'; import '../../attention/runtime/attention_store.dart'; import '../../attention/ui/needs_you_runs_heading.dart'; import '../domain/run_models.dart'; +import '../../../shell/shell_bar.dart'; import 'runs_controller.dart'; +import 'runs_stats_page.dart'; import 'runs_filters.dart'; class RunsList extends StatelessWidget { @@ -22,8 +24,12 @@ class RunsList extends StatelessWidget { this.attentionNow, this.notifications, this.attention, + this.active = true, }); + /// False while a run detail covers the list; the bar is then the run's. + final bool active; + final RunsController controller; final ValueChanged onSelected; @@ -45,6 +51,29 @@ class RunsList extends StatelessWidget { @override Widget build(BuildContext context) { + final actions = RunsBarActions( + controller, + ).build(context, onStats: () => openRunsStats(context, controller)); + // Outside the app shell (the list on its own) the actions head the list. + if (!ShellBar.available(context)) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(8, 4, 8, 0), + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + children: actions, + ), + ), + Expanded(child: _list(context)), + ], + ); + } + return ShellBar(active: active, actions: actions, child: _list(context)); + } + + Widget _list(BuildContext context) { if (controller.loading && controller.runs.isEmpty) { return Center( child: usesCupertinoHost(context) @@ -58,24 +87,7 @@ class RunsList extends StatelessWidget { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - _heading(context), if (controller.error != null) _inlineError(context), - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), - child: usesCupertinoHost(context) - ? CupertinoSearchTextField( - placeholder: 'Filter runs', - onChanged: controller.setQuery, - ) - : TextField( - decoration: const InputDecoration( - hintText: 'Filter runs', - isDense: true, - prefixIcon: Icon(Icons.search), - ), - onChanged: controller.setQuery, - ), - ), RunsFilters( controller: controller, action: NeedsYouRunsHeading( @@ -98,19 +110,6 @@ class RunsList extends StatelessWidget { ); } - Widget _heading(BuildContext context) { - final usage = controller.usage; - if (usage == null) return const SizedBox.shrink(); - return Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), - child: Text( - 'Usage: $usage', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ); - } - Widget _groupedRuns(BuildContext context) { final groups = groupRunsByDay(controller.visibleRuns, DateTime.now()); final entries = <({String? label, JsonMap? run})>[]; diff --git a/app/lib/features/runs/ui/runs_stats_page.dart b/app/lib/features/runs/ui/runs_stats_page.dart new file mode 100644 index 00000000..a57ec6fe --- /dev/null +++ b/app/lib/features/runs/ui/runs_stats_page.dart @@ -0,0 +1,230 @@ +import 'dart:math' as math; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../../../ui/status/run_status_icon.dart'; +import '../domain/run_models.dart'; +import '../../pipelines/pipeline_format.dart' show parseInstant; +import 'run_detail_content.dart'; +import 'runs_controller.dart'; + +/// Opens the runs' usage and charts on their own page. +Future openRunsStats(BuildContext context, RunsController controller) { + final page = RunsStatsPage(controller: controller); + return Navigator.of(context).push( + usesCupertinoHost(context) + ? CupertinoPageRoute(builder: (_) => page) + : MaterialPageRoute(builder: (_) => page), + ); +} + +/// Usage totals, runs by status (a pie) and runs per day for the last week. +class RunsStatsPage extends StatelessWidget { + const RunsStatsPage({super.key, required this.controller, this.now}); + + final RunsController controller; + final DateTime Function()? now; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final body = ListenableBuilder( + listenable: controller, + builder: (context, _) => _body(context, cupertino), + ); + if (cupertino) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Usage')), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Usage')), + body: SafeArea(top: false, child: body), + ); + } + + Widget _body(BuildContext context, bool cupertino) { + final runs = controller.runs; + final metrics = detailUsageMetrics(controller.usage); + final byState = {}; + for (final run in runs) { + final state = runStateOf(run['status']); + byState[state] = (byState[state] ?? 0) + 1; + } + final today = now?.call() ?? DateTime.now(); + final days = runsPerDay(runs, today); + final heading = TextStyle( + fontWeight: FontWeight.w600, + fontSize: 17, + color: cupertino ? CupertinoColors.label.resolveFrom(context) : null, + ); + final secondary = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + return ListView( + key: const ValueKey('runs.stats.page'), + padding: const EdgeInsets.all(16), + children: [ + Text('Usage', style: heading), + const SizedBox(height: 8), + if (metrics.isEmpty) + Text('No usage reported.', style: TextStyle(color: secondary)) + else + Wrap( + spacing: 24, + runSpacing: 12, + children: [ + for (final metric in metrics) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(metric.label, style: TextStyle(color: secondary)), + Text(metric.value, style: heading), + ], + ), + ], + ), + const SizedBox(height: 24), + Text('Runs by status', style: heading), + const SizedBox(height: 12), + if (runs.isEmpty) + Text('No runs loaded.', style: TextStyle(color: secondary)) + else + Row( + children: [ + SizedBox.square( + dimension: 140, + child: CustomPaint( + key: const ValueKey('runs.stats.pie'), + painter: _PiePainter([ + for (final entry in byState.entries) + ( + runStatusColor(entry.key).resolveFrom(context), + entry.value, + ), + ]), + ), + ), + const SizedBox(width: 20), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final entry in byState.entries) + Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + children: [ + RunStatusIcon( + state: entry.key, + label: entry.key, + size: 16, + ), + const SizedBox(width: 8), + Expanded(child: Text(entry.key)), + Text('${entry.value}'), + ], + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 24), + Text('Runs in the last 7 days', style: heading), + const SizedBox(height: 12), + SizedBox( + height: 140, + child: Row( + key: const ValueKey('runs.stats.days'), + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + for (final day in days) + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Text( + '${day.count}', + style: TextStyle(color: secondary), + ), + const SizedBox(height: 2), + Flexible( + child: FractionallySizedBox( + heightFactor: day.count == 0 + ? 0.02 + : day.count / + days.map((d) => d.count).reduce(math.max), + child: DecoratedBox( + decoration: BoxDecoration( + color: cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary, + borderRadius: BorderRadius.circular(4), + ), + ), + ), + ), + const SizedBox(height: 4), + Text(day.label, style: TextStyle(color: secondary)), + ], + ), + ), + ), + ], + ), + ), + ], + ); + } +} + +/// Runs started on each of the last seven local days, oldest first. +List<({String label, int count})> runsPerDay(List runs, DateTime now) { + const names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; + final today = DateTime(now.year, now.month, now.day); + final counts = List.filled(7, 0); + for (final run in runs) { + final started = parseInstant('${run['created_at'] ?? ''}')?.toLocal(); + if (started == null) continue; + final day = DateTime(started.year, started.month, started.day); + final ago = today.difference(day).inDays; + if (ago >= 0 && ago < 7) counts[6 - ago]++; + } + return [ + for (var i = 0; i < 7; i++) + ( + label: names[today.subtract(Duration(days: 6 - i)).weekday - 1], + count: counts[i], + ), + ]; +} + +class _PiePainter extends CustomPainter { + _PiePainter(this.slices); + + final List<(Color, int)> slices; + + @override + void paint(Canvas canvas, Size size) { + final total = slices.fold(0, (sum, slice) => sum + slice.$2); + if (total == 0) return; + final rect = Offset.zero & size; + var start = -math.pi / 2; + for (final (color, value) in slices) { + final sweep = value / total * 2 * math.pi; + canvas.drawArc(rect, start, sweep, true, Paint()..color = color); + start += sweep; + } + } + + @override + bool shouldRepaint(_PiePainter oldDelegate) => true; +} diff --git a/app/lib/shell/shell_bar.dart b/app/lib/shell/shell_bar.dart index 9070cc1c..74185cb4 100644 --- a/app/lib/shell/shell_bar.dart +++ b/app/lib/shell/shell_bar.dart @@ -69,9 +69,14 @@ class ShellBar extends StatefulWidget { this.title, this.onBack, this.actions = const [], + this.active = true, required this.child, }); + /// False while the screen is kept mounted but hidden (a list under an open + /// detail): it then gives the bar up. + final bool active; + final String? title; final VoidCallback? onBack; final List actions; @@ -99,6 +104,12 @@ class _ShellBarState extends State { void _publish() { final scope = _scope; if (scope == null) return; + if (!widget.active) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) scope.registry._clear(scope.destination, _owner); + }); + return; + } final spec = ShellBarSpec( title: widget.title, onBack: widget.onBack, diff --git a/app/test/features/runs/ui/runs_list_widget_test.dart b/app/test/features/runs/ui/runs_list_widget_test.dart index d2c5b9cc..8b73b944 100644 --- a/app/test/features/runs/ui/runs_list_widget_test.dart +++ b/app/test/features/runs/ui/runs_list_widget_test.dart @@ -77,36 +77,18 @@ void main() { onSelected: (id) => selectedRun = id, ); - expect(find.byType(CupertinoSearchTextField), findsOneWidget); + // The text filter lives in the filter sheet. + expect(find.byType(CupertinoSearchTextField), findsNothing); expect(find.text('Alpha'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('runs.filter'))); + await tester.pumpAndSettle(); await tester.enterText(find.byType(CupertinoSearchTextField), 'Beta'); await tester.pumpAndSettle(); - expect(find.text('Beta'), findsNWidgets(2)); + await tester.tapAt(const Offset(4, 4)); + await tester.pumpAndSettle(); expect(find.text('Alpha'), findsNothing); await tester.tap(find.byKey(const ValueKey('run-row-2'))); expect(selectedRun, 2); - await tester.enterText(find.byType(CupertinoSearchTextField), 'missing'); - await tester.pumpAndSettle(); - expect(find.text('No runs found.'), findsOneWidget); - await tester.enterText(find.byType(CupertinoSearchTextField), ''); - await tester.pumpAndSettle(); - await tester.tap(find.text('Filter')); - await tester.pumpAndSettle(); - final scheduled = find.widgetWithText( - CupertinoActionSheetAction, - 'Scheduled runs', - ); - await tester.ensureVisible(scheduled); - await tester.tap(scheduled); - await tester.pumpAndSettle(); - expect(controller.scheduled, 'scheduled'); - await tester.tap(find.text('Done')); - await tester.pumpAndSettle(); - expect(find.text('Scheduled runs'), findsOneWidget); - await tester.tap(find.text('Scheduled runs')); - await tester.pumpAndSettle(); - expect(controller.scheduled, 'any'); - expect(find.text('Scheduled runs'), findsNothing); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); @@ -143,6 +125,8 @@ void main() { }; await controller.load(); await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('runs.filter'))); + await tester.pumpAndSettle(); expect(find.byType(TextField), findsOneWidget); final layoutError = tester.takeException(); expect( @@ -193,7 +177,7 @@ void main() { ); for (final cupertino in [false, true]) { - testWidgets('the attention action shares the Filter toolbar row ' + testWidgets('the attention action heads the list under the actions ' '(${cupertino ? 'Cupertino' : 'Material'})', (tester) async { await mount(tester, cupertino: cupertino); await tester.pumpAndSettle(); @@ -202,13 +186,11 @@ void main() { matching: find.byType(NeedsYouRunsHeading), ); expect(bell, findsOneWidget); - final filter = find.descendant( - of: find.byType(RunsFilters), - matching: find.text('Filter'), - ); expect( - (tester.getCenter(bell).dy - tester.getCenter(filter).dy).abs(), - lessThan(1), + tester.getTopLeft(bell).dy, + greaterThanOrEqualTo( + tester.getBottomLeft(find.byKey(const ValueKey('runs.filter'))).dy, + ), ); expect(tester.takeException(), isNull); }); diff --git a/app/test/features/runs/ui/runs_toolbar_test.dart b/app/test/features/runs/ui/runs_toolbar_test.dart index 2d1df79e..f5a31d22 100644 --- a/app/test/features/runs/ui/runs_toolbar_test.dart +++ b/app/test/features/runs/ui/runs_toolbar_test.dart @@ -7,6 +7,7 @@ import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/runs/data/runs_repository.dart'; import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; import 'package:pipelines_app/features/runs/ui/runs_list.dart'; +import 'package:pipelines_app/features/runs/ui/runs_stats_page.dart'; class _Gateway implements ApiGateway { final framesController = StreamController.broadcast(); @@ -69,123 +70,126 @@ void main() { await tester.pumpAndSettle(); } + Future reveal(WidgetTester tester, Finder target) => + tester.scrollUntilVisible( + target, + 80, + // The sheet's own list, not the search field's inner scrollable. + scrollable: find + .descendant( + of: find.byKey(const ValueKey('runs.filter.sheet')), + matching: find.byType(Scrollable), + ) + .first, + ); + + Future closeSheet(WidgetTester tester) async { + await tester.tapAt(const Offset(4, 4)); + await tester.pumpAndSettle(); + } + testWidgets( - 'material toolbar is a compact menu row with removable applied chips', + 'material: filter and sort are icons; the filter sheet holds the search', (tester) async { await mount(tester, cupertino: false); - expect(find.byType(DropdownButton), findsNothing); - expect(find.byType(FilterChip), findsNothing); - expect(find.text('Filter'), findsOneWidget); - expect(find.text('Sort: Newest first'), findsOneWidget); + expect(find.byType(TextField), findsNothing); + expect(find.byKey(const ValueKey('runs.filter')), findsOneWidget); + expect(find.byKey(const ValueKey('runs.sort')), findsOneWidget); + expect(find.byKey(const ValueKey('runs.stats')), findsOneWidget); - await tester.tap(find.text('Filter')); + await tester.tap(find.byKey(const ValueKey('runs.filter'))); await tester.pumpAndSettle(); - expect(find.text('queued'), findsOneWidget); - expect(find.text('Pipeline'), findsOneWidget); - expect(find.text('Any pipeline'), findsOneWidget); - expect(find.text('Time range'), findsOneWidget); - expect(find.text('Last 7 days'), findsOneWidget); - expect(find.text('Any trigger'), findsOneWidget); + final sheet = find.byKey(const ValueKey('runs.filter.sheet')); expect( - find.text( - 'Some records have no scheduling provenance; they stay unclassified.', - ), + find.descendant(of: sheet, matching: find.byType(TextField)), findsOneWidget, ); - - final pipelineItem = find.ancestor( - of: find.text('Alpha'), - matching: find.byWidgetPredicate((widget) => widget is PopupMenuItem), + await tester.enterText( + find.byKey(const ValueKey('runs.filter.query')), + 'Beta', ); - await tester.ensureVisible(pipelineItem); - await tester.tap(pipelineItem); - await tester.pumpAndSettle(); + await tester.pump(); + expect(controller.query, 'Beta'); + + final alpha = find.descendant(of: sheet, matching: find.text('Alpha')); + await reveal(tester, alpha); + await tester.tap(alpha); + await tester.pump(); expect(controller.pipelineId, 9); - - await tester.tap(find.text('Filter (1)')); - await tester.pumpAndSettle(); - final timeItem = find.ancestor( - of: find.text('Last 7 days'), - matching: find.byWidgetPredicate((widget) => widget is PopupMenuItem), + final week = find.descendant( + of: sheet, + matching: find.text('Last 7 days'), ); - await tester.ensureVisible(timeItem); - await tester.tap(timeItem); - await tester.pumpAndSettle(); + await reveal(tester, week); + await tester.tap(week); + await tester.pump(); expect(controller.timeRange, 'last_7_days'); - expect(find.text('Filter (2)'), findsOneWidget); + await closeSheet(tester); + + // Applied filters stay visible and clearable under the bar. expect(find.byTooltip('Clear filter: Last 7 days'), findsOneWidget); + await tester.tap(find.byTooltip('Clear filter: Last 7 days')); + await tester.pumpAndSettle(); + expect(controller.timeRange, 'any_time'); - await tester.tap(find.text('Filter (2)')); + await tester.tap(find.byKey(const ValueKey('runs.sort'))); await tester.pumpAndSettle(); - final failedItem = find.ancestor( - of: find.text('failed'), - matching: find.byWidgetPredicate((widget) => widget is PopupMenuItem), - ); - await tester.tap(failedItem); + await tester.tap(find.text('Oldest first')); await tester.pumpAndSettle(); - expect(controller.statuses, {'failed'}); - expect(find.text('Filter (3)'), findsOneWidget); - expect(find.byType(InputChip), findsNWidgets(3)); - expect(find.text('failed'), findsWidgets); - expect(controller.visibleRuns, isEmpty); - - await tester.tap(find.textContaining('Sort:')); - await tester.pumpAndSettle(); - final statusItem = find.ancestor( - of: find.text('Status'), - matching: find.byWidgetPredicate((widget) => widget is PopupMenuItem), - ); - await tester.tap(statusItem); - await tester.pumpAndSettle(); - expect(controller.sort, 'status'); - expect(find.text('Sort: Status'), findsOneWidget); - - await tester.tap(find.byTooltip('Clear filter: failed')); - await tester.pumpAndSettle(); - expect(controller.statuses, isEmpty); - controller.clearFilters(); - await tester.pumpAndSettle(); - expect(find.byType(InputChip), findsNothing); - expect(find.text('Filter'), findsOneWidget); - expect(find.text('Alpha'), findsOneWidget); + expect(controller.sort, 'oldest_first'); }, variant: TargetPlatformVariant.only(TargetPlatform.android), ); testWidgets( - 'cupertino toolbar filters from one sheet and its chip clears the facet', + 'cupertino: the filter sheet filters and its chip clears the facet', (tester) async { await mount(tester, cupertino: true); - expect(find.text('Filter'), findsOneWidget); - expect(find.text('Sort: Newest first'), findsOneWidget); - - await tester.tap(find.text('Filter')); + await tester.tap(find.byKey(const ValueKey('runs.filter'))); await tester.pumpAndSettle(); - final failedAction = find.widgetWithText( - CupertinoActionSheetAction, - 'failed', - ); - await tester.ensureVisible(failedAction); - await tester.tap(failedAction); + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + final failed = find.widgetWithText(CupertinoListTile, 'failed'); + await reveal(tester, failed); + await tester.pumpAndSettle(); + await tester.tap(failed); await tester.pumpAndSettle(); expect(controller.statuses, {'failed'}); - expect(find.text('✓ failed'), findsOneWidget); - expect(find.text('Pipeline'), findsOneWidget); - expect(find.text('Last 7 days'), findsOneWidget); - expect(find.text('Filter (1)'), findsOneWidget); + await closeSheet(tester); - await tester.tap(find.text('Done')); - await tester.pumpAndSettle(); final failedChip = find.widgetWithText(CupertinoButton, 'failed'); expect(failedChip, findsOneWidget); expect(find.text('Alpha'), findsNothing); - await tester.tap(failedChip); await tester.pumpAndSettle(); expect(controller.statuses, isEmpty); - expect(find.text('Filter'), findsOneWidget); expect(find.text('Alpha'), findsOneWidget); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); + + testWidgets('the stats page shows usage, status pie and runs per day', ( + tester, + ) async { + await mount(tester, cupertino: false); + await tester.tap(find.byKey(const ValueKey('runs.stats'))); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('runs.stats.page')), findsOneWidget); + expect(find.byKey(const ValueKey('runs.stats.pie')), findsOneWidget); + expect(find.byKey(const ValueKey('runs.stats.days')), findsOneWidget); + expect(find.text('Runs by status'), findsOneWidget); + }); + + test('runs per day counts the last seven local days', () { + final now = DateTime(2026, 10, 23, 12); + final days = runsPerDay([ + {'created_at': DateTime(2026, 10, 23, 9).toUtc().toIso8601String()}, + {'created_at': DateTime(2026, 10, 23, 10).toUtc().toIso8601String()}, + {'created_at': DateTime(2026, 10, 20, 9).toUtc().toIso8601String()}, + {'created_at': DateTime(2026, 10, 1, 9).toUtc().toIso8601String()}, + ], now); + expect(days, hasLength(7)); + expect(days.last.count, 2); + expect(days[3].count, 1); + expect(days.fold(0, (sum, day) => sum + day.count), 3); + }); }