1155 lines
42 KiB
Dart
1155 lines
42 KiB
Dart
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 '../utils/format.dart';
|
||
import '../widgets/ui.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);
|
||
TargetRepository.changed.addListener(_load);
|
||
_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);
|
||
TargetRepository.changed.removeListener(_load);
|
||
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;
|
||
});
|
||
}
|
||
|
||
// Dates a period covers, under its name in the sheet
|
||
String? _periodRange(_Period p) {
|
||
final s = AppSettings.instance;
|
||
final f = DateFormat('d. M. yyyy');
|
||
final today = _today;
|
||
return switch (p) {
|
||
_Period.month => '${DateFormat('d. M.').format(DateTime(today.year, today.month))} – ${f.format(today)}',
|
||
_Period.threeMonths => '${DateFormat('d. M.').format(DateTime(today.year, today.month - 3, today.day))} – ${f.format(today)}',
|
||
_Period.year => '${today.year}',
|
||
_Period.all => s.t('since the first saved target'),
|
||
_Period.custom => _custom == null ? s.t('choose dates …') : _periodLabel(p),
|
||
};
|
||
}
|
||
|
||
void _pickPeriod() {
|
||
final s = AppSettings.instance;
|
||
showAppSheet(
|
||
context,
|
||
title: s.t('Period'),
|
||
subtitle: s.t('Applies to Statistics and History'),
|
||
builder: (sheet) => Column(
|
||
children: [
|
||
for (final p in _Period.values)
|
||
SheetOption(
|
||
label: p == _Period.custom ? s.t('Custom range') : _periodLabel(p),
|
||
subtitle: _periodRange(p),
|
||
selected: p == _period,
|
||
onTap: () {
|
||
Navigator.pop(sheet);
|
||
_setPeriod(p);
|
||
},
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
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 = _formatCounts(sessions);
|
||
return counts.keys.toList()
|
||
..sort((a, b) => counts[b]!.compareTo(counts[a]!));
|
||
}
|
||
|
||
// Number of targets with each shot count
|
||
static Map<int, int> _formatCounts(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;
|
||
}
|
||
|
||
// 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(filters: _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(filters: _buildStatsBar(_formatCounts(typed.where(_inPeriod).toList()), shots)),
|
||
Expanded(
|
||
child: _years.isEmpty
|
||
? _centered(_buildEmpty())
|
||
: stats.targets == 0
|
||
? Column(children: [
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 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;
|
||
return Padding(
|
||
padding: const EdgeInsets.only(bottom: 48), // a little above the middle
|
||
child: EmptyState(icon: Icons.event_busy_rounded, title: s.t('No sessions in this period')),
|
||
);
|
||
}
|
||
|
||
// "Obdobje … Ta mesec ▾": says what it changes and that it can be tapped.
|
||
// Opens the period sheet; Statistika and Zgodovina share it.
|
||
Widget _periodRow({bool compact = false}) {
|
||
final s = AppSettings.instance;
|
||
final c = Palette.current;
|
||
return AppCard(
|
||
onTap: _pickPeriod,
|
||
radius: 14,
|
||
padding: const EdgeInsets.fromLTRB(14, 0, 10, 0),
|
||
child: SizedBox(
|
||
height: 46,
|
||
child: Row(
|
||
children: [
|
||
Icon(Icons.calendar_today_outlined, size: 18, color: c.accent),
|
||
const SizedBox(width: 10),
|
||
Text(s.t('Period'), style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: c.ink)),
|
||
SizedBox(width: compact ? 8 : 12),
|
||
Expanded(
|
||
child: Text(
|
||
_periodLabel(_period),
|
||
textAlign: compact ? TextAlign.left : TextAlign.right,
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: TextStyle(fontSize: 13, color: c.muted),
|
||
),
|
||
),
|
||
const SizedBox(width: 4),
|
||
Icon(Icons.expand_more_rounded, size: 20, color: c.muted),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
// 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(AppTheme.edge, 0, AppTheme.edge, 0),
|
||
child: _historyHeader()),
|
||
Expanded(child: _centered(_noSessions())),
|
||
]);
|
||
}
|
||
return RefreshIndicator(
|
||
onRefresh: _load,
|
||
child: ListView(
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24),
|
||
children: _buildHistory(sessions, average),
|
||
),
|
||
);
|
||
}
|
||
|
||
// Title, then one card: the two screens over that screen's filters
|
||
Widget _buildTabs({Widget? filters}) {
|
||
final s = AppSettings.instance;
|
||
return Column(
|
||
children: [
|
||
PageHeader(
|
||
title: s.t('Book'),
|
||
action: CircleButton(icon: Icons.info_outline_rounded, tooltip: s.t('Help'), onTap: () => showBookHelp(context)),
|
||
),
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 12),
|
||
child: SegmentedCard(rows: [
|
||
SegmentedTabs(
|
||
bare: true,
|
||
height: 40,
|
||
items: [
|
||
SegmentItem(s.t('Statistics'), Icons.bar_chart_rounded),
|
||
SegmentItem(s.t('History'), Icons.history_rounded),
|
||
],
|
||
selected: _view.index,
|
||
onSelect: (i) => _change(() => _view = _View.values[i]),
|
||
),
|
||
if (filters != null) filters,
|
||
]),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
|
||
// Zgodovina: which sessions to list
|
||
Widget _buildHistoryBar() {
|
||
final s = AppSettings.instance;
|
||
return SegmentedTabs(
|
||
bare: true,
|
||
height: 36,
|
||
items: [SegmentItem(s.t('All')), SegmentItem(s.t('Trainings')), SegmentItem(s.t('Tournaments'))],
|
||
selected: _historyFilter.index,
|
||
onSelect: (i) => _change(() => _historyFilter = _HistoryFilter.values[i]),
|
||
);
|
||
}
|
||
|
||
// Statistika: trainings or tournaments, and at the end of the same bar the
|
||
// shots-per-target format as a menu. Shots are 1–5 (the capture limit);
|
||
// older saves above 5 keep their own entry. Formats with no targets yet
|
||
// can't be picked.
|
||
Widget _buildStatsBar(Map<int, int> counts, int? selected) {
|
||
final s = AppSettings.instance;
|
||
final c = Palette.current;
|
||
final sorted = {
|
||
for (int n = AppSettings.minBullets; n <= AppSettings.maxBullets; n++) n,
|
||
...counts.keys,
|
||
}.toList()
|
||
..sort((a, b) => b.compareTo(a));
|
||
final shotsMenu = PopupMenuButton<int>(
|
||
tooltip: s.t('Shots per target'),
|
||
initialValue: selected,
|
||
position: PopupMenuPosition.under,
|
||
offset: const Offset(0, 6),
|
||
color: c.isDark ? c.card2 : c.card,
|
||
surfaceTintColor: Colors.transparent,
|
||
shape: RoundedRectangleBorder(
|
||
borderRadius: BorderRadius.circular(14),
|
||
side: BorderSide(color: c.line),
|
||
),
|
||
onSelected: (n) => _change(() => _shots = n),
|
||
itemBuilder: (_) => [
|
||
for (final n in sorted)
|
||
PopupMenuItem<int>(
|
||
value: n,
|
||
enabled: (counts[n] ?? 0) > 0,
|
||
height: 44,
|
||
child: Row(
|
||
children: [
|
||
SizedBox(
|
||
width: 22,
|
||
child: n == selected ? Icon(Icons.check_rounded, size: 18, color: c.accent) : null,
|
||
),
|
||
const SizedBox(width: 6),
|
||
Text(shotCount(n),
|
||
style: TextStyle(
|
||
fontSize: 14,
|
||
fontWeight: n == selected ? FontWeight.w700 : FontWeight.w500,
|
||
color: (counts[n] ?? 0) > 0 ? c.ink : c.faint)),
|
||
const SizedBox(width: 16),
|
||
const Spacer(),
|
||
Text(targetCount(counts[n] ?? 0),
|
||
style: TextStyle(fontSize: 12, color: c.muted, fontFeatures: AppTheme.tnum)),
|
||
],
|
||
),
|
||
),
|
||
],
|
||
child: Padding(
|
||
padding: const EdgeInsets.only(left: 8, right: 2),
|
||
child: Row(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
Text(selected == null ? '–' : shotCount(selected),
|
||
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: c.ink)),
|
||
Icon(Icons.expand_more_rounded, size: 18, color: c.muted),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
return SegmentedTabs(
|
||
bare: true,
|
||
height: 36,
|
||
items: [SegmentItem(s.t('Trainings')), SegmentItem(s.t('Tournaments'))],
|
||
selected: _filter.index,
|
||
onSelect: (i) => _change(() {
|
||
_filter = _Filter.values[i];
|
||
_shots = null;
|
||
_chartAt = null;
|
||
}),
|
||
trailing: shotsMenu,
|
||
);
|
||
}
|
||
|
||
// 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
|
||
],
|
||
);
|
||
}
|
||
|
||
// Statistika as cards: 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 c = Palette.current;
|
||
final bestSession = stats.bestSession;
|
||
final tournaments = _filter == _Filter.tournament;
|
||
const gap = SizedBox(height: 12);
|
||
|
||
final top = AppCard(
|
||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||
child: IntrinsicHeight(
|
||
child: Row(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Expanded(flex: 10, child: _averageContent(stats)),
|
||
VerticalDivider(width: 1, thickness: 1, color: c.line2),
|
||
Expanded(
|
||
flex: 10,
|
||
child: Padding(
|
||
padding: const EdgeInsets.only(left: 14, right: 10),
|
||
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: dec(stats.averageTarget!, 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: dec(bestSession.averagePerShot!),
|
||
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 >= 520) {
|
||
return Padding(
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 16),
|
||
child: Column(
|
||
children: [
|
||
_periodRow(),
|
||
gap,
|
||
top,
|
||
gap,
|
||
Expanded(child: AppCard(padding: EdgeInsets.zero, child: _buildChart(all, stats, fill: true))),
|
||
if (best != null) ...[gap, best],
|
||
],
|
||
),
|
||
);
|
||
}
|
||
return RefreshIndicator(
|
||
onRefresh: _load,
|
||
child: ListView(
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24),
|
||
children: [
|
||
_periodRow(),
|
||
gap,
|
||
top,
|
||
gap,
|
||
AppCard(padding: EdgeInsets.zero, child: _buildChart(all, stats)),
|
||
if (best != null) ...[gap, best],
|
||
],
|
||
),
|
||
);
|
||
});
|
||
}
|
||
|
||
Widget _averageContent(ShooterStats stats) {
|
||
final s = AppSettings.instance;
|
||
final c = Palette.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: AppTheme.kicker(c).copyWith(fontSize: 10.5)),
|
||
FittedBox(
|
||
fit: BoxFit.scaleDown,
|
||
alignment: Alignment.centerLeft,
|
||
child: Text(
|
||
stats.averagePerShot == null ? '–' : dec(stats.averagePerShot!),
|
||
style: TextStyle(
|
||
fontSize: 46, fontWeight: FontWeight.w800, letterSpacing: -1, color: c.ink, height: 1.15, fontFeatures: AppTheme.tnum),
|
||
),
|
||
),
|
||
if (trend != null) ...[
|
||
const SizedBox(height: 4),
|
||
Container(
|
||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||
decoration: BoxDecoration(
|
||
color: trend >= 0 ? c.posSoft : c.redSoft,
|
||
borderRadius: BorderRadius.circular(20),
|
||
),
|
||
child: Text(
|
||
'${trend >= 0 ? '▲' : '▼'} ${dec(trend.abs())} ${s.t('vs earlier')}',
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: c.delta(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 c = Palette.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);
|
||
final title = _chartByYear ? '${at.year}' : DateFormat('LLLL yyyy', _locale).format(at);
|
||
|
||
Widget arrow(IconData icon, DateTime? to) => GestureDetector(
|
||
behavior: HitTestBehavior.opaque,
|
||
onTap: to == null ? null : () => setState(() => _chartAt = to),
|
||
child: Padding(
|
||
padding: const EdgeInsets.all(4),
|
||
child: Icon(icon, size: 20, color: to == null ? c.faint : c.ink2),
|
||
),
|
||
);
|
||
|
||
return Padding(
|
||
padding: const EdgeInsets.fromLTRB(8, 10, 14, 14),
|
||
child: Column(
|
||
children: [
|
||
Row(
|
||
children: [
|
||
Expanded(
|
||
child: Row(
|
||
children: [
|
||
arrow(Icons.chevron_left_rounded, prev.isBefore(first) ? null : prev),
|
||
Flexible(
|
||
child: FittedBox(
|
||
fit: BoxFit.scaleDown,
|
||
child: Text(title, maxLines: 1, style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: c.ink)),
|
||
),
|
||
),
|
||
arrow(Icons.chevron_right_rounded, next.isAfter(today) ? null : next),
|
||
],
|
||
),
|
||
),
|
||
_Toggle(
|
||
labels: [s.t('Month'), s.t('Year')],
|
||
selected: _chartByYear ? 1 : 0,
|
||
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: c.muted))),
|
||
),
|
||
)
|
||
else ...[
|
||
const SizedBox(height: 4),
|
||
_fillIf(
|
||
fill,
|
||
Padding(
|
||
padding: const EdgeInsets.only(left: 6),
|
||
child: ProgressChart(
|
||
expand: fill,
|
||
labels: data.labels,
|
||
series: [
|
||
ChartSeries(s.t('Shot average'), c.accent, data.perShot, axis: ChartAxis.left),
|
||
ChartSeries(s.t('Number of points'), c.isDark ? c.ink2 : c.muted, data.total,
|
||
decimals: 0, axis: ChartAxis.right),
|
||
],
|
||
textColor: c.muted,
|
||
gridColor: c.line2,
|
||
surfaceColor: c.card,
|
||
tooltipColor: c.isDark ? c.ink : c.ink,
|
||
tooltipTextColor: c.isDark ? c.bg : Colors.white,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
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;
|
||
double? best;
|
||
for (final x in sessions) {
|
||
final avg = x.averagePerShot;
|
||
if (avg != null && (best == null || avg > best)) best = avg;
|
||
}
|
||
return [
|
||
_historyHeader(),
|
||
for (final x in ordered) _sessionCard(x, average, isBest: sessions.length > 1 && x.averagePerShot == best),
|
||
];
|
||
}
|
||
|
||
// Period selector (shared with Statistika) and the sort order
|
||
Widget _historyHeader() {
|
||
final s = AppSettings.instance;
|
||
final c = Palette.current;
|
||
return Padding(
|
||
padding: const EdgeInsets.only(bottom: 12),
|
||
child: Row(
|
||
children: [
|
||
Expanded(child: _periodRow(compact: true)),
|
||
const SizedBox(width: 8),
|
||
// Each tap switches between date and score order
|
||
AppCard(
|
||
radius: 14,
|
||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||
onTap: () => _change(() => _sortByScore = !_sortByScore),
|
||
child: SizedBox(
|
||
height: 46,
|
||
child: Row(
|
||
children: [
|
||
Icon(_sortByScore ? Icons.leaderboard_outlined : Icons.calendar_today_outlined, size: 18, color: c.accent),
|
||
const SizedBox(width: 8),
|
||
Text(s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'),
|
||
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: c.ink)),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
// 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 or the dots open details.
|
||
Widget _sessionCard(Session session, double? average, {bool isBest = false}) {
|
||
final s = AppSettings.instance;
|
||
final c = Palette.current;
|
||
final avg = session.averagePerShot;
|
||
final delta = avg == null || average == null ? null : avg - average;
|
||
|
||
return Padding(
|
||
padding: const EdgeInsets.only(bottom: 10),
|
||
child: AppCard(
|
||
padding: const EdgeInsets.fromLTRB(10, 10, 0, 10),
|
||
onTap: () => _openTargets(session),
|
||
onLongPress: () => _openDetails(session),
|
||
child: Row(
|
||
children: [
|
||
_DateBlock(date: session.date, locale: _locale),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
if (session.isTournament) ...[
|
||
Icon(Icons.emoji_events_outlined, size: 16, color: c.accent),
|
||
const SizedBox(width: 4),
|
||
],
|
||
Flexible(
|
||
child: Text(session.name,
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: c.ink)),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 3),
|
||
Text(targetCount(session.targets.length), style: TextStyle(fontSize: 12, color: c.muted)),
|
||
],
|
||
),
|
||
),
|
||
_CardFigure(value: '${session.totalScore}', note: s.t('Sum'), noteColor: c.muted),
|
||
const SizedBox(width: 14),
|
||
_CardFigure(
|
||
value: avg == null ? '–' : dec(avg),
|
||
valueColor: isBest ? c.gold : null,
|
||
note: delta == null ? ' ' : signedDec(delta),
|
||
noteColor: delta == null ? null : c.delta(delta),
|
||
bold: true,
|
||
),
|
||
SizedBox(
|
||
width: 40,
|
||
child: IconButton(
|
||
tooltip: s.t('Details'),
|
||
visualDensity: VisualDensity.compact,
|
||
icon: Icon(Icons.more_vert_rounded, size: 20, color: c.muted),
|
||
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;
|
||
return Padding(
|
||
padding: const EdgeInsets.only(bottom: 48), // a little above the middle
|
||
child: EmptyState(
|
||
icon: Icons.track_changes_rounded,
|
||
title: s.t('No saved target data found'),
|
||
hint: s.t('Saved targets and your statistics will appear here'),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// What Knjiga shows and where to tap; opened from the info button.
|
||
void showBookHelp(BuildContext context) {
|
||
final s = AppSettings.instance;
|
||
showHelpSheet(context, t: s.t, items: const [
|
||
(Icons.bar_chart_rounded, 'Statistics / History: your form and progress graph, or the list of all your sessions.'),
|
||
(Icons.emoji_events_outlined, 'Trainings / Tournaments: choose which sessions the statistics count.'),
|
||
(Icons.grid_view_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_outlined, 'Best training / tournament in the bottom card: tap to open its targets.'),
|
||
(Icons.calendar_today_outlined,
|
||
'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: 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_outlined, '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.'),
|
||
]);
|
||
}
|
||
|
||
/// 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 c = Palette.current;
|
||
return Row(
|
||
children: [
|
||
Text(value, style: TextStyle(fontSize: 17, fontWeight: FontWeight.w800, color: c.ink, fontFeatures: AppTheme.tnum)),
|
||
const SizedBox(width: 6),
|
||
Expanded(
|
||
child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: c.muted)),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Best-session card: trophy, 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 c = Palette.current;
|
||
return AppCard(
|
||
onTap: onTap,
|
||
padding: const EdgeInsets.fromLTRB(14, 12, 10, 12),
|
||
child: Row(
|
||
children: [
|
||
IconBadge(Icons.emoji_events_outlined, size: 40, color: c.gold),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(label,
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: c.ink)),
|
||
Text(caption, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: c.muted)),
|
||
],
|
||
),
|
||
),
|
||
Text(value,
|
||
style: TextStyle(fontSize: 21, fontWeight: FontWeight.w800, color: c.isDark ? c.gold : c.goldInk, fontFeatures: AppTheme.tnum)),
|
||
const SizedBox(width: 2),
|
||
Icon(Icons.chevron_right_rounded, size: 20, color: c.faint),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Date tile on the card's left: weekday, day, month.
|
||
class _DateBlock extends StatelessWidget {
|
||
final DateTime date;
|
||
final String locale;
|
||
|
||
const _DateBlock({required this.date, required this.locale});
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final c = Palette.current;
|
||
final small = TextStyle(fontSize: 9, fontWeight: FontWeight.w700, letterSpacing: 0.4, color: c.accentInk);
|
||
return Container(
|
||
width: 46,
|
||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||
decoration: BoxDecoration(color: c.accentSoft, borderRadius: BorderRadius.circular(12)),
|
||
child: Column(
|
||
children: [
|
||
Text(DateFormat('EEE', locale).format(date).toUpperCase().replaceAll('.', ''), style: small),
|
||
Text(DateFormat('d').format(date),
|
||
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w800, height: 1.15, color: c.ink)),
|
||
Text(DateFormat('MMM', locale).format(date).toUpperCase().replaceAll('.', ''), style: small),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Two-option switch (Mesec | Leto): a raised pill on a quiet track, each
|
||
/// segment as wide as its label.
|
||
class _Toggle extends StatelessWidget {
|
||
final List<String> labels;
|
||
final int selected;
|
||
final ValueChanged<int> onSelect;
|
||
|
||
const _Toggle({required this.labels, required this.selected, required this.onSelect});
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final c = Palette.current;
|
||
return Container(
|
||
height: 30,
|
||
padding: const EdgeInsets.all(3),
|
||
decoration: BoxDecoration(color: c.isDark ? c.bg : c.tile, borderRadius: BorderRadius.circular(10)),
|
||
child: Row(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
for (int i = 0; i < labels.length; i++)
|
||
GestureDetector(
|
||
behavior: HitTestBehavior.opaque,
|
||
onTap: () => onSelect(i),
|
||
child: AnimatedContainer(
|
||
duration: const Duration(milliseconds: 150),
|
||
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||
alignment: Alignment.center,
|
||
decoration: BoxDecoration(
|
||
color: i == selected ? (c.isDark ? c.tile : c.card) : Colors.transparent,
|
||
borderRadius: BorderRadius.circular(7),
|
||
boxShadow: i == selected && !c.isDark ? c.shadow : null,
|
||
),
|
||
child: Text(
|
||
labels[i],
|
||
maxLines: 1,
|
||
style: TextStyle(
|
||
fontSize: 12,
|
||
fontWeight: i == selected ? FontWeight.w700 : FontWeight.w500,
|
||
color: i == selected ? c.ink : c.muted,
|
||
),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// One figure on a history card: bold number with a small note under it.
|
||
class _CardFigure extends StatelessWidget {
|
||
final String value;
|
||
final Color? valueColor;
|
||
final String? note;
|
||
final Color? noteColor;
|
||
final bool bold;
|
||
|
||
const _CardFigure({required this.value, this.valueColor, this.note, this.noteColor, this.bold = false});
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final c = Palette.current;
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.end,
|
||
children: [
|
||
Text(value,
|
||
style: TextStyle(
|
||
fontSize: 17, fontWeight: FontWeight.w800, color: valueColor ?? c.ink, fontFeatures: AppTheme.tnum)),
|
||
// The note row is always there (blank without a note), so the numbers line up
|
||
Text(note ?? ' ',
|
||
style: TextStyle(
|
||
fontSize: bold ? 11 : 9.5,
|
||
fontWeight: bold ? FontWeight.w700 : FontWeight.w500,
|
||
color: noteColor,
|
||
fontFeatures: AppTheme.tnum)),
|
||
],
|
||
);
|
||
}
|
||
}
|