Files
SDKmuta/lib/widgets/progress_chart.dart
T
2026-10-31 15:27:32 +01:00

243 lines
8.2 KiB
Dart

import 'dart:math';
import 'package:flutter/material.dart';
enum ChartAxis { left, right, none }
/// One line on the chart. Each series has its own scale, so values of very
/// different size (average per shot vs. session total) can share the chart.
/// [axis] says which side labels its scale.
class ChartSeries {
final String name;
final Color color;
final List<double> values; // one per label
final int decimals;
final ChartAxis axis;
const ChartSeries(this.name, this.color, this.values,
{this.decimals = 2, this.axis = ChartAxis.none});
String format(double v) => v.toStringAsFixed(decimals);
}
/// Line chart: 2px lines, 8px points, three faint gridlines, up to one labelled
/// axis per side. Tap (or drag) to show every series' value at the nearest point.
class ProgressChart extends StatefulWidget {
final List<String> labels; // shown in the tooltip and under the first/last point
final List<ChartSeries> series; // legend and tooltip order
final Color textColor;
final Color gridColor;
const ProgressChart({
super.key,
required this.labels,
required this.series,
required this.textColor,
required this.gridColor,
});
@override
State<ProgressChart> createState() => _ProgressChartState();
}
class _ProgressChartState extends State<ProgressChart> {
int? _selected;
void _select(Offset position, Size size) {
final n = widget.labels.length;
if (n == 0) return;
final plot = _ChartPainter.plotRect(size);
final x = (position.dx - plot.left) / plot.width;
setState(() => _selected = (x * (n - 1)).round().clamp(0, n - 1));
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
LayoutBuilder(
builder: (context, constraints) {
final size = Size(constraints.maxWidth, 190);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (d) => _select(d.localPosition, size),
onHorizontalDragUpdate: (d) => _select(d.localPosition, size),
child: CustomPaint(
size: size,
painter: _ChartPainter(
labels: widget.labels,
series: widget.series,
textColor: widget.textColor,
gridColor: widget.gridColor,
selected: _selected,
),
),
);
},
),
const SizedBox(height: 8),
// Legend, centred under the graph
Wrap(
alignment: WrapAlignment.center,
spacing: 16,
runSpacing: 4,
children: [
for (final s in widget.series)
Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 14,
height: 3,
decoration: BoxDecoration(color: s.color, borderRadius: BorderRadius.circular(2)),
),
const SizedBox(width: 6),
Text(s.name, style: TextStyle(fontSize: 12, color: widget.textColor)),
],
),
],
),
],
);
}
}
class _ChartPainter extends CustomPainter {
static const double axis = 34; // room for y labels on each side
static const double pad = 10; // keeps end points inside the plot
static const double top = 34; // room for the tooltip
static const double bottom = 20; // room for x labels
static Rect plotRect(Size size) =>
Rect.fromLTRB(axis + pad, top, size.width - axis - pad, size.height - bottom);
final List<String> labels;
final List<ChartSeries> series;
final Color textColor;
final Color gridColor;
final int? selected;
_ChartPainter({
required this.labels,
required this.series,
required this.textColor,
required this.gridColor,
required this.selected,
});
// Min and max of a series, widened so a flat line sits in the middle
static (double, double) _range(List<double> values, double minSpan) {
var lo = values.reduce(min);
var hi = values.reduce(max);
if (hi - lo < minSpan) {
final mid = (hi + lo) / 2;
lo = mid - minSpan / 2;
hi = mid + minSpan / 2;
}
return (lo, hi);
}
@override
void paint(Canvas canvas, Size size) {
if (labels.isEmpty || series.isEmpty) return;
final plot = plotRect(size);
final n = labels.length;
final ranges = [
for (final s in series) _range(s.values, s.values.reduce(max).abs() * 0.1 + 0.2),
];
double xAt(int i) => n == 1 ? plot.center.dx : plot.left + plot.width * i / (n - 1);
double yAt(double v, (double, double) r) => plot.bottom - plot.height * (v - r.$1) / (r.$2 - r.$1);
// Gridlines + y labels in each axis series' colour
final grid = Paint()
..color = gridColor
..strokeWidth = 1;
for (final f in [0.0, 0.5, 1.0]) {
final y = plot.bottom - plot.height * f;
canvas.drawLine(Offset(axis, y), Offset(size.width - axis, y), grid);
for (int k = 0; k < series.length; k++) {
if (series[k].axis == ChartAxis.none) continue;
final right = series[k].axis == ChartAxis.right;
final r = ranges[k];
final v = r.$1 + (r.$2 - r.$1) * f;
final text = series[k].decimals == 0 ? v.round().toString() : v.toStringAsFixed(1);
_text(canvas, text, Offset(right ? size.width : 0, y - 7), 11, series[k].color, alignRight: right);
}
}
// x labels: first and last only
_text(canvas, labels.first, Offset(plot.left - pad, plot.bottom + 5), 11, textColor);
if (n > 1) {
_text(canvas, labels.last, Offset(plot.right + pad, plot.bottom + 5), 11, textColor, alignRight: true);
}
// Lines, last series first so the main one stays on top
for (int k = series.length - 1; k >= 0; k--) {
final s = series[k];
final r = ranges[k];
final path = Path()..moveTo(xAt(0), yAt(s.values[0], r));
for (int i = 1; i < n; i++) {
path.lineTo(xAt(i), yAt(s.values[i], r));
}
canvas.drawPath(
path,
Paint()
..color = s.color
..strokeWidth = 2
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round,
);
// Points with a surface ring so they read on top of the line
for (int i = 0; i < n; i++) {
final isSel = i == selected;
final p = Offset(xAt(i), yAt(s.values[i], r));
canvas.drawCircle(p, isSel ? 6 : 4.5, Paint()..color = Colors.white);
canvas.drawCircle(p, isSel ? 4.5 : 3.5, Paint()..color = s.color);
}
}
// Tooltip for the selected point: label, then each value in its colour
if (selected != null) {
final i = selected!;
canvas.drawLine(Offset(xAt(i), plot.top), Offset(xAt(i), plot.bottom), grid);
final tp = TextPainter(
text: TextSpan(
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.white),
children: [
TextSpan(text: labels[i]),
for (final s in series)
TextSpan(
text: ' ${s.format(s.values[i])}',
style: TextStyle(color: Color.lerp(s.color, Colors.white, 0.35)),
),
],
),
textDirection: TextDirection.ltr,
)..layout(maxWidth: size.width - 16);
final w = tp.width + 16;
final left = (xAt(i) - w / 2).clamp(0.0, size.width - w);
canvas.drawRRect(
RRect.fromRectAndRadius(Rect.fromLTWH(left, 2, w, 24), const Radius.circular(6)),
Paint()..color = Colors.grey[900]!,
);
tp.paint(canvas, Offset(left + 8, 2 + (24 - tp.height) / 2));
}
}
void _text(Canvas canvas, String text, Offset at, double size, Color color, {bool alignRight = false}) {
final tp = TextPainter(
text: TextSpan(text: text, style: TextStyle(fontSize: size, color: color)),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(canvas, alignRight ? at.translate(-tp.width, 0) : at);
}
@override
bool shouldRepaint(_ChartPainter old) =>
old.labels != labels ||
old.series != series ||
old.selected != selected ||
old.textColor != textColor;
}