Files
pipelines/app/lib/features/runs/ui/runs_stats_page.dart
T
alan e43cc867f9 Sheets, decision options, usage, settings and artifact errors: review r2 batches H and L
Shared AppSheetHeader (title + Done) for the Runs filter/sort and Needs you
sheets; Runs filter single-choice groups as check rows and statuses in
sentence case; Cupertino decision options as a check list; run action sheet
titled with the run; usage page without the duplicate title and with honest
empty states; Settings Reconnect wording, compact notifications row and a
tinted Cupertino Save workspace; friendly artifact preview failures with
Retry.
2026-10-31 12:13:34 +00:00

291 lines
9.9 KiB
Dart

import '../../../ui/adaptive/segmented_bar.dart';
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/floating_bar_layout.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, runStateLabel;
import 'run_detail_content.dart';
import 'runs_controller.dart';
/// Opens the runs' usage and charts on their own page.
Future<void> openRunsStats(BuildContext context, RunsController controller) {
final page = RunsStatsPage(controller: controller);
return Navigator.of(context).push<void>(
usesCupertinoHost(context)
? CupertinoPageRoute<void>(builder: (_) => page)
: MaterialPageRoute<void>(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 SegmentedBar(cupertino: true, title: 'Usage'),
child: SafeArea(top: false, bottom: false, child: body),
);
}
return Scaffold(
extendBodyBehindAppBar: true,
appBar: const SegmentedBar(cupertino: false, title: 'Usage'),
body: SafeArea(top: false, bottom: false, child: body),
);
}
Widget _body(BuildContext context, bool cupertino) {
final runs = controller.runs;
final metrics = detailUsageMetrics(controller.usage);
final byState = <String, int>{};
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: withBarClearance(context, const EdgeInsets.all(16)),
children: [
// The bar already says Usage: the totals lead the page untitled.
if (metrics.isEmpty)
Text(
'No usage has been reported for these runs.',
key: const ValueKey('runs.stats.usage.empty'),
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: runStateLabel(entry.key),
size: 16,
),
const SizedBox(width: 8),
Expanded(child: Text(runStateLabel(entry.key))),
Text('${entry.value}'),
],
),
),
],
),
),
],
),
const SizedBox(height: 24),
Text('Runs in the last 7 days', style: heading),
const SizedBox(height: 12),
if (days.every((day) => day.count == 0))
Text(
'No runs started in the last 7 days.',
key: const ValueKey('runs.stats.days.empty'),
style: TextStyle(color: secondary),
)
else
_DaysChart(days: days, cupertino: cupertino, secondary: secondary),
],
);
}
}
/// Runs started on each of the last seven local days, oldest first.
List<({String label, int count})> runsPerDay(List<JsonMap> runs, DateTime now) {
const names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
final today = DateTime(now.year, now.month, now.day);
final counts = List<int>.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<int>(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;
}
/// Runs per day as bars over a baseline axis, each bar labelled with its
/// count and its weekday underneath. Only drawn when some day has a run.
class _DaysChart extends StatelessWidget {
const _DaysChart({
required this.days,
required this.cupertino,
required this.secondary,
});
final List<({String label, int count})> days;
final bool cupertino;
final Color secondary;
@override
Widget build(BuildContext context) {
final most = days.map((d) => d.count).reduce(math.max);
final bar = cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary;
final axis = cupertino
? CupertinoColors.separator.resolveFrom(context)
: Theme.of(context).colorScheme.outlineVariant;
return Column(
key: const ValueKey('runs.stats.days'),
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DecoratedBox(
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: axis)),
),
child: SizedBox(
height: 140,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
for (final day in days)
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
if (day.count > 0) ...[
Text(
'${day.count}',
style: TextStyle(color: secondary),
),
const SizedBox(height: 2),
Flexible(
child: FractionallySizedBox(
heightFactor: day.count / most,
child: DecoratedBox(
decoration: BoxDecoration(
color: bar,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(4),
),
),
child: const SizedBox.expand(),
),
),
),
],
],
),
),
),
],
),
),
),
const SizedBox(height: 4),
Row(
children: [
for (final day in days)
Expanded(
child: Text(
day.label,
textAlign: TextAlign.center,
style: TextStyle(color: secondary),
),
),
],
),
],
);
}
}