Files
SDKmuta/lib/screens/book_screen.dart
T
2026-11-13 10:56:11 +01:00

1145 lines
39 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/app_settings.dart';
import '../services/target_repository.dart';
import '../theme/app_theme.dart';
import '../widgets/bar_tabs.dart';
import '../widgets/help_sheet.dart';
import '../widgets/progress_chart.dart';
import '../widgets/section.dart';
import 'session_screen.dart';
import 'target_view.dart';
enum _Filter { training, tournament }
enum _Period { month, threeMonths, year, all, custom }
/// Knjiga: one summary card with the shooter's form, records and progress graph,
/// then their sessions. One period filter drives the card and the list, so they
/// always agree; the graph has its own month/year navigation.
class BookScreen extends StatefulWidget {
const BookScreen({super.key});
@override
State<BookScreen> createState() => _BookScreenState();
}
class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
static const int _chartSessions = 12;
List<Session>? _sessions; // all sessions; null while loading
List<int> _years = []; // years with sessions, newest first
_Filter _filter = _Filter.training;
int? _shots; // shots per target shown; null = pick the most common one
bool _sortByScore = false;
_Period _period = _Period.year;
DateTimeRange? _custom; // range for _Period.custom
bool _chartByYear =
false; // graph: one point per month instead of per session
DateTime?
_chartAt; // month (or year) the graph shows; null = the latest session's
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_restoreSettings().then((_) => _load());
}
// The view settings survive leaving the screen and restarting the app.
// Which month the graph is scrolled to is not a setting: it opens on the latest.
static const _prefix = 'book.';
Future<void> _restoreSettings() async {
final p = await SharedPreferences.getInstance();
T pick<T extends Enum>(List<T> values, String key, T fallback) {
final i = p.getInt(_prefix + key);
return i != null && i >= 0 && i < values.length ? values[i] : fallback;
}
final start = p.getInt('${_prefix}customStart');
final end = p.getInt('${_prefix}customEnd');
if (!mounted) return;
setState(() {
_filter = pick(_Filter.values, 'filter', _filter);
_period = pick(_Period.values, 'period', _period);
_shots = p.getInt('${_prefix}shots');
_sortByScore = p.getBool('${_prefix}sortByScore') ?? _sortByScore;
_chartByYear = p.getBool('${_prefix}chartByYear') ?? _chartByYear;
if (start != null && end != null) {
_custom = DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(start),
end: DateTime.fromMillisecondsSinceEpoch(end));
}
// A custom period without its range can't be shown
if (_period == _Period.custom && _custom == null) _period = _Period.year;
});
}
Future<void> _saveSettings() async {
final p = await SharedPreferences.getInstance();
await p.setInt('${_prefix}filter', _filter.index);
await p.setInt('${_prefix}period', _period.index);
if (_shots == null) {
await p.remove('${_prefix}shots');
} else {
await p.setInt('${_prefix}shots', _shots!);
}
await p.setBool('${_prefix}sortByScore', _sortByScore);
await p.setBool('${_prefix}chartByYear', _chartByYear);
if (_custom != null) {
await p.setInt('${_prefix}customStart', _custom!.start.millisecondsSinceEpoch);
await p.setInt('${_prefix}customEnd', _custom!.end.millisecondsSinceEpoch);
}
}
// setState for a view setting, then remember it
void _change(VoidCallback update) {
setState(update);
_saveSettings();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) _load();
}
static DateTime get _today {
final now = DateTime.now();
return DateTime(now.year, now.month, now.day);
}
// null = all time
DateTimeRange? get _range {
final today = _today;
return switch (_period) {
_Period.month =>
DateTimeRange(start: DateTime(today.year, today.month), end: today),
_Period.threeMonths => DateTimeRange(
start: DateTime(today.year, today.month - 3, today.day), end: today),
_Period.year => DateTimeRange(start: DateTime(today.year), end: today),
_Period.all => null,
_Period.custom => _custom,
};
}
bool _inPeriod(Session x) {
final r = _range;
if (r == null) return true;
final day = DateTime(x.date.year, x.date.month, x.date.day);
return !day.isBefore(r.start) && !day.isAfter(r.end);
}
// Everything is read at once: scores come from the repository's cache, so
// changing the period or moving the graph needs no further loading
Future<void> _load() async {
final sessions = await TargetRepository.loadSessions();
if (mounted) {
setState(() {
_years = {for (final x in sessions) x.date.year}.toList()
..sort((a, b) => b.compareTo(a));
_sessions = sessions;
});
}
}
String _periodLabel(_Period p) {
final s = AppSettings.instance;
if (p == _Period.custom && _custom != null) {
final f = DateFormat('d. M. yyyy');
return '${f.format(_custom!.start)} – ${f.format(_custom!.end)}';
}
return s.t(switch (p) {
_Period.month => 'This month',
_Period.threeMonths => 'Last 3 months',
_Period.year => 'This year',
_Period.all => 'All',
_Period.custom => 'Custom range',
});
}
Future<void> _setPeriod(_Period p) async {
if (p == _Period.custom) {
final today = _today;
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(_years.isEmpty ? today.year : _years.last),
lastDate: today,
initialDateRange: _custom ?? _range,
);
if (picked == null) return;
_custom = picked;
}
_change(() {
_period = p;
_shots = null;
});
}
void _pickPeriod() {
final s = AppSettings.instance;
showModalBottomSheet(
context: context,
builder: (sheet) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(
s.t('Period'),
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold),
),
),
for (final p in _Period.values)
SheetOption(
label: _periodLabel(p),
selected: p == _period,
selectedColor: s.bulletColor,
onTap: () {
Navigator.pop(sheet);
_setPeriod(p);
},
),
const SizedBox(height: 8),
],
),
),
);
}
List<Session> get _filtered => [
for (final s in _sessions ?? <Session>[])
if (s.isTournament == (_filter == _Filter.tournament)) s,
];
// Shots-per-target formats in the current tab, most used first
List<int> _formats(List<Session> sessions) {
final counts = <int, int>{};
for (final session in sessions) {
for (final t in session.targets) {
if (t.shots > 0) counts[t.shots] = (counts[t.shots] ?? 0) + 1;
}
}
return counts.keys.toList()
..sort((a, b) => counts[b]!.compareTo(counts[a]!));
}
// The full session, not the copy limited to one format
Session _full(Session session) => _sessions!
.firstWhere((s) => s.name == session.name, orElse: () => session);
Future<void> _openDetails(Session session) async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (_) => SessionScreen(session: _full(session))));
_load();
}
String get _locale => AppSettings.instance.dateLocale;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: AppSettings.instance,
builder: (context, _) {
if (_sessions == null) {
return Column(children: [
_buildTabs(),
const Expanded(child: Center(child: CircularProgressIndicator()))
]);
}
// Statistics only compare like with like: one tab, one shots-per-target
// format. The card and the list use the period; the graph its own month/year.
final typed = _filtered;
final formats = _formats(typed.where(_inPeriod).toList());
final shots = formats.contains(_shots)
? _shots
: (formats.isEmpty ? null : formats.first);
final format = [
for (final session in typed)
if (session.onlyShots(shots).targets.isNotEmpty)
session.onlyShots(shots),
];
final sessions = format.where(_inPeriod).toList();
final stats = ShooterStats.of(sessions);
return Column(
children: [
_buildTabs(),
_buildFilterBar(formats, shots),
Expanded(
child: RefreshIndicator(
onRefresh: _load,
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
children: [
if (_years.isEmpty)
_buildEmpty()
else ...[
if (stats.targets > 0) _buildSummary(format, stats),
..._buildHistory(sessions,
stats.sessions > 1 ? stats.averagePerShot : null),
],
],
),
),
),
],
);
},
);
}
// Filters continue the dark app bar, like Koledar/Stiki
Widget _buildTabs() {
final s = AppSettings.instance;
return BarTabs(
tabs: [
BarTab(s.t('Trainings'), Icons.track_changes_rounded),
BarTab(s.t('Tournaments'), Icons.emoji_events_rounded),
],
selected: _filter.index,
onSelect: (i) => _change(() {
_filter = _Filter.values[i];
_shots = null;
_chartAt = null;
}),
);
}
// Second dark row under the tabs: shots-per-target pills across the width
// Always 1–5 (the capture limit); older saves above 5 keep their own pill.
// Formats with no targets yet are dimmed and can't be picked.
Widget _buildFilterBar(List<int> formats, int? selected) {
final sorted = {
for (int n = AppSettings.minBullets; n <= AppSettings.maxBullets; n++) n,
...formats,
}.toList()
..sort();
return Container(
color: AppTheme.bar,
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
// Pills share the full width equally
child: Row(
children: [
Text(AppSettings.instance.t('Shots'),
style: const TextStyle(fontSize: 12, color: Colors.white60)),
for (final n in sorted) ...[
const SizedBox(width: 6),
Expanded(
child: _BarPill(
label: '$n',
selected: n == selected,
empty: !formats.contains(n),
onTap: formats.contains(n)
? () => _change(() => _shots = n)
: null),
),
],
],
),
);
}
// Monday–Sunday week of [date], cut to its month: "6.–12. 10.", "27.–31. 10."
static String _weekLabel(DateTime date) {
final day = DateTime(date.year, date.month, date.day);
final monday = day.subtract(Duration(days: day.weekday - 1));
final sunday = monday.add(const Duration(days: 6));
final lastDay = DateTime(day.year, day.month + 1, 0).day;
final from = monday.month == day.month ? monday.day : 1;
final to = sunday.month == day.month ? sunday.day : lastDay;
return from == to ? '$from. ${day.month}.' : '$from.–$to. ${day.month}.';
}
// [chronological] is already the graph's month or year. Never more than 12
// points and nothing left out: Year has one point per month; Month one per
// session, or one per week when there are more than 12. A grouped point's
// total is the average total per session.
({
List<String> labels,
List<double> perShot,
List<double> total
}) _chartData(List<Session> chronological) {
final groups = <(String, List<Session>)>[];
if (_chartByYear) {
for (final x in chronological) {
final label =
DateFormat('LLL', _locale).format(x.date).replaceAll('.', '');
if (groups.isEmpty || groups.last.$1 != label) groups.add((label, []));
groups.last.$2.add(x);
}
} else {
final byWeek = chronological.length > _chartSessions;
for (final x in chronological) {
final label =
byWeek ? _weekLabel(x.date) : DateFormat('d. M.').format(x.date);
if (!byWeek || groups.isEmpty || groups.last.$1 != label) {
groups.add((label, []));
}
groups.last.$2.add(x);
}
}
double sum(List<Session> g, int Function(Session) f) =>
g.fold(0, (a, x) => a + f(x)).toDouble();
return (
labels: [for (final g in groups) g.$1],
perShot: [
for (final (_, g) in groups)
sum(g, (x) => x.totalScore) / sum(g, (x) => x.shots)
],
total: [
for (final (_, g) in groups) sum(g, (x) => x.totalScore) / g.length
],
);
}
// Up = green, down = red; darker shades on light backgrounds
static Color _deltaColor(double delta) {
final light = AppSettings.instance.isLightBackground;
return delta >= 0
? (light ? Colors.green[800]! : Colors.greenAccent[400]!)
: (light ? Colors.red[800]! : Colors.redAccent[100]!);
}
static String _signed(double v) =>
'${v >= 0 ? '+' : '−'}${v.abs().toStringAsFixed(2)}';
// Tint of the bullet colour that still reads on the card: lighter on dark
// cards, darker on light ones
static Color _tint(double amount) {
final s = AppSettings.instance;
return Color.lerp(s.bulletColor,
s.isLightBackground ? Colors.black : Colors.white, amount)!;
}
// Hero on the card surface (follows light/dark like the rest of Knjiga): the
// period's average per shot with its trend, counts and best session.
// The graph below gets every loaded session of the format, [all], and picks
// its own month or year.
Widget _buildSummary(List<Session> all, ShooterStats stats) {
final s = AppSettings.instance;
final surf = Surfaces.current;
final trend = stats.trend;
final bestSession = stats.bestSession;
return ClipRRect(
borderRadius: BorderRadius.circular(20),
child: ColoredBox(
color: surf.card,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(18, 16, 18, 14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(s.t('Average per shot').toUpperCase(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
letterSpacing: 1.2,
color: surf.textSecondary)),
Text(
stats.averagePerShot?.toStringAsFixed(2) ?? '–',
style: TextStyle(
fontSize: 44,
fontWeight: FontWeight.w800,
color: surf.textPrimary,
height: 1.1),
),
if (trend != null)
Text(
'${trend >= 0 ? '▲' : '▼'} ${trend.abs().toStringAsFixed(2)} ${s.t('vs earlier')}',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: _deltaColor(trend)),
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_HeroCount(
value: '${stats.sessions}',
label: s.t(_filter == _Filter.tournament
? 'Tournaments'
: 'Trainings')),
_HeroCount(
value: '${stats.targets}', label: s.t('Targets')),
_HeroCount(
value: stats.averageTarget!.toStringAsFixed(1),
label: s.t('Average target')),
],
),
],
),
// Best session; tap to see its targets
if (bestSession != null && stats.sessions > 1) ...[
const SizedBox(height: 14),
_HeroRecord(
label: s.t(_filter == _Filter.tournament
? 'Best tournament'
: 'Best training'),
value: bestSession.averagePerShot!.toStringAsFixed(2),
caption:
'${DateFormat('d. M.').format(bestSession.date)} · ${bestSession.name}',
onTap: () => _openTargets(bestSession),
),
],
],
),
),
Divider(height: 1, thickness: 1, color: surf.divider),
_buildChart(all, stats),
],
),
),
);
}
// Shot average and points per session, each on its own scale.
Widget _buildChart(List<Session> all, ShooterStats stats) {
final s = AppSettings.instance;
final surf = Surfaces.current;
final scored = all.where((x) => x.shots > 0).toList();
final today = _today;
final at = _chartAt ??
(scored.isEmpty ? today : scored.first.date); // newest first
final shown = [
for (final x in scored.reversed) // oldest first
if (x.date.year == at.year &&
(_chartByYear || x.date.month == at.month))
x
];
final data = _chartData(shown);
// One step back/forward; null when it would leave the years with sessions
final first = DateTime(_years.isEmpty ? today.year : _years.last);
final prev =
_chartByYear ? DateTime(at.year - 1) : DateTime(at.year, at.month - 1);
final next =
_chartByYear ? DateTime(at.year + 1) : DateTime(at.year, at.month + 1);
// Short, fixed-width title so the arrows and the toggle never move
final title = _chartByYear
? '${at.year}'
: toBeginningOfSentenceCase(
DateFormat('LLL yyyy', _locale).format(at).replaceAll('.', ''));
Widget arrow(IconData icon, DateTime? to) => IconButton(
visualDensity: VisualDensity.compact,
icon:
Icon(icon, color: to == null ? surf.divider : surf.textSecondary),
onPressed: to == null ? null : () => setState(() => _chartAt = to),
);
return Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 14),
child: Column(
children: [
Row(
children: [
arrow(Icons.chevron_left_rounded,
prev.isBefore(first) ? null : prev),
SizedBox(
width: 76,
child: Text(
title,
textAlign: TextAlign.center,
maxLines: 1,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: surf.textPrimary),
),
),
arrow(Icons.chevron_right_rounded,
next.isAfter(today) ? null : next),
const Spacer(),
_Toggle(
labels: [s.t('Month'), s.t('Year')],
selected: _chartByYear ? 1 : 0,
color: s.bulletColor,
onSelect: (i) => _change(() {
_chartByYear = i == 1;
_chartAt = at;
}),
),
],
),
if (shown.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 40),
child: Text(s.t('No sessions in this period'),
style: TextStyle(color: surf.textSecondary)),
)
else ...[
const SizedBox(height: 4),
ProgressChart(
labels: data.labels,
series: [
ChartSeries(s.t('Shot average'), s.bulletColor, data.perShot,
axis: ChartAxis.left),
ChartSeries(s.t('Number of points'), _tint(0.55), data.total,
decimals: 0, axis: ChartAxis.right),
],
textColor: surf.textSecondary,
gridColor: surf.divider,
),
],
],
),
);
}
List<Widget> _buildHistory(List<Session> sessions, double? average) {
// Average per shot, so sessions with more targets don't win by volume
final ordered = _sortByScore
? ([...sessions]..sort(
(a, b) => (b.averagePerShot ?? 0).compareTo(a.averagePerShot ?? 0)))
: sessions;
return [
_historyHeader(),
for (final x in ordered) _sessionCard(x, average),
if (sessions.isEmpty)
Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: Text(AppSettings.instance.t('No sessions in this period'),
style: TextStyle(color: Surfaces.current.textSecondary)),
),
),
];
}
// Section title, then the period chip (drives the card above too) and the sort toggle
Widget _historyHeader() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 12, 0, 4),
child: Row(
children: [
Expanded(
child: Text(
s.t(_sortByScore ? 'Best results' : 'History').toUpperCase(),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
letterSpacing: 1.4,
color: surf.textSecondary,
),
),
),
ActionChip(
avatar: Icon(Icons.date_range_rounded,
size: 16, color: surf.textSecondary),
label: Text(_periodLabel(_period)),
labelStyle: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: surf.textPrimary),
backgroundColor: surf.card,
side: BorderSide.none,
shape: const StadiumBorder(),
visualDensity: VisualDensity.compact,
onPressed: _pickPeriod,
),
// Each tap switches between date and score order
IconButton(
tooltip: s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'),
icon: Icon(
_sortByScore ? Icons.leaderboard_rounded : Icons.event_rounded,
color: surf.textSecondary),
onPressed: () => _change(() => _sortByScore = !_sortByScore),
),
],
),
);
}
// Date block left; points (Skupek) and average per shot right, the average
// with how far it is from [average].
// Tap shows this session's targets on one target; long press opens details.
Widget _sessionCard(Session session, double? average) {
final s = AppSettings.instance;
final surf = Surfaces.current;
final avg = session.averagePerShot;
final delta = avg == null || average == null ? null : avg - average;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Material(
color: surf.card,
borderRadius: BorderRadius.circular(12),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => _openTargets(session),
onLongPress: () => _openDetails(session),
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_DateBlock(
date: session.date, color: s.bulletColor, locale: _locale),
Expanded(
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 4, 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (session.isTournament) ...[
Icon(Icons.emoji_events_rounded,
size: 16, color: s.bulletColor),
const SizedBox(width: 4),
],
Flexible(
child: Text(
session.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: surf.textPrimary),
),
),
],
),
const SizedBox(height: 3),
Text(
targetCount(session.targets.length),
style: TextStyle(
fontSize: 12, color: surf.textSecondary),
),
],
),
),
),
_CardFigure(
label: s.t('Sum'), value: '${session.totalScore}'),
const SizedBox(width: 14),
_CardFigure(
label: s.t('Average'),
value: avg?.toStringAsFixed(2) ?? '–',
note: delta == null ? null : _signed(delta),
noteColor: delta == null ? null : _deltaColor(delta),
),
IconButton(
tooltip: s.t('Details'),
visualDensity: VisualDensity.compact,
icon:
Icon(Icons.more_vert_rounded, color: surf.textSecondary),
onPressed: () => _openDetails(session),
),
],
),
),
),
),
);
}
Future<void> _openFiles(List<File> files, {required bool combined}) async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (_) => TargetViewScreen(
jsonFiles: files, refreshFolders: _load, isCombinedView: combined),
),
);
_load();
}
Future<void> _openTargets(Session session) async {
if (session.targets.isEmpty) return;
await _openFiles(session.files, combined: true);
}
Widget _buildEmpty() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Container(
padding: const EdgeInsets.symmetric(vertical: 48, horizontal: 24),
decoration: BoxDecoration(
color: surf.card, borderRadius: BorderRadius.circular(20)),
child: Column(
children: [
Icon(Icons.track_changes_rounded,
size: 48, color: surf.textSecondary),
const SizedBox(height: 12),
Text(
s.t('No saved target data found'),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color: surf.textPrimary),
),
const SizedBox(height: 4),
Text(
s.t('Saved targets and your statistics will appear here'),
textAlign: TextAlign.center,
style: TextStyle(color: surf.textSecondary),
),
],
),
);
}
}
/// What Knjiga shows and where to tap; opened from the info button in the app bar.
void showBookHelp(BuildContext context) {
final s = AppSettings.instance;
showHelpSheet(context, accent: s.bulletColor, t: s.t, items: const [
(
Icons.emoji_events_rounded,
'Trainings / Tournaments: choose which sessions the statistics count.'
),
(
Icons.filter_5_rounded,
'Shots 1–5: statistics only compare targets with the same number of shots. Grey numbers have no targets yet.'
),
(
Icons.trending_up_rounded,
'Arrow under the average: your last 5 sessions compared with the 5 before them.'
),
(
Icons.show_chart_rounded,
'Graph: shot average (left axis) and number of points (right axis). Month shows each session of a month, Year one point per month; the arrows go back through earlier months or years. Tap or drag on it to see the values.'
),
(
Icons.workspace_premium_rounded,
'Best training / tournament in the top card: tap to open its targets.'
),
(
Icons.date_range_rounded,
'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.'
),
(
Icons.sort_rounded,
'Sort icon: tap to switch between date order and best average per shot. The coloured number shows how far a session is from your average.'
),
(
Icons.touch_app_rounded,
'Tap a session to see all its targets with the selected number of shots on one target.'
),
(
Icons.more_vert_rounded,
'Three dots on the right or long press: session details, single targets, rename and delete.'
),
]);
}
/// "12 Trainings" line on the hero, value first.
class _HeroCount extends StatelessWidget {
final String value;
final String label;
const _HeroCount({required this.value, required this.label});
@override
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Padding(
padding: const EdgeInsets.only(top: 2),
child: Text.rich(
TextSpan(children: [
TextSpan(
text: value,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: surf.textPrimary)),
TextSpan(
text: ' $label',
style: TextStyle(fontSize: 12, color: surf.textSecondary)),
]),
),
);
}
}
/// Record on the hero: label and date left, value right. Tappable.
class _HeroRecord extends StatelessWidget {
final String label;
final String value;
final String caption;
final VoidCallback onTap;
const _HeroRecord(
{required this.label,
required this.value,
required this.caption,
required this.onTap});
@override
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Material(
color: surf.textPrimary.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(12),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 6, 8),
child: Row(
children: [
Icon(Icons.emoji_events_rounded,
size: 20, color: AppSettings.instance.bulletColor),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: surf.textPrimary)),
Text(caption,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style:
TextStyle(fontSize: 11, color: surf.textSecondary)),
],
),
),
Text(value,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
color: surf.textPrimary)),
Icon(Icons.chevron_right_rounded,
size: 20, color: surf.textSecondary),
],
),
),
),
);
}
}
/// Full-height date column on the card's left edge, like the calendar cards.
class _DateBlock extends StatelessWidget {
final DateTime date;
final Color color;
final String locale;
const _DateBlock(
{required this.date, required this.color, required this.locale});
@override
Widget build(BuildContext context) {
final small = TextStyle(
fontSize: 10,
fontWeight: FontWeight.w700,
color: Colors.white.withValues(alpha: 0.9));
return Container(
width: 56,
color: color,
padding: const EdgeInsets.symmetric(vertical: 8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(DateFormat('EEE', locale).format(date).toUpperCase(),
style: small),
Text(
DateFormat('d').format(date),
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.white,
height: 1.15),
),
Text(
DateFormat('MMM', locale)
.format(date)
.toUpperCase()
.replaceAll('.', ''),
style: small),
],
),
);
}
}
/// Two-option switch with fixed, equal segments, so it keeps its size and
/// place whichever option is selected or however long the labels are.
class _Toggle extends StatelessWidget {
static const double _segment = 58;
final List<String> labels;
final int selected;
final Color color;
final ValueChanged<int> onSelect;
const _Toggle(
{required this.labels,
required this.selected,
required this.color,
required this.onSelect});
@override
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Container(
padding: const EdgeInsets.all(2),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
border: Border.all(color: surf.divider),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (int i = 0; i < labels.length; i++)
Material(
color: i == selected ? color : Colors.transparent,
shape: const StadiumBorder(),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => onSelect(i),
child: SizedBox(
width: _segment,
height: 28,
child: Center(
child: Text(
labels[i],
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: i == selected
? Colors.white
: surf.textSecondary),
),
),
),
),
),
],
),
);
}
}
/// One figure on a history card: small uppercase label over a bold number,
/// with an optional coloured note underneath (its row is kept even when empty).
class _CardFigure extends StatelessWidget {
final String label;
final String value;
final String? note;
final Color? noteColor;
const _CardFigure(
{required this.label, required this.value, this.note, this.noteColor});
@override
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(label.toUpperCase(),
style: TextStyle(
fontSize: 9,
fontWeight: FontWeight.bold,
letterSpacing: 1,
color: surf.textSecondary)),
Text(value,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
fontFeatures: const [FontFeature.tabularFigures()],
color: surf.textPrimary)),
// The note row is always there (blank without a note), so label and
// number line up across figures whether or not they have a note.
Text(note ?? ' ',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
fontFeatures: const [FontFeature.tabularFigures()],
color: noteColor)),
],
),
);
}
}
/// Small pill on the dark bar: white when selected, outlined otherwise.
class _BarPill extends StatelessWidget {
final String label;
final bool selected;
final bool empty; // no targets with this many shots
final VoidCallback? onTap; // null = not selectable
const _BarPill(
{required this.label,
required this.selected,
this.empty = false,
required this.onTap});
@override
Widget build(BuildContext context) {
return Material(
color: selected ? Colors.white : Colors.transparent,
shape: StadiumBorder(
side: BorderSide(color: selected ? Colors.white : Colors.white30)),
child: InkWell(
customBorder: const StadiumBorder(),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Text(
label,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: selected
? Colors.black
: (empty ? Colors.white30 : Colors.white70),
),
),
),
),
);
}
}