diff --git a/assets/club.enc b/assets/club.enc index 9c25760..0d1cbd2 100644 --- a/assets/club.enc +++ b/assets/club.enc @@ -1 +1 @@ -{"v":1,"salt":"Mrvt+SH25mgmeHSMLSa5MQ==","nonce":"jeM7rMRlbYVFBf/f","cipher":"fjQ0MEjR5SaCvelQ0v3bMMr9s0YbGjTOjFBrFGMVf2f4gsq4fCVlgqFub9nXcsPHIMxwDTr/GXDWRuJQ1afut0XQl9b1jMLrVgL6ELH2mFpIRcyBFCNSgKeyTLOBFbtPvE1zHcBK3HkJtK8vqdjH/3uzf9sWIIBnOi4bzFz6NbBTzLEIU6LkfKOLOTsXx43GpD1EA8j+5F9LFp4FJq4Ap0A5PHxf4IcTOf41FNaNOnbOKLGbOSXCNuGdLy4IFvSeJ3wnnqaTWJXOOnNOA5oWDr2WCEuEm8PfQuHHxdy5b9SmL5cdTe6W6GyEJrruH+ragADiyi6xC+CCkRA3NgIPgm4VyIB9Tg6M9E02NMg05xpwy8DwPar04QFmAfsfJYD/lAFEpi7ZbcJaHgOj0MLpoOHdJInLndPg6mmwtJm3ov2tdUiLDghGx0VzmWFRn659jng853hQm/7AMJ20pg677hTH9hzamf0jmZkln7NTCvesdnhE4T69sJtP+i89k5L/knH2yEBHkID1p8X0GPp9armxZaozdUTbKTRfykKhCC61rAnJCxjCguPK8+GZexBuaJvMNiGj66z6Z3VFE61Dvv1Q17qrhiMK7ZafH4aeiuFUM9thOmxVR5bgmRtfMAb/RgGFn9QG+qupNyQldediUNlM8HT0sIJDgtMA1Xe8fnZ9+psV/TNgO93KsCNm/GyMl9ksRDg/bU6UqQ+LxELSeHzssPKzLWpVdG1dMgtT2bif/rd2W9YIi+FNUhZWV4Y0wjp0TOfUKrrnM4VyMfYnZ6HrYO4TybW55Ub/gBbVZuXocA7g2pnnBBvk9kL6neeR6Fs5fcIhDZrI66dXvL0YYLe9bpYFjWpo1eQCCTGtCpqdcuxi/SIVWcpJMhVB37Iilw/j7YZHLUSlIfDruNwG4nyoVjM/n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XO5Lou14cKnTCa6GBirFMi2fJAmZTTVdreXVjHYcUoDrbM4XSojKf4jxKROzi+eT7QIhKy2ValqIwsCSHljkd/2ugwGUT8v7HVvuM5aLazVrRo4NlWVrSgd63D69PUPMfhxsqBtXDSEIJHlpPObzwvvRkJs9AlbEB+MT3uum9bI7fcUqzUpt1ohSA2NB+eJUckF1huUwoJ5h0QP5bDwstAK20wm5Cr9wOAi/MoGJslqVjYkoX12uZHLCXtYvew9Y5DynQen9TfJxekwg2vpadJnhS99hJXuFpnVA6EvKhxO8IMOQfj8zzxLjLbS3jIznrFxU5sfQHb1uCVrvxU+PMyCACWmq3ag4t9kw5GPBwAKYpRmQOCIXt5ABrPRT85UGwo6qNmPbhehdaTcUM/pYI8b+BM3fRx+zOrxjIjxM67JACsmreouprJNgkG298hHtwF435cysSCPq4lzdzV04+hMYa9rfe0hnCQQ3k15xI9BcumlEBZFbvL545PWYN0Zg/GmRTJaVRxIynB3HAJw/ekR0QfZViIwr6/JWELNvO2coknEYjU5e4B/uw6Lut2qeh8BabQUDv5ZmsV8/c1u+IP4kd8GB1DGob6AzAbaFVctKzPRt3X+w6BuJ3fJfaE53BBWkWq3WVSegI7ZlkADjAFOWtQ7yW+ATf0IF/k9BhtpEGRPS5fPSfwh3Ptkf0/PcrtMQPqb1wgjzy+tl3o9CWfwvJW3hu8ac=","mac":"3aZYxqTeZujIHc58JnsVyg=="} \ No newline at end of file diff --git a/lib/screens/book_screen.dart b/lib/screens/book_screen.dart index fdb2963..7390ea0 100644 --- a/lib/screens/book_screen.dart +++ b/lib/screens/book_screen.dart @@ -1,3 +1,4 @@ +import 'dart:io'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import '../services/app_settings.dart'; @@ -12,7 +13,11 @@ import 'target_view.dart'; enum _Filter { training, tournament } -/// Knjiga: one summary card with the shooter's form, then their sessions by month. +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}); @@ -23,12 +28,17 @@ class BookScreen extends StatefulWidget { class _BookScreenState extends State with WidgetsBindingObserver { static const int _chartSessions = 12; - List? _sessions; // selected year only; null while loading - List _years = []; - int _year = DateTime.now().year; + List? _sessions; // all sessions; null while loading + List _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() { @@ -48,22 +58,80 @@ class _BookScreenState extends State with WidgetsBindingObserver { if (state == AppLifecycleState.resumed) _load(); } - // Only the selected year's targets are read, which keeps loading quick with years of data + 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 _load() async { - final years = await TargetRepository.years(); - final sessions = await TargetRepository.loadSessions(year: _year); + final sessions = await TargetRepository.loadSessions(); if (mounted) { setState(() { - _years = years; + _years = {for (final x in sessions) x.date.year}.toList() + ..sort((a, b) => b.compareTo(a)); _sessions = sessions; }); } } - void _pickYear() { + 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 _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; + } + setState(() { + _period = p; + _shots = null; + }); + } + + void _pickPeriod() { final s = AppSettings.instance; - final options = {..._years, DateTime.now().year}.toList() - ..sort((a, b) => b.compareTo(a)); showModalBottomSheet( context: context, builder: (sheet) => SafeArea( @@ -73,35 +141,23 @@ class _BookScreenState extends State with WidgetsBindingObserver { Padding( padding: const EdgeInsets.only(bottom: 12), child: Text( - s.t('Year'), + s.t('Period'), style: const TextStyle( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold), ), ), - Flexible( - child: ListView( - shrinkWrap: true, - children: [ - for (final y in options) - SheetOption( - label: '$y', - selected: y == _year, - selectedColor: s.bulletColor, - onTap: () { - Navigator.pop(sheet); - setState(() { - _year = y; - _sessions = null; - _shots = null; - }); - _load(); - }, - ), - ], + 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), ], ), @@ -153,17 +209,19 @@ class _BookScreenState extends State with WidgetsBindingObserver { ]); } - // Statistics only compare like with like: one tab, one shots-per-target format + // 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); + final formats = _formats(typed.where(_inPeriod).toList()); final shots = formats.contains(_shots) ? _shots : (formats.isEmpty ? null : formats.first); - final sessions = [ + 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( @@ -176,11 +234,12 @@ class _BookScreenState extends State with WidgetsBindingObserver { child: ListView( padding: const EdgeInsets.fromLTRB(16, 16, 16, 32), children: [ - if (stats.targets == 0) + if (_years.isEmpty) _buildEmpty() else ...[ - _buildSummary(sessions, stats), - ..._buildHistory(sessions), + if (stats.targets > 0) _buildSummary(format, stats), + ..._buildHistory(sessions, + stats.sessions > 1 ? stats.averagePerShot : null), ], ], ), @@ -204,11 +263,12 @@ class _BookScreenState extends State with WidgetsBindingObserver { onSelect: (i) => setState(() { _filter = _Filter.values[i]; _shots = null; + _chartAt = null; }), ); } - // Second dark row under the tabs: shots-per-target pills left, year right + // 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 formats, int? selected) { @@ -219,84 +279,110 @@ class _BookScreenState extends State with WidgetsBindingObserver { ..sort(); return Container( color: AppTheme.bar, - padding: const EdgeInsets.fromLTRB(12, 0, 4, 8), + padding: const EdgeInsets.fromLTRB(12, 4, 12, 10), + // Pills share the full width equally child: Row( children: [ - Expanded( - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: [ - Text(AppSettings.instance.t('Shots'), - style: - const TextStyle(fontSize: 12, color: Colors.white60)), - const SizedBox(width: 8), - for (final n in sorted) ...[ - _BarPill( - label: '$n', - selected: n == selected, - empty: !formats.contains(n), - onTap: formats.contains(n) - ? () => setState(() => _shots = n) - : null), - const SizedBox(width: 6), - ], - ], - ), + 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) + ? () => setState(() => _shots = n) + : null), ), - ), - TextButton.icon( - style: TextButton.styleFrom(foregroundColor: Colors.white), - onPressed: _pickYear, - icon: const Icon(Icons.calendar_month_rounded, size: 18), - label: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text('$_year', - style: const TextStyle(fontWeight: FontWeight.w700)), - const Icon(Icons.expand_more_rounded, size: 18), - ], - ), - ), + ], ], ), ); } - // Up to 12 trainings: one point each. More: one point per month, so a busy year - // shows the trend instead of day-to-day noise. - List _chartPoints(List chronological) { - if (chronological.length <= _chartSessions) { - return [ - for (final x in chronological) - ChartPoint(DateFormat('d. M.').format(x.date), x.averagePerShot!), - ]; - } - final byMonth = >{}; - for (final x in chronological) { - byMonth.putIfAbsent(x.date.month, () => []).add(x); - } - return [ - for (final entry in byMonth.entries) - ChartPoint( - DateFormat('LLL', _locale) - .format(DateTime(_year, entry.key)) - .replaceAll('.', ''), - entry.value.fold(0, (sum, x) => sum + x.totalScore) / - entry.value.fold(0, (sum, x) => sum + x.shots), - ), - ]; + // 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}.'; } - Widget _buildSummary(List sessions, ShooterStats stats) { + // [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 labels, + List perShot, + List total + }) _chartData(List chronological) { + final groups = <(String, List)>[]; + 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 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 all, ShooterStats stats) { final s = AppSettings.instance; final surf = Surfaces.current; - final chartSessions = sessions - .where((x) => x.shots > 0) - .toList() - .reversed - .toList(); // oldest first - const divider = VerticalDivider(width: 1, color: Colors.white24); + final trend = stats.trend; + final bestSession = stats.bestSession; return ClipRRect( borderRadius: BorderRadius.circular(20), @@ -305,110 +391,211 @@ class _BookScreenState extends State with WidgetsBindingObserver { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - // Dark header: all four numbers in equal columns - Container( - color: AppTheme.bar, - padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 14), - child: IntrinsicHeight( - child: Row( - children: [ - Expanded( - child: _MiniStat( - label: s.t('Average per shot'), - value: stats.averagePerShot?.toStringAsFixed(2) ?? '–', + 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)), + ), + ], + ), ), - ), - divider, - Expanded( - child: _MiniStat( - label: s.t('Best target'), - value: '${stats.best!.score}', - ), - ), - divider, - Expanded( - child: _MiniStat( - label: s.t('Average target'), - value: stats.averageTarget!.toStringAsFixed(1), - ), - ), - divider, - Expanded( - child: _MiniStat( - label: s.t(_filter == _Filter.tournament - ? 'Tournaments' - : 'Trainings'), - value: '${stats.sessions}', + 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), ), ], - ), + ], ), ), - if (chartSessions.length > 1) - Padding( - padding: const EdgeInsets.fromLTRB(12, 12, 12, 12), - child: ProgressChart( - points: _chartPoints(chartSessions), - color: s.bulletColor, - textColor: surf.textSecondary, - gridColor: surf.divider, - ), - ), + Divider(height: 1, thickness: 1, color: surf.divider), + _buildChart(all, stats), ], ), ), ); } - List _buildHistory(List sessions) { + // Shot average and points per session, each on its own scale. + Widget _buildChart(List all, ShooterStats stats) { final s = AppSettings.instance; final surf = Surfaces.current; - final widgets = []; + 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); - String monthOf(Session x) => - DateFormat('LLLL yyyy', _locale).format(x.date).toUpperCase(); + // 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('.', '')); - if (_sortByScore) { - // Average per shot, so sessions with more targets don't win by volume - final ranked = [...sessions]..sort( - (a, b) => (b.averagePerShot ?? 0).compareTo(a.averagePerShot ?? 0)); - widgets.add(_sortBar(s.t('Best results').toUpperCase())); - widgets.addAll(ranked.map(_sessionCard)); - return widgets; - } + 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), + ); - String? month; - for (final session in sessions) { - final m = monthOf(session); - if (m != month) { - // The first month header shares its row with the sort toggle - widgets.add(month == null ? _sortBar(m) : _monthHeader(m)); - month = m; - } - widgets.add(_sessionCard(session)); - } - if (sessions.isEmpty) { - widgets.add(Padding( - padding: const EdgeInsets.all(24), - child: Text(s.t('No saved target data found'), - style: TextStyle(color: surf.textSecondary)), - )); - } - return widgets; + 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) => setState(() { + _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, + ), + ], + ], + ), + ); } - // Sort choice sits right above the list it sorts - Widget _sortBar(String title) { + List _buildHistory(List 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, 16, 0, 4), + padding: const EdgeInsets.fromLTRB(4, 12, 0, 4), child: Row( children: [ Expanded( child: Text( - title, + s.t(_sortByScore ? 'Best results' : 'History').toUpperCase(), style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, @@ -417,162 +604,146 @@ class _BookScreenState extends State with WidgetsBindingObserver { ), ), ), - SegmentedButton( - showSelectedIcon: false, - style: SegmentedButton.styleFrom( - visualDensity: VisualDensity.compact, - selectedBackgroundColor: s.bulletColor, - selectedForegroundColor: Colors.white, - foregroundColor: surf.textSecondary, - textStyle: - const TextStyle(fontSize: 12, fontWeight: FontWeight.w600), - ), - segments: [ - ButtonSegment( - value: false, - icon: const Icon(Icons.event_rounded, size: 16), - label: Text(s.t('Sort by Date'))), - ButtonSegment( - value: true, - icon: const Icon(Icons.leaderboard_rounded, size: 16), - label: Text(s.t('Sort by Score'))), - ], - selected: {_sortByScore}, - onSelectionChanged: (v) => setState(() => _sortByScore = v.first), + 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: () => setState(() => _sortByScore = !_sortByScore), ), ], ), ); } - Widget _monthHeader(String text) { - return Padding( - padding: const EdgeInsets.fromLTRB(4, 24, 4, 10), - child: Text( - text, - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - letterSpacing: 1.4, - color: Surfaces.current.textSecondary, - ), - ), - ); - } - - // Date block on the left like the calendar cards. Tap shows this session's - // targets of the selected format on one target; the menu opens details/edit. - Widget _sessionCard(Session session) { + // Date block left; average per shot right, 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: 10), - child: Container( - decoration: BoxDecoration( - color: surf.card, - borderRadius: BorderRadius.circular(12), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.15), - blurRadius: 6, - offset: const Offset(0, 2)) - ], - ), + padding: const EdgeInsets.only(bottom: 8), + child: Material( + color: surf.card, + borderRadius: BorderRadius.circular(12), clipBehavior: Clip.antiAlias, - child: IntrinsicHeight( - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _DateBlock( - date: session.date, color: s.bulletColor, locale: _locale), - Expanded( - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: () => _openTargets(session), - onLongPress: () => _openDetails(session), - child: Padding( - padding: const EdgeInsets.fromLTRB(14, 12, 4, 12), - child: Row( - children: [ - Expanded( - child: Column( - 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: 16, - fontWeight: FontWeight.w700, - color: surf.textPrimary), - ), - ), - ], - ), - const SizedBox(height: 4), - Text( - [ - targetCount(session.targets.length), - if (avg != null) - '${avg.toStringAsFixed(2)} / ${s.t('shot')}', - ].join(' · '), - style: TextStyle( - fontSize: 12, color: surf.textSecondary), - ), - ], + 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), + ), ), - ), - Text( - '${session.totalScore}', - style: TextStyle( - fontSize: 22, - fontWeight: FontWeight.w800, - color: surf.textPrimary), - ), - ], - ), + ], + ), + const SizedBox(height: 3), + Text( + '${targetCount(session.targets.length)} · ${s.t('Total').toLowerCase()} ${session.totalScore}', + style: TextStyle( + fontSize: 12, color: surf.textSecondary), + ), + ], ), ), ), - ), - IconButton( - tooltip: s.t('Details'), - icon: Icon(Icons.more_vert_rounded, color: surf.textSecondary), - onPressed: () => _openDetails(session), - ), - ], + Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + avg?.toStringAsFixed(2) ?? '–', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w800, + color: surf.textPrimary), + ), + if (delta != null) + Text(_signed(delta), + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: _deltaColor(delta))), + ], + ), + ), + IconButton( + tooltip: s.t('Details'), + visualDensity: VisualDensity.compact, + icon: + Icon(Icons.more_vert_rounded, color: surf.textSecondary), + onPressed: () => _openDetails(session), + ), + ], + ), ), ), ), ); } - Future _openTargets(Session session) async { - if (session.targets.isEmpty) return; + Future _openFiles(List files, {required bool combined}) async { await Navigator.push( context, MaterialPageRoute( builder: (_) => TargetViewScreen( - jsonFiles: session.files, - refreshFolders: _load, - isCombinedView: true), + jsonFiles: files, refreshFolders: _load, isCombinedView: combined), ), ); _load(); } + Future _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; @@ -618,16 +789,24 @@ void showBookHelp(BuildContext context) { 'Shots 1–5: statistics only compare targets with the same number of shots. Grey numbers have no targets yet.' ), ( - Icons.calendar_month_rounded, - 'Year (top right): choose which year to show.' + Icons.trending_up_rounded, + 'Arrow under the average: your last 5 sessions compared with the 5 before them.' ), ( Icons.show_chart_rounded, - 'Graph: average per shot over time. Tap or drag on it to see each value.' + '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.leaderboard_rounded, - 'By date / By score: sort the list by date or by best average per shot.' + 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, @@ -640,32 +819,93 @@ void showBookHelp(BuildContext context) { ]); } -class _MiniStat extends StatelessWidget { - final String label; +/// "12 Trainings" line on the hero, value first. +class _HeroCount extends StatelessWidget { final String value; + final String label; - const _MiniStat({required this.label, required this.value}); + const _HeroCount({required this.value, required this.label}); - // White on the dark header; labels get two lines since four share the width @override Widget build(BuildContext context) { + final surf = Surfaces.current; return Padding( - padding: const EdgeInsets.symmetric(horizontal: 4), - child: Column( - children: [ - Text(value, - style: const TextStyle( - fontSize: 24, + padding: const EdgeInsets.only(top: 2), + child: Text.rich( + TextSpan(children: [ + TextSpan( + text: value, + style: TextStyle( + fontSize: 15, fontWeight: FontWeight.w800, - color: Colors.white)), - const SizedBox(height: 2), - Text(label, - textAlign: TextAlign.center, - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - fontSize: 11, color: Colors.white60, height: 1.2)), - ], + 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), + ], + ), + ), ), ); } @@ -715,6 +955,66 @@ class _DateBlock extends StatelessWidget { } } +/// 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 labels; + final int selected; + final Color color; + final ValueChanged 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), + ), + ), + ), + ), + ), + ], + ), + ); + } +} + /// Small pill on the dark bar: white when selected, outlined otherwise. class _BarPill extends StatelessWidget { final String label; @@ -738,9 +1038,10 @@ class _BarPill extends StatelessWidget { customBorder: const StadiumBorder(), onTap: onTap, child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6), + padding: const EdgeInsets.symmetric(vertical: 6), child: Text( label, + textAlign: TextAlign.center, style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, diff --git a/lib/services/target_repository.dart b/lib/services/target_repository.dart index 9c6b803..5c401fb 100644 --- a/lib/services/target_repository.dart +++ b/lib/services/target_repository.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:io'; +import 'dart:math'; import 'package:path_provider/path_provider.dart'; /// One saved target (a JSON file written by the preview screen). @@ -45,42 +46,74 @@ class Session { /// Aggregates over any set of sessions (trainings or tournaments of one format). class ShooterStats { + static const int trendWindow = 5; + final int sessions; final int targets; final int shots; - final TargetRecord? best; + final Session? bestSession; // highest average per shot final double? averageTarget; final double? averagePerShot; + final double? trend; // last sessions minus the ones before them, per shot const ShooterStats._({ required this.sessions, required this.targets, required this.shots, - required this.best, + required this.bestSession, required this.averageTarget, required this.averagePerShot, + required this.trend, }); + /// [sessions] newest first, as [TargetRepository.loadSessions] returns them. factory ShooterStats.of(List sessions) { final all = [for (final s in sessions) ...s.targets]; final shots = all.fold(0, (sum, t) => sum + t.shots); final total = all.fold(0, (sum, t) => sum + t.score); - final ranked = [...all]..sort((a, b) => b.score.compareTo(a.score)); final mean = all.isEmpty ? null : total / all.length; + Session? bestSession; + for (final s in sessions) { + final avg = s.averagePerShot; + if (avg != null && + (bestSession == null || avg > bestSession.averagePerShot!)) { + bestSession = s; + } + } + return ShooterStats._( sessions: sessions.length, targets: all.length, shots: shots, - best: ranked.isEmpty ? null : ranked.first, + bestSession: bestSession, averageTarget: mean, averagePerShot: shots == 0 ? null : total / shots, + trend: _trend(sessions), ); } + + // Average per shot of the newest sessions minus the same number before them + static double? _trend(List newestFirst) { + final scored = newestFirst.where((s) => s.shots > 0).toList(); + final n = min(trendWindow, scored.length ~/ 2); + if (n == 0) return null; + double avg(Iterable list) => + list.fold(0, (a, s) => a + s.totalScore) / + list.fold(0, (a, s) => a + s.shots); + return avg(scored.take(n)) - avg(scored.skip(n).take(n)); + } } /// Reads and edits the saved targets under /saved_images//. +/// +/// Score and shots of every target are cached in /target_index.json, +/// keyed by the file's path with its size and last change, so loading reads one +/// file instead of every target. A new, edited or renamed target no longer +/// matches its entry and is read again; entries of deleted files are dropped. class TargetRepository { + static Map? _index; // path in saved_images -> entry + static Future _root() async { final dir = Directory( '${(await getApplicationDocumentsDirectory()).path}/saved_images'); @@ -88,15 +121,56 @@ class TargetRepository { return dir; } - /// Sessions, newest first. With [year], only that year's target files are read. - static Future> loadSessions({int? year}) async { + static Future _indexFile() async => File( + '${(await getApplicationDocumentsDirectory()).path}/target_index.json'); + + static Future> _loadIndex() async { + if (_index != null) return _index!; + try { + final file = await _indexFile(); + _index = await file.exists() + ? jsonDecode(await file.readAsString()) as Map + : {}; + } catch (_) { + _index = {}; // unreadable: rebuild it from the targets + } + return _index!; + } + + /// Sessions, newest first. + static Future> loadSessions() async { final sessions = []; + final index = await _loadIndex(); + final seen = {}; + var changed = false; for (final folder in await _folders()) { - if (year != null && folder.date.year != year) continue; final targets = []; for (final file in folder.targetFiles) { - final record = await _readTarget(file); + final key = '${folder.name}/${file.uri.pathSegments.last}'; + seen.add(key); + final stat = file.statSync(); + final stamp = '${stat.size}:${stat.modified.millisecondsSinceEpoch}'; + final cached = index[key]; + TargetRecord? record; + if (cached is Map && cached['stamp'] == stamp) { + record = TargetRecord( + file: file, + shotAt: _timeFromFileName(file) ?? stat.modified, + score: cached['score'] as int, + shots: cached['shots'] as int, + ); + } else { + record = await _readTarget(file); + if (record != null) { + index[key] = { + 'stamp': stamp, + 'score': record.score, + 'shots': record.shots + }; + changed = true; + } + } if (record != null) targets.add(record); } targets.sort((a, b) => a.shotAt.compareTo(b.shotAt)); @@ -108,16 +182,20 @@ class TargetRepository { )); } + final before = index.length; + index.removeWhere((key, _) => !seen.contains(key)); + if (changed || index.length != before) { + try { + await (await _indexFile()).writeAsString(jsonEncode(index)); + } catch (_) { + // Only a cache: the next load reads the targets again + } + } + sessions.sort((a, b) => b.date.compareTo(a.date)); return sessions; } - /// Years that have at least one session, newest first. Reads only metadata. - static Future> years() async { - final years = {for (final f in await _folders()) f.date.year}.toList(); - return years..sort((a, b) => b.compareTo(a)); - } - // Cheap pass over the folders: metadata + file names, no target files read static Future> _folders() async { final root = await _root(); @@ -128,12 +206,15 @@ class TargetRepository { for (final f in folder.listSync().whereType()) if (f.path.endsWith('.json') && !f.path.endsWith('metadata.json')) f, ]; - final fileTimes = files.map(_timeFromFileName).whereType().toList()..sort(); + final fileTimes = + files.map(_timeFromFileName).whereType().toList()..sort(); result.add(_FolderInfo( name: folder.path.split('/').last, isTournament: meta['isTournament'] == true, date: DateTime.tryParse(meta['createdAt'] ?? '') ?? - (fileTimes.isNotEmpty ? fileTimes.first : folder.statSync().changed), + (fileTimes.isNotEmpty + ? fileTimes.first + : folder.statSync().changed), targetFiles: files, )); } @@ -213,5 +294,9 @@ class _FolderInfo { final DateTime date; final List targetFiles; - const _FolderInfo({required this.name, required this.isTournament, required this.date, required this.targetFiles}); + const _FolderInfo( + {required this.name, + required this.isTournament, + required this.date, + required this.targetFiles}); } diff --git a/lib/utils/translations.dart b/lib/utils/translations.dart index c31af79..6c6e60e 100644 --- a/lib/utils/translations.dart +++ b/lib/utils/translations.dart @@ -1217,18 +1217,6 @@ class AppTranslations { 'English': 'Shots 1–5: statistics only compare targets with the same number of shots. Grey numbers have no targets yet.', 'Slovenian': 'Streli 1–5: statistika primerja le tarče z enakim številom strelov. Sive številke še nimajo tarč.', }, - 'Year (top right): choose which year to show.': { - 'English': 'Year (top right): choose which year to show.', - 'Slovenian': 'Leto (desno zgoraj): izberi, katero leto se prikaže.', - }, - 'Graph: average per shot over time. Tap or drag on it to see each value.': { - 'English': 'Graph: average per shot over time. Tap or drag on it to see each value.', - 'Slovenian': 'Graf: povprečje na strel skozi čas. Tapni ali povleci po njem za posamezno vrednost.', - }, - 'By date / By score: sort the list by date or by best average per shot.': { - 'English': 'By date / By score: sort the list by date or by best average per shot.', - 'Slovenian': 'Po datumu / Po rezultatu: razvrsti seznam po datumu ali po najboljšem povprečju na strel.', - }, 'Tap a session to see all its targets with the selected number of shots on one target.': { 'English': 'Tap a session to see all its targets with the selected number of shots on one target.', 'Slovenian': 'Tapni sejo za prikaz vseh njenih tarč z izbranim številom strelov na eni tarči.', @@ -1237,6 +1225,75 @@ class AppTranslations { 'English': 'Three dots on the right or long press: session details, single targets, rename and delete.', 'Slovenian': 'Tri pike na desni ali dolg pritisk: podrobnosti seje, posamezne tarče, preimenovanje in brisanje.', }, + // Knjiga form sections + 'Shot average': { + 'English': 'Shot average', + 'Slovenian': 'Povprečje strela', + }, + 'Number of points': { + 'English': 'Number of points', + 'Slovenian': 'Število točk', + }, + '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.': { + 'English': '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.', + 'Slovenian': 'Graf: povprečje strela (leva os) in število točk (desna os). Mesec prikaže vsako sejo meseca, Leto eno točko na mesec; s puščicami greš nazaj po mesecih ali letih. Tapni ali povleci po njem za vrednosti.', + }, + '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.': { + 'English': '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.', + 'Slovenian': 'Obdobje (zraven Zgodovine): ta mesec, zadnji 3 meseci, to leto, vse ali svoji datumi. Uporabljata ga zgornja kartica in seznam.', + }, + 'Period': { + 'English': 'Period', + 'Slovenian': 'Obdobje', + }, + 'This month': { + 'English': 'This month', + 'Slovenian': 'Ta mesec', + }, + 'Last 3 months': { + 'English': 'Last 3 months', + 'Slovenian': 'Zadnji 3 meseci', + }, + 'This year': { + 'English': 'This year', + 'Slovenian': 'To leto', + }, + 'Custom range': { + 'English': 'Custom range', + 'Slovenian': 'Po meri', + }, + 'No sessions in this period': { + 'English': 'No sessions in this period', + 'Slovenian': 'V tem obdobju ni sej', + }, + 'Month': { + 'English': 'Month', + 'Slovenian': 'Mesec', + }, + 'Best training / tournament in the top card: tap to open its targets.': { + 'English': 'Best training / tournament in the top card: tap to open its targets.', + 'Slovenian': 'Najboljši trening / tekmovanje v zgornji kartici: tapni za prikaz njegovih tarč.', + }, + 'vs earlier': { + 'English': 'vs earlier', + 'Slovenian': 'glede na prej', + }, + 'Best training': { + 'English': 'Best training', + 'Slovenian': 'Najboljši trening', + }, + 'Best tournament': { + 'English': 'Best tournament', + 'Slovenian': 'Najboljše tekmovanje', + }, + 'Arrow under the average: your last 5 sessions compared with the 5 before them.': { + 'English': 'Arrow under the average: your last 5 sessions compared with the 5 before them.', + 'Slovenian': 'Puščica pod povprečjem: tvojih zadnjih 5 sej v primerjavi s 5 pred njimi.', + }, + '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.': { + 'English': '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.', + 'Slovenian': 'Ikona razvrščanja: tapni za preklop med vrstnim redom po datumu in po najboljšem povprečju na strel. Barvna številka pokaže, koliko seja odstopa od tvojega povprečja.', + }, 'Year': { 'English': 'Year', 'Slovenian': 'Leto', diff --git a/lib/widgets/progress_chart.dart b/lib/widgets/progress_chart.dart index 6015e46..572dde1 100644 --- a/lib/widgets/progress_chart.dart +++ b/lib/widgets/progress_chart.dart @@ -1,24 +1,36 @@ +import 'dart:math'; import 'package:flutter/material.dart'; -class ChartPoint { - final String label; // shown in the tooltip and under the first/last point - final double value; +enum ChartAxis { left, right, none } - const ChartPoint(this.label, this.value); +/// One line on the chart. Each series has its own scale, so values of very +/// different size (average per shot vs. session total) can share the chart. +/// [axis] says which side labels its scale. +class ChartSeries { + final String name; + final Color color; + final List values; // one per label + final int decimals; + final ChartAxis axis; + + const ChartSeries(this.name, this.color, this.values, + {this.decimals = 2, this.axis = ChartAxis.none}); + + String format(double v) => v.toStringAsFixed(decimals); } -/// Single-series line chart: 2px line, 8px points, three faint gridlines. -/// Tap (or drag) to show the nearest point's label and value. +/// Line chart: 2px lines, 8px points, three faint gridlines, up to one labelled +/// axis per side. Tap (or drag) to show every series' value at the nearest point. class ProgressChart extends StatefulWidget { - final List points; - final Color color; + final List labels; // shown in the tooltip and under the first/last point + final List series; // legend and tooltip order final Color textColor; final Color gridColor; const ProgressChart({ super.key, - required this.points, - required this.color, + required this.labels, + required this.series, required this.textColor, required this.gridColor, }); @@ -31,120 +43,180 @@ class _ProgressChartState extends State { int? _selected; void _select(Offset position, Size size) { - final n = widget.points.length; + final n = widget.labels.length; if (n == 0) return; - final plotWidth = size.width - _ChartPainter.leftAxis - _ChartPainter.pad * 2; - final x = (position.dx - _ChartPainter.leftAxis - _ChartPainter.pad) / plotWidth; + final plot = _ChartPainter.plotRect(size); + final x = (position.dx - plot.left) / plot.width; setState(() => _selected = (x * (n - 1)).round().clamp(0, n - 1)); } @override Widget build(BuildContext context) { - return LayoutBuilder( - builder: (context, constraints) { - final size = Size(constraints.maxWidth, 170); - return GestureDetector( - behavior: HitTestBehavior.opaque, - onTapDown: (d) => _select(d.localPosition, size), - onHorizontalDragUpdate: (d) => _select(d.localPosition, size), - child: CustomPaint( - size: size, - painter: _ChartPainter( - points: widget.points, - color: widget.color, - textColor: widget.textColor, - gridColor: widget.gridColor, - selected: _selected, - ), - ), - ); - }, + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + LayoutBuilder( + builder: (context, constraints) { + final size = Size(constraints.maxWidth, 190); + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTapDown: (d) => _select(d.localPosition, size), + onHorizontalDragUpdate: (d) => _select(d.localPosition, size), + child: CustomPaint( + size: size, + painter: _ChartPainter( + labels: widget.labels, + series: widget.series, + textColor: widget.textColor, + gridColor: widget.gridColor, + selected: _selected, + ), + ), + ); + }, + ), + const SizedBox(height: 8), + // Legend, centred under the graph + Wrap( + alignment: WrapAlignment.center, + spacing: 16, + runSpacing: 4, + children: [ + for (final s in widget.series) + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 14, + height: 3, + decoration: BoxDecoration(color: s.color, borderRadius: BorderRadius.circular(2)), + ), + const SizedBox(width: 6), + Text(s.name, style: TextStyle(fontSize: 12, color: widget.textColor)), + ], + ), + ], + ), + ], ); } } class _ChartPainter extends CustomPainter { - static const double leftAxis = 32; // room for y labels + static const double axis = 34; // room for y labels on each side static const double pad = 10; // keeps end points inside the plot static const double top = 34; // room for the tooltip static const double bottom = 20; // room for x labels - final List points; - final Color color; + static Rect plotRect(Size size) => + Rect.fromLTRB(axis + pad, top, size.width - axis - pad, size.height - bottom); + + final List labels; + final List series; final Color textColor; final Color gridColor; final int? selected; _ChartPainter({ - required this.points, - required this.color, + required this.labels, + required this.series, required this.textColor, required this.gridColor, required this.selected, }); + // Min and max of a series, widened so a flat line sits in the middle + static (double, double) _range(List values, double minSpan) { + var lo = values.reduce(min); + var hi = values.reduce(max); + if (hi - lo < minSpan) { + final mid = (hi + lo) / 2; + lo = mid - minSpan / 2; + hi = mid + minSpan / 2; + } + return (lo, hi); + } + @override void paint(Canvas canvas, Size size) { - if (points.isEmpty) return; - final values = points.map((p) => p.value); - var minV = values.reduce((a, b) => a < b ? a : b); - var maxV = values.reduce((a, b) => a > b ? a : b); - if (maxV - minV < 1) { - minV -= 0.5; - maxV += 0.5; - } - final plot = Rect.fromLTRB(leftAxis + pad, top, size.width - pad, size.height - bottom); + if (labels.isEmpty || series.isEmpty) return; + final plot = plotRect(size); + final n = labels.length; + final ranges = [ + for (final s in series) _range(s.values, s.values.reduce(max).abs() * 0.1 + 0.2), + ]; - Offset at(int i) => Offset( - points.length == 1 ? plot.center.dx : plot.left + plot.width * i / (points.length - 1), - plot.bottom - plot.height * (points[i].value - minV) / (maxV - minV), - ); + double xAt(int i) => n == 1 ? plot.center.dx : plot.left + plot.width * i / (n - 1); + double yAt(double v, (double, double) r) => plot.bottom - plot.height * (v - r.$1) / (r.$2 - r.$1); - // Gridlines + y labels (min, mid, max) + // Gridlines + y labels in each axis series' colour final grid = Paint() ..color = gridColor ..strokeWidth = 1; for (final f in [0.0, 0.5, 1.0]) { final y = plot.bottom - plot.height * f; - canvas.drawLine(Offset(leftAxis, y), Offset(size.width, y), grid); - _text(canvas, (minV + (maxV - minV) * f).toStringAsFixed(1), Offset(0, y - 7), 11, textColor); + canvas.drawLine(Offset(axis, y), Offset(size.width - axis, y), grid); + for (int k = 0; k < series.length; k++) { + if (series[k].axis == ChartAxis.none) continue; + final right = series[k].axis == ChartAxis.right; + final r = ranges[k]; + final v = r.$1 + (r.$2 - r.$1) * f; + final text = series[k].decimals == 0 ? v.round().toString() : v.toStringAsFixed(1); + _text(canvas, text, Offset(right ? size.width : 0, y - 7), 11, series[k].color, alignRight: right); + } } // x labels: first and last only - _text(canvas, points.first.label, Offset(plot.left - pad, plot.bottom + 5), 11, textColor); - if (points.length > 1) { - _text(canvas, points.last.label, Offset(plot.right, plot.bottom + 5), 11, textColor, alignRight: true); + _text(canvas, labels.first, Offset(plot.left - pad, plot.bottom + 5), 11, textColor); + if (n > 1) { + _text(canvas, labels.last, Offset(plot.right + pad, plot.bottom + 5), 11, textColor, alignRight: true); } - // Line - final path = Path()..moveTo(at(0).dx, at(0).dy); - for (int i = 1; i < points.length; i++) { - path.lineTo(at(i).dx, at(i).dy); - } - canvas.drawPath( - path, - Paint() - ..color = color - ..strokeWidth = 2 - ..style = PaintingStyle.stroke - ..strokeJoin = StrokeJoin.round, - ); - - // Points with a surface ring so they read on top of the line - for (int i = 0; i < points.length; i++) { - final isSel = i == selected; - canvas.drawCircle(at(i), isSel ? 7 : 5, Paint()..color = Colors.white); - canvas.drawCircle(at(i), isSel ? 5.5 : 4, Paint()..color = color); + // Lines, last series first so the main one stays on top + for (int k = series.length - 1; k >= 0; k--) { + final s = series[k]; + final r = ranges[k]; + final path = Path()..moveTo(xAt(0), yAt(s.values[0], r)); + for (int i = 1; i < n; i++) { + path.lineTo(xAt(i), yAt(s.values[i], r)); + } + canvas.drawPath( + path, + Paint() + ..color = s.color + ..strokeWidth = 2 + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round, + ); + // Points with a surface ring so they read on top of the line + for (int i = 0; i < n; i++) { + final isSel = i == selected; + final p = Offset(xAt(i), yAt(s.values[i], r)); + canvas.drawCircle(p, isSel ? 6 : 4.5, Paint()..color = Colors.white); + canvas.drawCircle(p, isSel ? 4.5 : 3.5, Paint()..color = s.color); + } } - // Tooltip for the selected point + // Tooltip for the selected point: label, then each value in its colour if (selected != null) { - final p = at(selected!); - canvas.drawLine(Offset(p.dx, plot.top), Offset(p.dx, plot.bottom), grid); - final label = '${points[selected!].label} ${points[selected!].value.toStringAsFixed(2)}'; - final tp = _layout(label, 12, Colors.white, bold: true); + final i = selected!; + canvas.drawLine(Offset(xAt(i), plot.top), Offset(xAt(i), plot.bottom), grid); + final tp = TextPainter( + text: TextSpan( + style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.white), + children: [ + TextSpan(text: labels[i]), + for (final s in series) + TextSpan( + text: ' ${s.format(s.values[i])}', + style: TextStyle(color: Color.lerp(s.color, Colors.white, 0.35)), + ), + ], + ), + textDirection: TextDirection.ltr, + )..layout(maxWidth: size.width - 16); final w = tp.width + 16; - final left = (p.dx - w / 2).clamp(0.0, size.width - w); + final left = (xAt(i) - w / 2).clamp(0.0, size.width - w); canvas.drawRRect( RRect.fromRectAndRadius(Rect.fromLTWH(left, 2, w, 24), const Radius.circular(6)), Paint()..color = Colors.grey[900]!, @@ -153,22 +225,18 @@ class _ChartPainter extends CustomPainter { } } - TextPainter _layout(String text, double size, Color color, {bool bold = false}) { - return TextPainter( - text: TextSpan( - text: text, - style: TextStyle(fontSize: size, color: color, fontWeight: bold ? FontWeight.w600 : FontWeight.normal), - ), + void _text(Canvas canvas, String text, Offset at, double size, Color color, {bool alignRight = false}) { + final tp = TextPainter( + text: TextSpan(text: text, style: TextStyle(fontSize: size, color: color)), textDirection: TextDirection.ltr, )..layout(); - } - - void _text(Canvas canvas, String text, Offset at, double size, Color color, {bool alignRight = false}) { - final tp = _layout(text, size, color); tp.paint(canvas, alignRight ? at.translate(-tp.width, 0) : at); } @override bool shouldRepaint(_ChartPainter old) => - old.points != points || old.selected != selected || old.color != color || old.textColor != textColor; + old.labels != labels || + old.series != series || + old.selected != selected || + old.textColor != textColor; }