Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Let you run daily, weekly and monthly listening goals at the same time

Barnabas2ca260c0658e
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 36fc4df2..e7d799e5 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -149,8 +149,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _useColorEverywhere = false;
String _language = '';
int _startScreen = 2;
- String _statsGoalType = 'off';
- int _statsGoalMinutes = 30;
+ final Map<String, int> _statsGoalMinutes = {
+ for (final p in PlayerSettings.statsGoalPeriods) p: 0
+ };
int _statsBookGoal = 0;
String _statsChartStyle = 'bar';
int _statsChartRange = 7;
@@ -466,9 +467,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
width: 72,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
- child: Text(value,
- textAlign: TextAlign.center,
- style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w700)),
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text(value,
+ maxLines: 1,
+ textAlign: TextAlign.center,
+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w700)),
+ ),
),
),
),
@@ -487,8 +492,37 @@ class _SettingsScreenState extends State<SettingsScreen> {
return h > 0 ? l.statsScreenDurationHm(h, m) : l.statsScreenDurationM(m);
}
+ /// Stepper granularity, scaled so the longer periods aren't hundreds of taps
+ /// wide. Tapping the value still takes an exact number.
+ int _statsGoalStepMinutes(String period) => switch (period) {
+ 'weekly' => 30,
+ 'monthly' => 60,
+ _ => 5,
+ };
+
+ String _statsGoalLabel(AppLocalizations l, String period) => switch (period) {
+ 'weekly' => l.statsGoalWeekly,
+ 'monthly' => l.statsGoalMonthly,
+ _ => l.statsGoalDaily,
+ };
+
+ Widget _statsGoalRow(
+ ColorScheme cs, TextTheme tt, AppLocalizations l, String period) {
+ final minutes = _statsGoalMinutes[period]!;
+ final step = _statsGoalStepMinutes(period);
+ final max = PlayerSettings.maxStatsGoalMinutes(period);
+ return _statsStepperRow(
+ cs, tt, _statsGoalLabel(l, period), _statsMinutesLabel(l, minutes),
+ onTapValue: () => _editStatsTimeTarget(period),
+ onMinus: minutes > step
+ ? () => _setStatsGoalMinutes(period, minutes - step)
+ : null,
+ onPlus:
+ minutes < max ? () => _setStatsGoalMinutes(period, minutes + step) : null);
+ }
+
/// Accepts plain minutes ("90") or h:mm ("1:30").
- int? _parseGoalMinutes(String input) {
+ int? _parseGoalMinutes(String input, String period) {
final t = input.trim();
if (t.isEmpty) return null;
int? minutes;
@@ -503,7 +537,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
minutes = int.tryParse(t);
}
if (minutes == null || minutes < 1) return null;
- return minutes.clamp(1, 1440);
+ return minutes.clamp(1, PlayerSettings.maxStatsGoalMinutes(period));
}
Future<String?> _promptStatsValue(String hint, TextInputType keyboard) async {
@@ -528,14 +562,28 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
- Future<void> _editStatsTimeTarget() async {
+ Future<void> _editStatsTimeTarget(String period) async {
final l = AppLocalizations.of(context)!;
final input = await _promptStatsValue(l.statsGoalEnterTimeHint, TextInputType.datetime);
if (input == null) return;
- final minutes = _parseGoalMinutes(input);
+ final minutes = _parseGoalMinutes(input, period);
if (minutes == null) return;
- setState(() => _statsGoalMinutes = minutes);
- PlayerSettings.setStatsGoalMinutes(minutes);
+ _setStatsGoalMinutes(period, minutes);
+ }
+
+ void _setStatsGoalMinutes(String period, int minutes) {
+ final clamped = minutes.clamp(0, PlayerSettings.maxStatsGoalMinutes(period));
+ setState(() => _statsGoalMinutes[period] = clamped);
+ PlayerSettings.setStatsGoalMinutesFor(period, clamped);
+ }
+
+ /// Switching a period on reinstates whatever target it last held, so the
+ /// stored value has to come back from the store rather than being assumed.
+ Future<void> _toggleStatsGoal(String period, bool on) async {
+ await PlayerSettings.setStatsGoalEnabled(period, on);
+ final minutes = await PlayerSettings.getStatsGoalMinutesFor(period);
+ if (!mounted) return;
+ setState(() => _statsGoalMinutes[period] = minutes);
}
Future<void> _editStatsBookTarget() async {
@@ -781,8 +829,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
final manualSeed = await PlayerSettings.getManualSeedColor();
final gradientIntensity = await PlayerSettings.getGradientIntensity();
final useColorEverywhere = await PlayerSettings.getUseColorEverywhere();
- final statsGoalType = await PlayerSettings.getStatsGoalType();
- final statsGoalMinutes = await PlayerSettings.getStatsGoalMinutes();
+ final statsGoalMinutes = <String, int>{
+ for (final p in PlayerSettings.statsGoalPeriods)
+ p: await PlayerSettings.getStatsGoalMinutesFor(p)
+ };
final statsBookGoal = await PlayerSettings.getStatsBookGoal();
final statsChartStyle = await PlayerSettings.getStatsChartStyle();
final statsChartRange = await PlayerSettings.getStatsChartRange();
@@ -928,8 +978,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
_shakeSensitivity = shakeSens;
_language = language;
_canPickDownloadLocation = true;
- _statsGoalType = statsGoalType;
- _statsGoalMinutes = statsGoalMinutes;
+ _statsGoalMinutes
+ ..clear()
+ ..addAll(statsGoalMinutes);
_statsBookGoal = statsBookGoal;
_statsChartStyle = statsChartStyle;
_statsChartRange = statsChartRange;
@@ -1744,36 +1795,39 @@ class _SettingsScreenState extends State<SettingsScreen> {
width: double.infinity,
child: SegmentedButton<String>(
showSelectedIcon: false,
+ multiSelectionEnabled: true,
+ emptySelectionAllowed: true,
segments: [
- ButtonSegment(value: 'off', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsGoalOff, maxLines: 1))),
- ButtonSegment(value: 'daily', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsGoalDaily, maxLines: 1))),
- ButtonSegment(value: 'weekly', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsGoalWeekly, maxLines: 1))),
- ButtonSegment(value: 'monthly', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsGoalMonthly, maxLines: 1))),
+ for (final p in PlayerSettings.statsGoalPeriods)
+ ButtonSegment(
+ value: p,
+ label: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text(_statsGoalLabel(l, p), maxLines: 1))),
],
- selected: {_statsGoalType},
+ selected: {
+ for (final e in _statsGoalMinutes.entries)
+ if (e.value > 0) e.key
+ },
onSelectionChanged: _loaded ? (selected) {
- setState(() => _statsGoalType = selected.first);
- PlayerSettings.setStatsGoalType(_statsGoalType);
+ for (final p in PlayerSettings.statsGoalPeriods) {
+ final on = selected.contains(p);
+ if (on == (_statsGoalMinutes[p]! > 0)) continue;
+ _toggleStatsGoal(p, on);
+ }
} : null,
style: const ButtonStyle(visualDensity: VisualDensity.compact),
),
),
- if (_statsGoalType != 'off')
- _statsStepperRow(cs, tt, l.statsGoalTarget,
- _statsMinutesLabel(l, _statsGoalMinutes),
- onTapValue: _editStatsTimeTarget,
- onMinus: _statsGoalMinutes > 5
- ? () {
- setState(() => _statsGoalMinutes -= 5);
- PlayerSettings.setStatsGoalMinutes(_statsGoalMinutes);
- }
- : null,
- onPlus: _statsGoalMinutes < 600
- ? () {
- setState(() => _statsGoalMinutes += 5);
- PlayerSettings.setStatsGoalMinutes(_statsGoalMinutes);
- }
- : null),
+ if (_statsGoalMinutes.values.every((m) => m == 0))
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Text(l.statsGoalOff,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ for (final p in PlayerSettings.statsGoalPeriods)
+ if (_statsGoalMinutes[p]! > 0)
+ _statsGoalRow(cs, tt, l, p),
],
),
),
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
index 2481f704..4fe93634 100644
--- a/lib/screens/stats_screen.dart
+++ b/lib/screens/stats_screen.dart
@@ -34,8 +34,9 @@ class _StatsScreenState extends State<StatsScreen>
int _episodesFinished = 0;
int _booksFinishedThisYear = 0;
int _episodesFinishedThisYear = 0;
- String _goalType = 'off';
- int _goalMinutes = 30;
+ final Map<String, int> _goalMinutes = {
+ for (final p in PlayerSettings.statsGoalPeriods) p: 0
+ };
int _bookGoal = 0;
String _chartStyle = 'bar';
int _chartRange = 7;
@@ -125,8 +126,10 @@ class _StatsScreenState extends State<StatsScreen>
void _onSettingsChanged() => _loadGoalSettings();
Future<void> _loadGoalSettings() async {
- final type = await PlayerSettings.getStatsGoalType();
- final minutes = await PlayerSettings.getStatsGoalMinutes();
+ final minutes = <String, int>{
+ for (final p in PlayerSettings.statsGoalPeriods)
+ p: await PlayerSettings.getStatsGoalMinutesFor(p)
+ };
final books = await PlayerSettings.getStatsBookGoal();
final chartStyle = await PlayerSettings.getStatsChartStyle();
final chartRange = await PlayerSettings.getStatsChartRange();
@@ -140,8 +143,9 @@ class _StatsScreenState extends State<StatsScreen>
_selectedDayKey = null;
_selectedSection = null;
}
- _goalType = type;
- _goalMinutes = minutes;
+ _goalMinutes
+ ..clear()
+ ..addAll(minutes);
_bookGoal = books;
_chartStyle = chartStyle;
_chartRange = chartRange;
@@ -475,7 +479,7 @@ class _StatsScreenState extends State<StatsScreen>
const SizedBox(height: 16),
],
'goals': [
- if (_goalType != 'off' || _bookGoal > 0) ...[
+ if (_goalMinutes.values.any((m) => m > 0) || _bookGoal > 0) ...[
_goalCard(cs, tt, l, today, thisWeek, thisMonth),
const SizedBox(height: 16),
],
@@ -990,28 +994,74 @@ class _StatsScreenState extends State<StatsScreen>
// --- GOAL CARD ---
+ Widget _timeGoalRow(ColorScheme cs, TextTheme tt, AppLocalizations l,
+ String period, double elapsedSeconds, double ringSize, Color doneColor) {
+ final targetSeconds = _goalMinutes[period]! * 60.0;
+ final progress = targetSeconds > 0
+ ? (elapsedSeconds / targetSeconds).clamp(0.0, 1.0).toDouble()
+ : 0.0;
+ final reached = targetSeconds > 0 && elapsedSeconds >= targetSeconds;
+ final label = switch (period) {
+ 'weekly' => l.statsWeeklyGoal,
+ 'monthly' => l.statsMonthlyGoal,
+ _ => l.statsDailyGoal,
+ };
+ final big = ringSize >= 56;
+ return Row(children: [
+ SizedBox(
+ width: ringSize,
+ height: ringSize,
+ child: Stack(alignment: Alignment.center, children: [
+ SizedBox(
+ width: ringSize,
+ height: ringSize,
+ child: CircularProgressIndicator(
+ value: progress,
+ strokeWidth: big ? 5 : 4,
+ backgroundColor: cs.onSurface.withValues(alpha: 0.08),
+ valueColor: AlwaysStoppedAnimation(reached ? doneColor : cs.primary),
+ ),
+ ),
+ if (reached)
+ Icon(Icons.check_rounded, color: doneColor, size: ringSize * 0.43)
+ else
+ Text('${(progress * 100).round()}%',
+ style: (big ? tt.labelMedium : tt.labelSmall)
+ ?.copyWith(fontWeight: FontWeight.w700, color: cs.onSurface)),
+ ]),
+ ),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(label,
+ style: tt.titleSmall
+ ?.copyWith(fontWeight: FontWeight.w700, color: cs.onSurface)),
+ const SizedBox(height: 2),
+ Text(
+ l.statsGoalProgress(
+ _formatDuration(elapsedSeconds), _formatDuration(targetSeconds)),
+ style:
+ tt.bodySmall?.copyWith(color: reached ? doneColor : cs.onSurfaceVariant),
+ ),
+ ])),
+ ]);
+ }
+
Widget _goalCard(ColorScheme cs, TextTheme tt, AppLocalizations l,
double today, double thisWeek, double thisMonth) {
final isDark = Theme.of(context).brightness == Brightness.dark;
final doneColor = isDark ? Colors.greenAccent[400]! : Colors.green.shade700;
- final hasTimeGoal = _goalType != 'off';
final hasBookGoal = _bookGoal > 0;
- final periodSeconds = _goalType == 'weekly'
- ? thisWeek
- : _goalType == 'monthly'
- ? thisMonth
- : today;
- final targetSeconds = _goalMinutes * 60.0;
- final double timeProgress =
- targetSeconds > 0 ? (periodSeconds / targetSeconds).clamp(0.0, 1.0).toDouble() : 0.0;
- final timeReached = hasTimeGoal && periodSeconds >= targetSeconds;
- final goalLabel = _goalType == 'weekly'
- ? l.statsWeeklyGoal
- : _goalType == 'monthly'
- ? l.statsMonthlyGoal
- : l.statsDailyGoal;
+ final elapsed = {'daily': today, 'weekly': thisWeek, 'monthly': thisMonth};
+ final activeGoals = [
+ for (final p in PlayerSettings.statsGoalPeriods)
+ if (_goalMinutes[p]! > 0) p
+ ];
+ // Shrink the ring once more than one goal is on, so three still sit
+ // comfortably in the card.
+ final ringSize = activeGoals.length > 1 ? 44.0 : 56.0;
final double bookProgress =
hasBookGoal ? (_booksFinishedThisYear / _bookGoal).clamp(0.0, 1.0).toDouble() : 0.0;
@@ -1031,46 +1081,12 @@ class _StatsScreenState extends State<StatsScreen>
border: Border.all(color: cs.onSurface.withValues(alpha: 0.06)),
),
child: Column(children: [
- if (hasTimeGoal)
- Row(children: [
- SizedBox(
- width: 56,
- height: 56,
- child: Stack(alignment: Alignment.center, children: [
- SizedBox(
- width: 56,
- height: 56,
- child: CircularProgressIndicator(
- value: timeProgress,
- strokeWidth: 5,
- backgroundColor: cs.onSurface.withValues(alpha: 0.08),
- valueColor: AlwaysStoppedAnimation(timeReached ? doneColor : cs.primary),
- ),
- ),
- if (timeReached)
- Icon(Icons.check_rounded, color: doneColor, size: 24)
- else
- Text('${(timeProgress * 100).round()}%',
- style: tt.labelMedium
- ?.copyWith(fontWeight: FontWeight.w700, color: cs.onSurface)),
- ]),
- ),
- const SizedBox(width: 16),
- Expanded(
- child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Text(goalLabel,
- style: tt.titleSmall
- ?.copyWith(fontWeight: FontWeight.w700, color: cs.onSurface)),
- const SizedBox(height: 2),
- Text(
- l.statsGoalProgress(
- _formatDuration(periodSeconds), _formatDuration(targetSeconds)),
- style: tt.bodySmall
- ?.copyWith(color: timeReached ? doneColor : cs.onSurfaceVariant),
- ),
- ])),
- ]),
- if (hasTimeGoal && hasBookGoal) const SizedBox(height: 16),
+ for (var i = 0; i < activeGoals.length; i++) ...[
+ if (i > 0) const SizedBox(height: 12),
+ _timeGoalRow(cs, tt, l, activeGoals[i], elapsed[activeGoals[i]]!,
+ ringSize, doneColor),
+ ],
+ if (activeGoals.isNotEmpty && hasBookGoal) const SizedBox(height: 16),
if (hasBookGoal)
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 88193122..457db72c 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -117,8 +117,9 @@ class BackupService {
'progressTextScale': await PlayerSettings.getProgressTextScale(),
'lockPortrait': await PlayerSettings.getLockPortrait(),
'autoSeriesDownloadDefault': await PlayerSettings.getAutoSeriesDownloadDefault(),
- 'statsGoalType': await PlayerSettings.getStatsGoalType(),
- 'statsGoalMinutes': await PlayerSettings.getStatsGoalMinutes(),
+ 'statsGoalDailyMinutes': await PlayerSettings.getStatsGoalMinutesFor('daily'),
+ 'statsGoalWeeklyMinutes': await PlayerSettings.getStatsGoalMinutesFor('weekly'),
+ 'statsGoalMonthlyMinutes': await PlayerSettings.getStatsGoalMinutesFor('monthly'),
'statsBookGoal': await PlayerSettings.getStatsBookGoal(),
'statsChartStyle': await PlayerSettings.getStatsChartStyle(),
'statsChartRange': await PlayerSettings.getStatsChartRange(),
@@ -555,8 +556,20 @@ class BackupService {
if (s['progressTextScale'] != null) await PlayerSettings.setProgressTextScale((s['progressTextScale'] as num).toDouble());
if (s['lockPortrait'] != null) await PlayerSettings.setLockPortrait(s['lockPortrait'] as bool);
if (s['autoSeriesDownloadDefault'] != null) await PlayerSettings.setAutoSeriesDownloadDefault(s['autoSeriesDownloadDefault'] as bool);
- if (s['statsGoalType'] != null) await PlayerSettings.setStatsGoalType(s['statsGoalType'] as String);
- if (s['statsGoalMinutes'] != null) await PlayerSettings.setStatsGoalMinutes(s['statsGoalMinutes'] as int);
+ for (final p in PlayerSettings.statsGoalPeriods) {
+ final key = 'statsGoal${p[0].toUpperCase()}${p.substring(1)}Minutes';
+ if (s[key] != null) await PlayerSettings.setStatsGoalMinutesFor(p, s[key] as int);
+ }
+ // Backups from before goals went per-period carried one target plus the
+ // period it applied to.
+ if (s['statsGoalDailyMinutes'] == null &&
+ s['statsGoalWeeklyMinutes'] == null &&
+ s['statsGoalMonthlyMinutes'] == null &&
+ s['statsGoalMinutes'] != null &&
+ PlayerSettings.statsGoalPeriods.contains(s['statsGoalType'])) {
+ await PlayerSettings.setStatsGoalMinutesFor(
+ s['statsGoalType'] as String, s['statsGoalMinutes'] as int);
+ }
if (s['statsBookGoal'] != null) await PlayerSettings.setStatsBookGoal(s['statsBookGoal'] as int);
if (s['statsChartStyle'] != null) await PlayerSettings.setStatsChartStyle(s['statsChartStyle'] as String);
if (s['statsChartRange'] != null) await PlayerSettings.setStatsChartRange(s['statsChartRange'] as int);
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dart
index fe0f4155..f670b310 100644
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@ -213,13 +213,69 @@ class PlayerSettings {
static Future<void> setMaxConcurrentDownloads(int value) => _set('maxConcurrentDownloads', value);
// ── Stats page ──
- // Goal period shown on the stats page: 'off' | 'daily' | 'weekly' | 'monthly'.
- static Future<String> getStatsGoalType() => _get('stats_goal_type', 'off');
- static Future<void> setStatsGoalType(String value) => _set('stats_goal_type', value, notify: true);
+ /// Listening goal periods, in the order they're shown.
+ static const statsGoalPeriods = ['daily', 'weekly', 'monthly'];
+
+ static String _statsGoalKey(String period) => 'stats_goal_${period}_minutes';
+ static String _statsGoalOnKey(String period) => 'stats_goal_${period}_on';
+
+ /// Target used when a period is first switched on, so the goal card starts
+ /// somewhere sensible instead of at 0%.
+ static int defaultStatsGoalMinutes(String period) => switch (period) {
+ 'weekly' => 7 * 60,
+ 'monthly' => 30 * 60,
+ _ => 60,
+ };
+
+ /// The most a period's target can be: all the time that period holds. These
+ /// match the rolling windows the stats page actually sums (7 and 30 days
+ /// back from today), not calendar weeks or months.
+ static int maxStatsGoalMinutes(String period) => switch (period) {
+ 'weekly' => 7 * 24 * 60,
+ 'monthly' => 30 * 24 * 60,
+ _ => 24 * 60,
+ };
+
+ /// Target listening minutes for one goal period, or 0 when that goal is
+ /// switched off. All three periods can be on at once. The target survives
+ /// being switched off, so turning a goal back on restores the number you
+ /// set instead of dropping back to the default.
+ static Future<int> getStatsGoalMinutesFor(String period) async {
+ await _migrateStatsGoals();
+ if (!await _get(_statsGoalOnKey(period), false)) return 0;
+ return _get(_statsGoalKey(period), defaultStatsGoalMinutes(period));
+ }
+
+ static Future<void> setStatsGoalMinutesFor(String period, int minutes) async {
+ await _migrateStatsGoals();
+ if (minutes <= 0) {
+ await _set(_statsGoalOnKey(period), false, notify: true);
+ return;
+ }
+ await _set(_statsGoalKey(period), minutes.clamp(1, maxStatsGoalMinutes(period)));
+ await _set(_statsGoalOnKey(period), true, notify: true);
+ }
- /// Target listening minutes for the active goal period.
- static Future<int> getStatsGoalMinutes() => _get('stats_goal_minutes', 30);
- static Future<void> setStatsGoalMinutes(int value) => _set('stats_goal_minutes', value, notify: true);
+ /// Switch a period's goal on or off without disturbing its target.
+ static Future<void> setStatsGoalEnabled(String period, bool on) async {
+ await _migrateStatsGoals();
+ await _set(_statsGoalOnKey(period), on, notify: true);
+ }
+
+ /// One-time migration from the single active-period goal to per-period
+ /// targets, so an existing goal survives the upgrade. Runs per account,
+ /// which is why it hangs off the getters instead of app start.
+ static Future<void> _migrateStatsGoals() async {
+ if (await ScopedPrefs.containsKey('stats_goal_migrated')) return;
+ final oldPeriod = await _get('stats_goal_type', 'off');
+ if (statsGoalPeriods.contains(oldPeriod)) {
+ final oldMinutes = await _get('stats_goal_minutes', 30);
+ await _set(_statsGoalKey(oldPeriod),
+ oldMinutes.clamp(1, maxStatsGoalMinutes(oldPeriod)));
+ await _set(_statsGoalOnKey(oldPeriod), true);
+ }
+ await _set('stats_goal_migrated', true);
+ }
/// Yearly book-challenge target. 0 = off.
static Future<int> getStatsBookGoal() => _get('stats_book_goal', 0);