Files
SDKmuta/lib/screens/book_screen.dart
T
Jan Pleterski 5f9e2a3b86 optimization of the detection algorithem.
BOOK update.
2026-11-27 09:43:25 +01:00

1406 lines
47 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 _View { stats, history }
enum _Filter { training, tournament }
enum _HistoryFilter { all, training, tournament }
enum _Period { month, threeMonths, year, all, custom }
/// Knjiga, two screens:
/// * Statistika: the summary card (form, records) and the progress graph for
/// one kind of session and one number of shots per target, so averages
/// compare like with like. The graph has its own month/year navigation.
/// * Zgodovina: every session of the chosen kind, whatever its shot count.
/// One period filter drives the card and the list, so they always agree.
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
_View _view = _View.stats;
_Filter _filter = _Filter.training; // Statistika: trainings or tournaments
_HistoryFilter _historyFilter = _HistoryFilter.all; // Zgodovina
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(() {
_view = pick(_View.values, 'view', _view);
_filter = pick(_Filter.values, 'filter', _filter);
_historyFilter = pick(_HistoryFilter.values, 'historyFilter', _historyFilter);
_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}view', _view.index);
await p.setInt('${_prefix}filter', _filter.index);
await p.setInt('${_prefix}historyFilter', _historyFilter.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()))
]);
}
if (_view == _View.history) {
return Column(children: [
_buildTabs(),
_buildHistoryBar(),
Expanded(child: _buildHistoryScreen()),
]);
}
// Statistics only compare like with like: one kind of session, one
// shots-per-target format. The card uses 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(),
_buildStatsBar(formats, shots),
Expanded(
child: _years.isEmpty
? _centered(_buildEmpty())
: stats.targets == 0
? Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: _periodRow()),
Expanded(child: _centered(_noSessions())),
])
: _buildStats(format, stats),
),
],
);
},
);
}
// An empty state in the middle of the free space; pull-to-refresh still works
Widget _centered(Widget child) {
return RefreshIndicator(
onRefresh: _load,
child: CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(),
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: child,
),
),
),
],
),
);
}
// Nothing in the chosen period or filter (there are sessions elsewhere)
Widget _noSessions() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Padding(
padding: const EdgeInsets.only(bottom: 48), // a little above the middle
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.event_busy_rounded, size: 40, color: surf.textSecondary),
const SizedBox(height: 10),
Text(s.t('No sessions in this period'),
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15, color: surf.textSecondary)),
],
),
);
}
// Full-width "Obdobje … To leto ▾" button: says what it changes and that it
// can be tapped. Opens the period sheet; Statistika and Zgodovina share it.
Widget _periodRow() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Material(
color: surf.card,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _pickPeriod,
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
child: Row(
children: [
Icon(Icons.date_range_rounded, size: 20, color: s.bulletColor),
const SizedBox(width: 10),
Text(s.t('Period'),
style: TextStyle(fontSize: 13, color: surf.textSecondary)),
const SizedBox(width: 12),
Expanded(
child: Text(
_periodLabel(_period),
textAlign: TextAlign.right,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: surf.textPrimary),
),
),
Icon(Icons.expand_more_rounded, color: surf.textSecondary),
],
),
),
),
);
}
// Zgodovina: every session of the chosen kind in the period, any shot count
Widget _buildHistoryScreen() {
if (_years.isEmpty) return _centered(_buildEmpty());
final sessions = [
for (final x in _sessions!)
if (_inPeriod(x) &&
switch (_historyFilter) {
_HistoryFilter.all => true,
_HistoryFilter.training => !x.isTournament,
_HistoryFilter.tournament => x.isTournament,
})
x,
];
// Average per shot over the listed sessions, for each card's difference
final shots = sessions.fold(0, (a, x) => a + x.shots);
final average = sessions.length > 1 && shots > 0
? sessions.fold(0, (a, x) => a + x.totalScore) / shots
: null;
if (sessions.isEmpty) {
return Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: _historyHeader()),
Expanded(child: _centered(_noSessions())),
]);
}
return RefreshIndicator(
onRefresh: _load,
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 32),
children: _buildHistory(sessions, average),
),
);
}
// The two screens; filters continue the dark app bar, like Koledar/Stiki
Widget _buildTabs() {
final s = AppSettings.instance;
return BarTabs(
tabs: [
BarTab(s.t('Statistics'), Icons.insights_rounded),
BarTab(s.t('History'), Icons.history_rounded),
],
selected: _view.index,
onSelect: (i) => _change(() => _view = _View.values[i]),
);
}
// Zgodovina's dark row: which sessions to list
Widget _buildHistoryBar() {
final s = AppSettings.instance;
final labels = {
_HistoryFilter.all: s.t('All'),
_HistoryFilter.training: s.t('Trainings'),
_HistoryFilter.tournament: s.t('Tournaments'),
};
return Container(
color: AppTheme.bar,
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
child: Row(
children: [
for (final f in _HistoryFilter.values) ...[
if (f.index > 0) const SizedBox(width: 6),
Expanded(
child: _BarPill(
label: labels[f]!,
selected: f == _historyFilter,
empty: false,
onTap: () => _change(() => _historyFilter = f),
),
),
],
],
),
);
}
// Statistika's dark row: trainings or tournaments, then shots per target.
// Shots are 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 _buildStatsBar(List<int> formats, int? selected) {
final s = AppSettings.instance;
final sorted = {
for (int n = AppSettings.minBullets; n <= AppSettings.maxBullets; n++) n,
...formats,
}.toList()
..sort();
Widget kind(_Filter f, String label) => Expanded(
flex: 5,
child: _BarPill(
label: s.t(label),
selected: f == _filter,
empty: false,
onTap: () => _change(() {
_filter = f;
_shots = null;
_chartAt = null;
}),
),
);
return Container(
color: AppTheme.bar,
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
child: Row(
children: [
kind(_Filter.training, 'Trainings'),
const SizedBox(width: 6),
kind(_Filter.tournament, 'Tournaments'),
// Divider between the two groups
Container(
width: 1,
height: 22,
margin: const EdgeInsets.symmetric(horizontal: 8),
color: Colors.white24),
for (final n in sorted) ...[
if (n != sorted.first) const SizedBox(width: 4),
Expanded(
flex: 2,
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)!;
}
// Statistika as cards: one with the period's average per shot and its trend
// beside three counts; the graph; the best session. It fits
// the screen without scrolling, the graph taking the height that is left;
// on a screen too small for that it scrolls with a fixed-height graph.
// The graph gets every loaded session of the format, [all], and picks its
// own month or year.
Widget _buildStats(List<Session> all, ShooterStats stats) {
final s = AppSettings.instance;
final bestSession = stats.bestSession;
final tournaments = _filter == _Filter.tournament;
const gap = SizedBox(height: 12);
// One card: the average on the left, the three counts on the right
final surf = Surfaces.current;
final top = _BookCard(
padding: const EdgeInsets.symmetric(vertical: 14),
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(flex: 11, child: _averageContent(stats)),
VerticalDivider(width: 1, thickness: 1, color: surf.divider),
Expanded(
flex: 9,
child: Padding(
padding: const EdgeInsets.only(left: 14, right: 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_CountLine(
value: '${stats.sessions}',
label: s.t(tournaments ? 'Tournaments' : 'Trainings')),
_CountLine(
value: '${stats.targets}', label: s.t('Targets')),
_CountLine(
value: stats.averageTarget!.toStringAsFixed(1),
label: s.t('Average target')),
],
),
),
),
],
),
),
);
// Best session; tap to see its targets
final best = bestSession != null && stats.sessions > 1
? _HeroRecord(
label: s.t(tournaments ? 'Best tournament' : 'Best training'),
value: bestSession.averagePerShot!.toStringAsFixed(2),
caption:
'${DateFormat('d. M.').format(bestSession.date)} · ${bestSession.name}',
onTap: () => _openTargets(bestSession),
)
: null;
return LayoutBuilder(builder: (context, box) {
// Room for the cards above plus a graph that is still worth reading
if (box.maxHeight >= 560) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Column(
children: [
_periodRow(),
const SizedBox(height: 8),
top,
gap,
Expanded(child: _BookCard(child: _buildChart(all, stats, fill: true))),
if (best != null) ...[gap, best],
],
),
);
}
return RefreshIndicator(
onRefresh: _load,
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 32),
children: [
_periodRow(),
const SizedBox(height: 8),
top,
gap,
_BookCard(child: _buildChart(all, stats)),
if (best != null) ...[gap, best],
],
),
);
});
}
Widget _averageContent(ShooterStats stats) {
final s = AppSettings.instance;
final surf = Surfaces.current;
final trend = stats.trend;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(s.t('Average per shot').toUpperCase(),
maxLines: 2,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
letterSpacing: 1.2,
color: surf.textSecondary)),
FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
stats.averagePerShot?.toStringAsFixed(2) ?? '–',
style: TextStyle(
fontSize: 48,
fontWeight: FontWeight.w800,
color: surf.textPrimary,
height: 1.1),
),
),
if (trend != null)
Text(
'${trend >= 0 ? '▲' : '▼'} ${trend.abs().toStringAsFixed(2)} ${s.t('vs earlier')}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: _deltaColor(trend)),
),
],
),
);
}
// Shot average and points per session, each on its own scale.
// [fill]: the graph takes all the height the card gets (inside an Expanded)
Widget _buildChart(List<Session> all, ShooterStats stats, {bool fill = false}) {
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)
_fillIf(
fill,
Padding(
padding: const EdgeInsets.symmetric(vertical: 40),
child: Center(
child: Text(s.t('No sessions in this period'),
style: TextStyle(color: surf.textSecondary)),
),
),
)
else ...[
const SizedBox(height: 4),
_fillIf(
fill,
ProgressChart(
expand: fill,
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,
),
),
],
],
),
);
}
static Widget _fillIf(bool fill, Widget child) =>
fill ? Expanded(child: child) : child;
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),
];
}
// Period selector (shared with Statistika) and the sort order, both labelled
Widget _historyHeader() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Padding(
// With the list's 4 px this starts 8 px under the bar, like Statistika
padding: const EdgeInsets.only(top: 4, bottom: 8),
// Same height for both buttons
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(child: _periodRow()),
const SizedBox(width: 8),
// Each tap switches between date and score order
Material(
color: surf.card,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => _change(() => _sortByScore = !_sortByScore),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
Icon(
_sortByScore
? Icons.leaderboard_rounded
: Icons.event_rounded,
size: 20,
color: s.bulletColor),
const SizedBox(width: 6),
Text(s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'),
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: surf.textPrimary)),
],
),
),
),
),
],
),
),
);
}
// 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(
width: double.infinity,
margin: const EdgeInsets.only(bottom: 48), // a little above the middle
padding: const EdgeInsets.symmetric(vertical: 36, horizontal: 24),
decoration: BoxDecoration(
color: surf.card, borderRadius: BorderRadius.circular(24)),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: s.bulletColor.withValues(alpha: 0.15),
shape: BoxShape.circle,
),
child: Icon(Icons.track_changes_rounded,
size: 44, color: s.bulletColor),
),
const SizedBox(height: 16),
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.insights_rounded,
'Statistics / History: your form and progress graph, or the list of all your sessions.'
),
(
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: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.'
),
(
Icons.filter_list_rounded,
'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.'
),
(
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 on one target.'
),
(
Icons.more_vert_rounded,
'Three dots on the right or long press: session details, single targets, rename and delete.'
),
]);
}
/// A rounded card on the page, the same surface as the history cards.
class _BookCard extends StatelessWidget {
final Widget child;
final EdgeInsetsGeometry padding;
const _BookCard({required this.child, this.padding = EdgeInsets.zero});
@override
Widget build(BuildContext context) {
return Container(
padding: padding,
decoration: BoxDecoration(
color: Surfaces.current.card,
borderRadius: BorderRadius.circular(20)),
child: child,
);
}
}
/// One count in the summary card: number, then its label, on one line.
class _CountLine extends StatelessWidget {
final String value;
final String label;
const _CountLine({required this.value, required this.label});
@override
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Row(
children: [
Text(value,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: surf.textPrimary)),
const SizedBox(width: 8),
Expanded(
child: Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: surf.textSecondary)),
),
],
);
}
}
/// Best-session card: 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.card,
borderRadius: BorderRadius.circular(20),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 10, 14),
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),
),
),
),
),
);
}
}