Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Smoother Library/Home scrolling, podcast unfinished badge, matchAuthor POST

Barnabasf8973528b153
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 30d59013..4705190c 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -1182,6 +1182,8 @@
"episodeListPlaysOlderToNewer": "Plays older to newer episodes",
"episodeListEpisodeCount": "{count, plural, =1{1 episode} other{{count} episodes}}",
"@episodeListEpisodeCount": { "placeholders": { "count": { "type": "int" } } },
+ "episodeListUnfinishedCount": "{count, plural, =1{1 unfinished} other{{count} unfinished}}",
+ "@episodeListUnfinishedCount": { "placeholders": { "count": { "type": "int" } } },
"episodeListAutoDownloadChip": "Auto-Download",
"episodeListSubscribedChip": "Subscribed",
"episodeListExplicitChip": "Explicit",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index ff87a367..a1d26ee8 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -6131,6 +6131,12 @@ abstract class AppLocalizations {
/// **'{count, plural, =1{1 episode} other{{count} episodes}}'**
String episodeListEpisodeCount(int count);
+ /// No description provided for @episodeListUnfinishedCount.
+ ///
+ /// In en, this message translates to:
+ /// **'{count, plural, =1{1 unfinished} other{{count} unfinished}}'**
+ String episodeListUnfinishedCount(int count);
+
/// No description provided for @episodeListAutoDownloadChip.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index b36d2b0c..014d45fa 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -3453,6 +3453,17 @@ class AppLocalizationsDe extends AppLocalizations {
return '$_temp0';
}
+ @override
+ String episodeListUnfinishedCount(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other: '$count unfinished',
+ one: '1 unfinished',
+ );
+ return '$_temp0';
+ }
+
@override
String get episodeListAutoDownloadChip => 'Auto-Download';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 3d64a2b0..c0684960 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -3415,6 +3415,17 @@ class AppLocalizationsEn extends AppLocalizations {
return '$_temp0';
}
+ @override
+ String episodeListUnfinishedCount(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other: '$count unfinished',
+ one: '1 unfinished',
+ );
+ return '$_temp0';
+ }
+
@override
String get episodeListAutoDownloadChip => 'Auto-Download';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index bd1756ea..2af581e1 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -3338,6 +3338,17 @@ class AppLocalizationsZh extends AppLocalizations {
return '$_temp0';
}
+ @override
+ String episodeListUnfinishedCount(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other: '$count unfinished',
+ one: '1 unfinished',
+ );
+ return '$_temp0';
+ }
+
@override
String get episodeListAutoDownloadChip => 'Auto-Download';
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 9a815c1d..27e2d012 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -448,6 +448,41 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
return data;
}
+ /// Count of episodes in [show] that the user hasn't finished (includes
+ /// partially-played and never-started episodes). Used by tile badges and
+ /// the show sheet header.
+ ///
+ /// Prefers the server-provided `numEpisodesIncomplete` field (requested via
+ /// `include=numEpisodesIncomplete` on the library/personalized endpoints) so
+ /// scrolling grids don't have to load every episode payload. Falls back to
+ /// iterating `media.episodes` when the full payload is available (e.g.
+ /// inside the show sheet).
+ int getUnfinishedEpisodeCount(Map<String, dynamic>? show) {
+ if (show == null) return 0;
+ final media = show['media'] as Map<String, dynamic>? ?? const {};
+ // Try the server-provided count first.
+ final serverCount = show['numEpisodesIncomplete'] as int? ??
+ media['numEpisodesIncomplete'] as int?;
+ if (serverCount != null) return serverCount;
+
+ // Fallback: count from the loaded episodes array. Match server semantics
+ // — count any episode the user hasn't marked finished.
+ final itemId = show['id'] as String? ?? '';
+ if (itemId.isEmpty) return 0;
+ final episodes = media['episodes'] as List<dynamic>? ?? const [];
+ if (episodes.isEmpty) return 0;
+ var count = 0;
+ for (final e in episodes) {
+ if (e is! Map<String, dynamic>) continue;
+ final epId = e['id'] as String? ?? '';
+ if (epId.isEmpty) continue;
+ final pd = getEpisodeProgressData(itemId, epId);
+ final isFinished = pd?['isFinished'] == true;
+ if (!isFinished) count++;
+ }
+ return count;
+ }
+
Future<void> refreshLocalProgress() async {
final sync = ProgressSyncService();
final itemIds = <String>{..._progressMap.keys};
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index e12b4d86..9952107a 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
@@ -55,6 +56,16 @@ class AppShell extends StatefulWidget {
return true;
}
+ /// Called by Home (callingTab=0) and Library (callingTab=1) after their
+ /// first frame. Lets the AppShell re-sync the bottom-nav listener to the
+ /// right notifier — handles both "screen state didn't exist on initial
+ /// attach" and "lazy attach attached to the wrong tab during a fade
+ /// transition" (LibraryProvider notify can rebuild AppShell mid-fade and
+ /// schedule a postFrame that fires before _currentIndex transitions).
+ static void notifyScreenReady(int callingTab) {
+ _AppShellState._instance?._reattachIfNeeded(callingTab);
+ }
+
@override
State<AppShell> createState() => _AppShellState();
}
@@ -149,50 +160,61 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
}
}
- /// Subscribe to the active screen's barsVisibleNotifier when on Home or
+ /// Subscribe to the active screen's barsRevealNotifier when on Home or
/// Library tab, and ensure the nav bar is visible on all other tabs.
void _syncNavBarListener(int index) {
- debugPrint('[NavBar] _syncNavBarListener(index=$index) ctrl=${_navBarAnimController.value.toStringAsFixed(2)}');
_detachNavBarListener();
- ValueNotifier<bool>? notifier;
+ // Snap visible immediately on every tab change so a partial-hide state
+ // from another tab can never bleed into the new tab.
+ _navBarAnimController.value = 1.0;
+ ValueListenable<double>? notifier;
if (index == 0) {
- notifier = _homeKey.currentState?.barsVisibleNotifier;
+ notifier = _homeKey.currentState?.barsRevealNotifier;
} else if (index == 1) {
- notifier = _libraryKey.currentState?.barsVisibleNotifier;
+ notifier = _libraryKey.currentState?.barsRevealNotifier;
}
if (notifier != null) {
_activeBarNotifier = notifier;
+ // Mirror the screen's continuous 0..1 reveal value directly onto the
+ // controller so the bottom nav slides in lockstep with the header.
_navBarListener = () {
- if (notifier!.value) {
- _navBarAnimController.forward();
- } else {
- _navBarAnimController.reverse();
- }
+ final v = notifier!.value.clamp(0.0, 1.0);
+ // Skip no-op controller writes. AnimationController.value setter
+ // notifies listeners (and triggers SizeTransition + Scaffold layout)
+ // even when the value didn't change, which causes scroll jank when
+ // the bar is already fully open/closed.
+ if ((_navBarAnimController.value - v).abs() < 0.005) return;
+ _navBarAnimController.value = v;
};
notifier.addListener(_navBarListener!);
_navBarListener!();
- debugPrint('[NavBar] Attached listener to tab=$index notifier.value=${notifier.value} ctrl=${_navBarAnimController.value.toStringAsFixed(2)}');
- } else {
- // Not a scroll-hide tab - force nav bar visible immediately.
- // Use .value to snap instead of animate, avoiding races where
- // the controller gets stuck mid-animation.
- _navBarAnimController.value = 1.0;
- debugPrint('[NavBar] Snap to 1.0 for non-scroll tab=$index');
}
}
- ValueNotifier<bool>? _activeBarNotifier;
+ ValueListenable<double>? _activeBarNotifier;
void _detachNavBarListener() {
if (_navBarListener != null && _activeBarNotifier != null) {
_activeBarNotifier!.removeListener(_navBarListener!);
- // Reset the notifier so bars are visible when the user returns to this tab
- _activeBarNotifier!.value = true;
}
_navBarListener = null;
_activeBarNotifier = null;
}
+ /// Hook called by Home/Library when their state finishes mounting so we can
+ /// pick up (or correct) the listener attach. Re-syncs unconditionally when
+ /// the calling tab matches the current tab, even if a listener is already
+ /// attached — that listener may have been attached to the wrong tab by the
+ /// lazy-attach race during a fade transition.
+ void _reattachIfNeeded(int callingTab) {
+ if (!mounted) return;
+ // Only act when the screen calling us is actually the active one. If the
+ // user has navigated away in the meantime, leave the existing attachment
+ // to whatever screen they're on.
+ if (_currentIndex != callingTab) return;
+ _syncNavBarListener(_currentIndex);
+ }
+
void _ensurePageBuilt(int index) {
if (_pages[index] != null) return;
switch (index) {
@@ -447,6 +469,10 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
+ // Belt-and-suspenders: never let the nav bar come back hidden after a
+ // resume. The screens snap their own driver back to shown on next scroll
+ // anyway, but mirror it here in case the user resumes onto a stale tab.
+ _navBarAnimController.value = 1.0;
context.read<LibraryProvider>().onAppForegrounded();
SleepTimerService().onAppForegrounded();
AudioPlayerService.onAppForegrounded();
@@ -466,6 +492,15 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
}
}
+ @override
+ void didChangeMetrics() {
+ // Orientation change, software keyboard, anything that resizes the window:
+ // make sure the bottom nav isn't stuck partway hidden.
+ _navBarAnimController.value = 1.0;
+ _homeKey.currentState?.resetReveal();
+ _libraryKey.currentState?.resetReveal();
+ }
+
DateTime? _lastRefresh;
static const _refreshCooldown = Duration(minutes: 1);
@@ -544,14 +579,28 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
}
Widget _buildBottomNav(BuildContext context) {
- // Lazily attach listener when on Home or Library tab (handles start-on-tab case).
- // The screen's state may not exist on the first frame, so retry until attached.
- if ((_currentIndex == 0 || _currentIndex == 1) && _navBarListener == null) {
+ // Determine the *correct* notifier for the active tab so we can detect
+ // both "no listener" and "listener attached to the wrong tab" — the
+ // second happens when LibraryProvider.notify() rebuilds AppShell mid-fade
+ // and the lazy attach captures the pre-fade _currentIndex.
+ final isHomeOrLibrary = _currentIndex == 0 || _currentIndex == 1;
+ ValueListenable<double>? correctNotifier;
+ if (_currentIndex == 0) {
+ correctNotifier = _homeKey.currentState?.barsRevealNotifier;
+ } else if (_currentIndex == 1) {
+ correctNotifier = _libraryKey.currentState?.barsRevealNotifier;
+ }
+ final wrongAttachment = isHomeOrLibrary &&
+ _navBarListener != null &&
+ correctNotifier != null &&
+ !identical(_activeBarNotifier, correctNotifier);
+ final missingAttachment = isHomeOrLibrary && _navBarListener == null;
+
+ if (missingAttachment || wrongAttachment) {
final scheduledIndex = _currentIndex;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || _currentIndex != scheduledIndex) return;
_syncNavBarListener(_currentIndex);
- // If the screen state wasn't ready yet, retry on next frame
if (_navBarListener == null && _currentIndex == scheduledIndex) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _currentIndex == scheduledIndex) {
@@ -560,7 +609,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
});
}
});
- } else if (_currentIndex != 0 && _currentIndex != 1 && _navBarListener != null) {
+ } else if (!isHomeOrLibrary && _navBarListener != null) {
// Stale listener left over from a fade transition — detach and snap the
// nav bar visible so it doesn't get hidden by the previous tab's notifier.
WidgetsBinding.instance.addPostFrameCallback((_) {
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
index 44610e33..c79b0574 100644
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@ -1,4 +1,5 @@
import 'dart:io';
+import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
@@ -21,6 +22,7 @@ import '../widgets/collection_detail_sheet.dart';
import '../widgets/section_detail_sheet.dart';
import '../widgets/feature_hint.dart';
import '../widgets/offline_status_icon.dart';
+import '../widgets/scroll_reveal.dart';
import '../widgets/section_labels.dart';
import 'app_shell.dart';
import '../l10n/app_localizations.dart';
@@ -32,17 +34,17 @@ class HomeScreen extends StatefulWidget {
State<HomeScreen> createState() => HomeScreenState();
}
-class HomeScreenState extends State<HomeScreen> {
+class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMixin {
final _player = AudioPlayerService();
bool _hideEbookOnly = false;
bool _rectangleCovers = false;
// ── Scroll-to-hide bars ──
- final ValueNotifier<bool> barsVisibleNotifier = ValueNotifier(true);
+ /// Continuous 0..1 reveal value the AppShell mirrors onto the bottom nav.
+ late final ScrollRevealDriver _revealDriver = ScrollRevealDriver(vsync: this);
+ ValueListenable<double> get barsRevealNotifier => _revealDriver.notifier;
+ void resetReveal() => _revealDriver.resetToShown();
final _scrollController = ScrollController();
- double _lastScrollOffset = 0;
- double _scrollAccumulator = 0;
- static const _scrollThreshold = 40.0;
// Cached filtered sections — invalidated when source data or settings change.
List<Map<String, dynamic>>? _cachedSections;
@@ -59,45 +61,10 @@ class HomeScreenState extends State<HomeScreen> {
String? _lastKnownItemId;
bool _lastKnownPlaying = false;
- void _onScrollDirection() {
- if (!_scrollController.hasClients) return;
- final offset = _scrollController.offset;
- final delta = offset - _lastScrollOffset;
- _lastScrollOffset = offset;
-
- if (offset <= 0) {
- _scrollAccumulator = 0;
- _showBars();
- return;
- }
- if (delta.abs() < 0.5) return;
-
- if ((delta > 0) != (_scrollAccumulator > 0)) _scrollAccumulator = 0;
- _scrollAccumulator += delta;
-
- if (_scrollAccumulator > _scrollThreshold) {
- _hideBars();
- } else if (_scrollAccumulator < -_scrollThreshold) {
- _showBars();
- }
- }
-
- void _showBars() {
- if (!barsVisibleNotifier.value) {
- barsVisibleNotifier.value = true;
- }
- }
-
- void _hideBars() {
- if (barsVisibleNotifier.value) {
- barsVisibleNotifier.value = false;
- }
- }
-
@override
void initState() {
super.initState();
- _scrollController.addListener(_onScrollDirection);
+ _revealDriver.attach(_scrollController);
_player.addListener(_onPlayerChanged);
PlayerSettings.settingsChanged.addListener(_loadSettings);
_loadSettings();
@@ -106,6 +73,11 @@ class HomeScreenState extends State<HomeScreen> {
if (lib.libraries.isEmpty) lib.loadLibraries();
lib.refreshLocalProgress();
});
+ // Tell AppShell we're alive so its bottom-nav listener can attach now
+ // rather than waiting on a postFrame retry that may never re-fire.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) AppShell.notifyScreenReady(0);
+ });
}
Future<void> _loadSettings() async {
@@ -193,8 +165,8 @@ class HomeScreenState extends State<HomeScreen> {
@override
void dispose() {
+ _revealDriver.dispose();
_scrollController.dispose();
- barsVisibleNotifier.dispose();
_player.removeListener(_onPlayerChanged);
PlayerSettings.settingsChanged.removeListener(_loadSettings);
super.dispose();
@@ -345,7 +317,12 @@ class HomeScreenState extends State<HomeScreen> {
),
),
child: SafeArea(
- child: RefreshIndicator(
+ child: NotificationListener<ScrollNotification>(
+ onNotification: (n) {
+ if (n is ScrollEndNotification) _revealDriver.settle();
+ return false;
+ },
+ child: RefreshIndicator(
onRefresh: () async {
await lib.refresh();
},
@@ -660,6 +637,7 @@ class HomeScreenState extends State<HomeScreen> {
],
),
),
+ ),
),
),
);
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index 3b624498..1d9df825 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'dart:ui' as ui;
+import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
@@ -19,9 +20,11 @@ import '../widgets/library_series_tab.dart';
import '../widgets/library_authors_tab.dart';
import '../widgets/library_narrators_tab.dart';
import 'admin_podcasts_screen.dart';
+import 'app_shell.dart';
import 'upcoming_releases_screen.dart';
import '../widgets/audible_series_sheet.dart' show showAudibleRegionPicker;
import '../widgets/offline_status_icon.dart';
+import '../widgets/scroll_reveal.dart';
import '../l10n/app_localizations.dart';
/// Responsive grid column count based on available width.
@@ -66,13 +69,13 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_searchController.clear();
_onSearchChanged('');
_focusNode.unfocus();
- _showBars();
+ _revealDriver.resetToShown();
}
/// Give focus to the search bar (used by the app-icon "Search" shortcut).
void focusSearch() {
if (!mounted) return;
- _showBars();
+ _revealDriver.resetToShown();
FocusScope.of(context).requestFocus(_focusNode);
// Delay the explicit keyboard-show so focus has time to attach to the
// text field and any in-flight navigation (popping Downloads/Bookmarks,
@@ -155,56 +158,12 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
double get _coverAspectRatio => _rectangleCovers ? 2 / 3 : 1.0;
// ── Scroll-to-hide bars ──
- /// Notifies AppShell whether the bottom nav bar should be visible.
- final ValueNotifier<bool> barsVisibleNotifier = ValueNotifier(true);
- late final AnimationController _headerAnimController = AnimationController(
- vsync: this,
- duration: const Duration(milliseconds: 400),
- value: 1.0,
- );
- double _lastScrollOffset = 0;
- double _scrollAccumulator = 0;
- static const _scrollThreshold = 40.0; // pixels of scroll before hide/show triggers
-
- void _onScrollDirection(ScrollController controller) {
- if (_isInSearchMode) return;
- if (!controller.hasClients) return;
- final offset = controller.offset;
- final delta = offset - _lastScrollOffset;
- _lastScrollOffset = offset;
-
- // At the top, always show
- if (offset <= 0) {
- _scrollAccumulator = 0;
- _showBars();
- return;
- }
- if (delta.abs() < 0.5) return;
-
- // Accumulate scroll in current direction; reset on direction change
- if ((delta > 0) != (_scrollAccumulator > 0)) _scrollAccumulator = 0;
- _scrollAccumulator += delta;
-
- if (_scrollAccumulator > _scrollThreshold) {
- _hideBars();
- } else if (_scrollAccumulator < -_scrollThreshold) {
- _showBars();
- }
- }
-
- void _showBars() {
- if (!barsVisibleNotifier.value) {
- barsVisibleNotifier.value = true;
- _headerAnimController.forward();
- }
- }
-
- void _hideBars() {
- if (barsVisibleNotifier.value) {
- barsVisibleNotifier.value = false;
- _headerAnimController.reverse();
- }
- }
+ /// Continuous 0..1 reveal: 1 = header + nav fully visible, 0 = both hidden.
+ /// Drives the header SizeTransition, the floating tab bar, and the AppShell
+ /// bottom nav in lockstep.
+ late final ScrollRevealDriver _revealDriver = ScrollRevealDriver(vsync: this);
+ ValueListenable<double> get barsRevealNotifier => _revealDriver.notifier;
+ void resetReveal() => _revealDriver.resetToShown();
/// Called externally (e.g. from AppShell) to focus the search field.
void requestSearchFocus() {
@@ -216,15 +175,19 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
@override
void initState() {
super.initState();
- _scrollController.addListener(_onScroll);
- _seriesScrollController.addListener(_onSeriesScroll);
- _authorsScrollController.addListener(_onAuthorsScroll);
- _narratorsScrollController.addListener(_onNarratorsScroll);
+ // Reveal driver is fed by NotificationListener at the screen level —
+ // works across multiple per-tab scroll controllers in the IndexedStack
+ // without needing to re-attach on every tab switch.
// Load initial page once the library is ready
WidgetsBinding.instance.addPostFrameCallback((_) {
_initTabController();
_tryInitialLoad();
});
+ // Tell AppShell we're alive so its bottom-nav listener can attach now
+ // rather than waiting on a postFrame retry that may never re-fire.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) AppShell.notifyScreenReady(1);
+ });
}
void _initTabController() {
@@ -240,9 +203,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final newTab = _tabController!.index;
if (newTab == _currentTab) return;
setState(() => _currentTab = newTab);
- // Reset scroll tracking and show bars when switching sub-tabs
- _lastScrollOffset = 0;
- _showBars();
+ // Reset reveal so the SliverAppBar is fully visible after a tab switch.
+ _revealDriver.resetToShown();
PlayerSettings.setLibraryTab(newTab);
// Lazy load data for the tab
if (newTab == 1 && _seriesItems.isEmpty && !_isLoadingSeriesPage) {
@@ -298,12 +260,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_allNarratorsCacheLibraryId = null;
_searchNarratorResults = [];
});
- if (_scrollController.hasClients) _scrollController.jumpTo(0);
- if (_seriesScrollController.hasClients) _seriesScrollController.jumpTo(0);
- if (_authorsScrollController.hasClients) _authorsScrollController.jumpTo(0);
- if (_narratorsScrollController.hasClients) _narratorsScrollController.jumpTo(0);
- _lastScrollOffset = 0;
- _showBars();
+ _revealDriver.resetToShown();
// Restore sort/filter for the new library type, then load
_restoreSortFilter().then((_) {
if (mounted) _loadPage();
@@ -484,12 +441,11 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_debounce?.cancel();
_searchController.dispose();
_focusNode.dispose();
+ _revealDriver.dispose();
_scrollController.dispose();
_seriesScrollController.dispose();
_authorsScrollController.dispose();
_narratorsScrollController.dispose();
- _headerAnimController.dispose();
- barsVisibleNotifier.dispose();
_tabController?.removeListener(_onTabChanged);
_tabController?.dispose();
PlayerSettings.settingsChanged.removeListener(_onSettingsChanged);
@@ -501,31 +457,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
super.dispose();
}
- // ── Scroll-based pagination + direction tracking ──
- void _onScroll() {
- _onScrollDirection(_scrollController);
- if (_isInSearchMode) return;
- if (_scrollController.position.pixels >=
- _scrollController.position.maxScrollExtent - 400) {
- _loadPage();
- }
- }
-
- void _onSeriesScroll() {
- _onScrollDirection(_seriesScrollController);
- if (_seriesScrollController.position.pixels >=
- _seriesScrollController.position.maxScrollExtent - 400) {
- _loadSeriesPage();
- }
- }
-
- void _onAuthorsScroll() {
- _onScrollDirection(_authorsScrollController);
- }
-
- void _onNarratorsScroll() {
- _onScrollDirection(_narratorsScrollController);
- }
+ // Pagination is now triggered by the NotificationListener inside each tab
+ // widget, which calls back into _loadPage / _loadSeriesPage when the user
+ // approaches the bottom of the visible scroll view.
// ══════════════════════════════════════════════════════════════
// LIBRARY TAB - Load a page of items
@@ -1032,7 +966,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
void _onSearchChanged(String query) {
_debounce?.cancel();
// Always show bars when entering/exiting search
- _showBars();
+ _revealDriver.resetToShown();
if (query.trim().isEmpty) {
setState(() {
_searchBookResults = [];
@@ -1362,12 +1296,86 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
),
),
SafeArea(
- child: Column(
+ // Per-tab CustomScrollView with its own SliverAppBar(floating, snap)
+ // for the header. No NestedScrollView coordinator in the scroll
+ // path, which makes scrolling noticeably smoother. The reveal
+ // driver is fed by a single NotificationListener at this level so
+ // the bottom nav stays in sync regardless of which tab is active.
+ child: Stack(
children: [
- SizeTransition(
- sizeFactor: _headerAnimController,
- axisAlignment: -1.0,
- child: Column(mainAxisSize: MainAxisSize.min, children: [
+ NotificationListener<ScrollNotification>(
+ onNotification: (n) {
+ if (n is ScrollUpdateNotification) {
+ _revealDriver.noteScroll(
+ n.scrollDelta ?? 0, n.metrics.pixels);
+ } else if (n is ScrollEndNotification) {
+ _revealDriver.settle();
+ }
+ return false;
+ },
+ child: Builder(
+ builder: (ctx) {
+ // Paint the same screen-height gradient inside the
+ // SliverAppBar so the header (a) visually matches the
+ // body's gradient when sitting at the top, and (b) is
+ // opaque enough to occlude books when it floats back in
+ // mid-scroll. The gradient is shifted up by the SafeArea
+ // top inset so its color at any screen-Y matches the
+ // body gradient at the same screen-Y (no visible seam at
+ // the bottom of the header).
+ final topInset = MediaQuery.of(context).padding.top;
+ final screenH = MediaQuery.of(context).size.height;
+ final headerBackground = oledNotifier.value
+ ? const ColoredBox(color: Colors.black)
+ : ClipRect(
+ child: OverflowBox(
+ maxHeight: screenH,
+ minHeight: 0,
+ alignment: Alignment.topCenter,
+ child: Transform.translate(
+ offset: Offset(0, -topInset),
+ child: SizedBox(
+ height: screenH,
+ width: double.infinity,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: scaffoldBg,
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.22, 0.72, 1.0],
+ colors: [
+ cs.primary.withValues(alpha: 0.06),
+ cs.surface,
+ lowerFade,
+ scaffoldBg,
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ final headerSliver = SliverAppBar(
+ floating: true,
+ snap: true,
+ // primary: false disables Material's automatic status
+ // bar padding so the header doesn't get inset twice
+ // (we already wrap the whole NestedScrollView in
+ // SafeArea above).
+ primary: false,
+ toolbarHeight: _isInSearchMode ? 156 : 184,
+ backgroundColor: scaffoldBg,
+ surfaceTintColor: Colors.transparent,
+ elevation: 0,
+ scrolledUnderElevation: 0,
+ automaticallyImplyLeading: false,
+ flexibleSpace: ClipRect(
+ child: Stack(
+ children: [
+ Positioned.fill(child: headerBackground),
+ Column(mainAxisSize: MainAxisSize.min, children: [
AbsorbPageHeader(
title: l.libraryTitle,
trailing: OfflineStatusIcon(
@@ -1450,65 +1458,74 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
if (!_isInSearchMode)
_buildInfoRow(cs, tt, l),
]),
- ),
- Expanded(
- child: Stack(
- children: [
- _isInSearchMode
- ? _buildSearchResults(cs, tt, l)
- : hasTabs
- ? _buildTabbedContent(cs, tt)
- : _buildGrid(),
- // Floating tab bar at bottom (book libraries only, hidden during search)
- if (hasTabs)
- Positioned(
- left: 0, right: 0,
- bottom: 12,
- child: ValueListenableBuilder<bool>(
- valueListenable: barsVisibleNotifier,
- builder: (_, visible, child) => AnimatedSlide(
- duration: const Duration(milliseconds: 250),
- offset: visible ? Offset.zero : const Offset(0, 3),
- child: AnimatedOpacity(
- duration: const Duration(milliseconds: 200),
- opacity: visible ? 1.0 : 0.0,
- child: child,
- ),
- ),
- child: _buildFloatingTabBar(cs),
+ ],
),
),
- // Floating sort button for podcast libraries
- if (!hasTabs && !_isInSearchMode)
- Positioned(
- left: 0, right: 0,
- bottom: 12,
- child: ValueListenableBuilder<bool>(
- valueListenable: barsVisibleNotifier,
- builder: (_, visible, child) => AnimatedSlide(
- duration: const Duration(milliseconds: 250),
- offset: visible ? Offset.zero : const Offset(0, 3),
- child: AnimatedOpacity(
- duration: const Duration(milliseconds: 200),
- opacity: visible ? 1.0 : 0.0,
- child: child,
- ),
- ),
- child: Center(child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- _buildFloatingSortButton(cs, tt),
- if (context.read<AuthProvider>().isRoot) ...[
- const SizedBox(width: 8),
- _buildFloatingManageButton(cs),
- ],
+ );
+ return _isInSearchMode
+ ? _buildSearchResults(cs, tt, l, headerSliver)
+ : hasTabs
+ ? _buildTabbedContent(cs, tt, headerSliver)
+ : _buildGrid(headerSliver);
+ },
+ ),
+ ),
+ if (hasTabs && !_isInSearchMode)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 12,
+ child: ValueListenableBuilder<double>(
+ valueListenable: _revealDriver.notifier,
+ // Translate only; skip the Opacity saveLayer that was
+ // forcing a per-frame re-raster of the BackdropFilter
+ // pill. Skip painting entirely once basically hidden.
+ builder: (_, reveal, child) {
+ if (reveal < 0.02) return const SizedBox.shrink();
+ return IgnorePointer(
+ ignoring: reveal < 0.5,
+ child: Transform.translate(
+ offset: Offset(0, (1 - reveal) * 80),
+ child: child,
+ ),
+ );
+ },
+ child: RepaintBoundary(child: _buildFloatingTabBar(cs)),
+ ),
+ ),
+ if (!hasTabs && !_isInSearchMode)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 12,
+ child: ValueListenableBuilder<double>(
+ valueListenable: _revealDriver.notifier,
+ builder: (_, reveal, child) {
+ if (reveal < 0.02) return const SizedBox.shrink();
+ return IgnorePointer(
+ ignoring: reveal < 0.5,
+ child: Transform.translate(
+ offset: Offset(0, (1 - reveal) * 80),
+ child: child,
+ ),
+ );
+ },
+ child: RepaintBoundary(
+ child: Center(
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _buildFloatingSortButton(cs, tt),
+ if (context.read<AuthProvider>().isRoot) ...[
+ const SizedBox(width: 8),
+ _buildFloatingManageButton(cs),
],
- )),
+ ],
),
),
- ],
+ ),
+ ),
),
- ),
],
),
),
@@ -1706,15 +1723,18 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
);
}
- Widget _buildTabbedContent(ColorScheme cs, TextTheme tt) {
- // Use IndexedStack to preserve scroll positions across tabs
+ Widget _buildTabbedContent(ColorScheme cs, TextTheme tt, Widget headerSliver) {
+ // IndexedStack preserves each tab's scroll position when switching tabs.
+ // Each tab is its own CustomScrollView with its own SliverAppBar instance,
+ // so floating-header behavior is per-tab and there's no NestedScrollView
+ // coordinator overhead in the scroll path.
return IndexedStack(
index: _currentTab,
children: [
- _buildGrid(),
- _buildSeriesGrid(),
- _buildAuthorsGrid(),
- _buildNarratorsGrid(),
+ _buildGrid(headerSliver),
+ _buildSeriesGrid(headerSliver),
+ _buildAuthorsGrid(headerSliver),
+ _buildNarratorsGrid(headerSliver),
],
);
}
@@ -1756,46 +1776,51 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
// ═══════════════════════════════════════════════════════════════
// LIBRARY TAB - BROWSE GRID
// ═══════════════════════════════════════════════════════════════
- Widget _buildGrid() {
+ Widget _buildGrid(Widget headerSliver) {
return LibraryBooksTab(
items: _items,
isLoadingPage: _isLoadingPage,
hasMore: _hasMore,
- scrollController: _scrollController,
filter: _filter,
genreFilter: _genreFilter,
rectangleCovers: _rectangleCovers,
coverAspectRatio: _coverAspectRatio,
onRefresh: _refreshAll,
onClearFilter: () => _changeFilter(LibraryFilter.none),
+ headerSliver: headerSliver,
+ scrollController: _scrollController,
+ onLoadMore: _loadPage,
);
}
// ═══════════════════════════════════════════════════════════════
// SERIES TAB - GRID
// ═══════════════════════════════════════════════════════════════
- Widget _buildSeriesGrid() {
+ Widget _buildSeriesGrid(Widget headerSliver) {
return LibrarySeriesTab(
seriesItems: _seriesItems,
isLoadingSeriesPage: _isLoadingSeriesPage,
hasMoreSeries: _hasMoreSeries,
- scrollController: _seriesScrollController,
rectangleCovers: _rectangleCovers,
coverAspectRatio: _coverAspectRatio,
onRefresh: _refreshSeries,
+ headerSliver: headerSliver,
+ scrollController: _seriesScrollController,
+ onLoadMore: _loadSeriesPage,
);
}
// ═══════════════════════════════════════════════════════════════
// AUTHORS TAB - GRID
// ═══════════════════════════════════════════════════════════════
- Widget _buildAuthorsGrid() {
+ Widget _buildAuthorsGrid(Widget headerSliver) {
return LibraryAuthorsTab(
authors: _authors,
isLoadingAuthors: _isLoadingAuthors,
authorsLoaded: _authorsLoaded,
- scrollController: _authorsScrollController,
onRefresh: _refreshAuthors,
+ headerSliver: headerSliver,
+ scrollController: _authorsScrollController,
);
}
@@ -1811,46 +1836,68 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
await _loadNarrators();
}
- Widget _buildNarratorsGrid() {
+ Widget _buildNarratorsGrid(Widget headerSliver) {
return LibraryNarratorsTab(
narrators: _narrators,
isLoading: _isLoadingNarrators,
loaded: _narratorsLoaded,
- scrollController: _narratorsScrollController,
onRefresh: _refreshNarrators,
+ headerSliver: headerSliver,
+ scrollController: _narratorsScrollController,
);
}
// ═══════════════════════════════════════════════════════════════
// SEARCH RESULTS
// ═══════════════════════════════════════════════════════════════
- Widget _buildSearchResults(ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ Widget _buildSearchResults(
+ ColorScheme cs, TextTheme tt, AppLocalizations l, Widget headerSliver) {
+ final injector = headerSliver;
if (_isSearching) {
- return const Center(child: CircularProgressIndicator());
+ return CustomScrollView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ injector,
+ const SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(child: CircularProgressIndicator()),
+ ),
+ ],
+ );
}
if (!_hasSearched) {
- return const SizedBox.shrink();
+ return CustomScrollView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [injector, const SliverToBoxAdapter(child: SizedBox.shrink())],
+ );
}
if (_searchBookResults.isEmpty && _searchSeriesResults.isEmpty && _searchAuthorResults.isEmpty && _searchNarratorResults.isEmpty && _searchEpisodeResults.isEmpty) {
- return Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.search_off_rounded, size: 48, color: cs.onSurfaceVariant),
- const SizedBox(height: 12),
- Text(l.libraryNoResults,
- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
- ],
- ),
+ return CustomScrollView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ injector,
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.search_off_rounded, size: 48, color: cs.onSurfaceVariant),
+ const SizedBox(height: 12),
+ Text(l.libraryNoResults,
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ ),
+ ],
);
}
final auth = context.read<AuthProvider>();
final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;
- return ListView(
- padding: const EdgeInsets.fromLTRB(16, 8, 16, 100),
- children: [
+ final children = <Widget>[
// ─── BOOKS / SHOWS (only title matches) ───
if (_searchBookResults.isNotEmpty) ...[
...() {
@@ -1955,6 +2002,18 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
),
..._searchNarratorResults.map((name) => NarratorResultTile(name: name)),
],
+ ];
+
+ return CustomScrollView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ injector,
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 100),
+ sliver: SliverList(
+ delegate: SliverChildListDelegate(children),
+ ),
+ ),
],
);
}
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index e0416a69..1c734e89 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -359,7 +359,11 @@ class ApiService {
}) async {
try {
var url = '$_cleanBaseUrl/api/libraries/$libraryId/items'
- '?page=$page&limit=$limit&sort=$sort&desc=$desc';
+ '?page=$page&limit=$limit&sort=$sort&desc=$desc'
+ // Ask the server to populate numEpisodesIncomplete on podcast items
+ // so podcast tiles can show an unplayed-count badge without loading
+ // every show's full episode list.
+ '&include=numEpisodesIncomplete';
if (filter != null) url += '&filter=$filter';
if (expanded) url += '&minified=0';
if (collapseSeries) url += '&collapseseries=1';
@@ -634,23 +638,24 @@ class ApiService {
/// Quick-match an author against the configured provider (Audible).
/// Server fetches name/asin/description/image, updates the author server-side,
/// and returns the updated author. Returns null if no match or on error.
- /// GET /api/authors/:id/match?q=...&region=...
+ /// POST /api/authors/:id/match body: { q, region }
+ /// Response: { updated: true, author: {...} } on match, { updated: false } on no match.
Future<Map<String, dynamic>?> matchAuthor(
String authorId, {
required String q,
String region = 'us',
}) async {
try {
- final url = '$_cleanBaseUrl/api/authors/$authorId/match'
- '?q=${Uri.encodeQueryComponent(q)}'
- '&region=${Uri.encodeQueryComponent(region)}';
- final r = await _authGet(Uri.parse(url));
+ final r = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/authors/$authorId/match'),
+ body: jsonEncode({'q': q, 'region': region}),
+ );
debugPrint('[API] matchAuthor $authorId -> ${r.statusCode}: ${r.body}');
if (r.statusCode == 200) {
final data = jsonDecode(r.body) as Map<String, dynamic>;
- // Server returns the updated author directly, or { author: {...} }
+ // Server signals no match with { updated: false } and no author payload.
+ if (data['updated'] == false) return null;
if (data['author'] is Map) return data['author'] as Map<String, dynamic>;
- if (data.containsKey('updated')) return data;
return data;
}
} catch (e) { debugPrint('matchAuthor error: $e'); }
diff --git a/lib/widgets/book_card.dart b/lib/widgets/book_card.dart
index dc0da110..fffc3897 100644
--- a/lib/widgets/book_card.dart
+++ b/lib/widgets/book_card.dart
@@ -44,13 +44,18 @@ class BookCard extends StatelessWidget {
final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;
final isExplicit = PlayerSettings.showExplicitBadge && metadata['explicit'] == true;
final isDownloaded = DownloadService().isDownloaded(itemId ?? '');
+ // Only compute for podcast shows that aren't being rendered as an episode
+ // (an episode card shows the recentEpisode payload, not show-level info).
+ final unfinishedCount = (lib.isPodcastLibrary && item['recentEpisode'] == null)
+ ? lib.getUnfinishedEpisodeCount(item)
+ : 0;
final headers = lib.mediaHeaders;
if (isWide) {
return _buildWideCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isExplicit: isExplicit);
}
- return _buildCompactCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isFinished: isFinished, isDownloaded: isDownloaded, isExplicit: isExplicit);
+ return _buildCompactCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isFinished: isFinished, isDownloaded: isDownloaded, isExplicit: isExplicit, unfinishedCount: unfinishedCount);
}
void _navigateToDetail(BuildContext context) {
@@ -206,6 +211,7 @@ class BookCard extends StatelessWidget {
bool isFinished = false,
bool isDownloaded = false,
bool isExplicit = false,
+ int unfinishedCount = 0,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -248,7 +254,8 @@ class BookCard extends StatelessWidget {
),
if (isExplicit)
Positioned(
- top: 4, right: 4,
+ top: unfinishedCount > 0 ? 26 : 4,
+ right: 4,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
decoration: BoxDecoration(
@@ -258,6 +265,27 @@ class BookCard extends StatelessWidget {
child: Text(l.bookCardExplicitBadge, style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w800)),
),
),
+ if (unfinishedCount > 0)
+ Positioned(
+ top: 4,
+ right: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6, vertical: 2),
+ decoration: BoxDecoration(
+ color: cs.primary,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Text(
+ '$unfinishedCount',
+ style: TextStyle(
+ color: cs.onPrimary,
+ fontSize: 10,
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ ),
+ ),
if (isFinished || isDownloaded)
Positioned(
left: 0,
diff --git a/lib/widgets/edit_author_sheet.dart b/lib/widgets/edit_author_sheet.dart
index 29409932..4db640b3 100644
--- a/lib/widgets/edit_author_sheet.dart
+++ b/lib/widgets/edit_author_sheet.dart
@@ -3,6 +3,8 @@ import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../l10n/app_localizations.dart';
import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import 'overlay_toast.dart';
/// Opens a full-screen editor for an author (root admin only).
/// Two tabs:
@@ -137,15 +139,23 @@ class _EditAuthorContentState extends State<_EditAuthorContent>
_matchEmpty = true;
} else {
_matchResult = result;
+ // Sync the Custom tab fields with the matched values so editing
+ // continues from the new data instead of the old.
+ final matchedName = result['name'] as String?;
+ final matchedAsin = result['asin'] as String?;
+ final matchedDesc = result['description'] as String?;
+ if (matchedName != null) _nameCtrl.text = matchedName;
+ if (matchedAsin != null) _asinCtrl.text = matchedAsin;
+ if (matchedDesc != null) _descCtrl.text = matchedDesc;
}
});
if (result != null && result.isNotEmpty) {
// The match endpoint already updates the author server-side, so notify parent.
widget.onUpdated();
- _showSnack(AppLocalizations.of(context)!.authorMatched);
+ _showToast(AppLocalizations.of(context)!.authorMatched, icon: Icons.check_circle_rounded);
} else {
- _showSnack(AppLocalizations.of(context)!.authorNoMatchFound);
+ _showToast(AppLocalizations.of(context)!.authorNoMatchFound, icon: Icons.search_off_rounded);
}
}
@@ -173,7 +183,7 @@ class _EditAuthorContentState extends State<_EditAuthorContent>
if (result['ok'] != true) {
setState(() => _saving = false);
- _showSnack(AppLocalizations.of(context)!.authorUpdateFailed);
+ _showToast(AppLocalizations.of(context)!.authorUpdateFailed, icon: Icons.error_outline_rounded);
return;
}
@@ -193,7 +203,7 @@ class _EditAuthorContentState extends State<_EditAuthorContent>
final imgOk = await api.updateAuthorImageFromUrl(widget.authorId, imageUrl);
if (!imgOk && mounted) {
setState(() => _saving = false);
- _showSnack(AppLocalizations.of(context)!.authorImageFailed);
+ _showToast(AppLocalizations.of(context)!.authorImageFailed, icon: Icons.error_outline_rounded);
return;
}
}
@@ -203,7 +213,7 @@ class _EditAuthorContentState extends State<_EditAuthorContent>
if (mounted) {
setState(() => _saving = false);
Navigator.of(context).pop();
- _showSnack(AppLocalizations.of(context)!.authorUpdated);
+ _showToast(AppLocalizations.of(context)!.authorUpdated, icon: Icons.check_circle_rounded);
}
}
@@ -235,21 +245,14 @@ class _EditAuthorContentState extends State<_EditAuthorContent>
setState(() => _saving = false);
if (ok) {
widget.onUpdated();
- _showSnack(l.authorImageRemoved);
+ _showToast(l.authorImageRemoved, icon: Icons.check_circle_rounded);
} else {
- _showSnack(l.authorImageFailed);
+ _showToast(l.authorImageFailed, icon: Icons.error_outline_rounded);
}
}
- void _showSnack(String text) {
- ScaffoldMessenger.of(context)
- ..clearSnackBars()
- ..showSnackBar(SnackBar(
- content: Text(text),
- behavior: SnackBarBehavior.floating,
- duration: const Duration(seconds: 2),
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
+ void _showToast(String text, {IconData? icon}) {
+ showOverlayToast(context, text, icon: icon);
}
// ─── Build ──────────────────────────────────────────────────
@@ -369,7 +372,16 @@ class _EditAuthorContentState extends State<_EditAuthorContent>
final name = result['name'] as String? ?? '';
final asin = result['asin'] as String? ?? '';
final desc = (result['description'] as String? ?? '').replaceAll(RegExp(r'<[^>]*>'), '').trim();
- final imageUrl = result['imageUrl'] as String? ?? result['image'] as String? ?? '';
+ // ABS saves the matched image server-side and returns the author with an
+ // imagePath. Build the URL through the API service (with the auth token)
+ // and cache-bust with updatedAt so we don't show the previous cached image.
+ final api = context.read<AuthProvider>().apiService;
+ final hasImagePath = (result['imagePath'] as String?)?.isNotEmpty == true;
+ final ts = (result['updatedAt'] as num?)?.toInt();
+ final imageUrl = (api != null && hasImagePath)
+ ? api.getAuthorImageUrl(widget.authorId, updatedAt: ts)
+ : '';
+ final headers = context.read<LibraryProvider>().mediaHeaders;
return Card(
elevation: 0,
@@ -388,6 +400,7 @@ class _EditAuthorContentState extends State<_EditAuthorContent>
child: SizedBox(
width: 60, height: 60,
child: CachedNetworkImage(imageUrl: imageUrl, fit: BoxFit.cover,
+ httpHeaders: headers,
placeholder: (_, __) => Container(color: cs.surfaceContainerHighest),
errorWidget: (_, __, ___) => Container(color: cs.surfaceContainerHighest,
child: Icon(Icons.person_rounded, size: 28, color: cs.onSurfaceVariant)),
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
index 505c8a62..8163ade0 100644
--- a/lib/widgets/episode_list_sheet.dart
+++ b/lib/widgets/episode_list_sheet.dart
@@ -616,15 +616,25 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
// Metadata chips
const SizedBox(height: 12),
- Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
+ Builder(builder: (_) {
+ final unfinishedCount = _episodes.where((e) {
+ final epId = (e is Map<String, dynamic>) ? (e['id'] as String? ?? '') : '';
+ if (epId.isEmpty) return false;
+ final pd = lib.getEpisodeProgressData(_itemId, epId);
+ final isFinished = pd?['isFinished'] == true;
+ return !isFinished;
+ }).length;
+ return Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
if (!_isLoading) _chip(Icons.podcasts_rounded, l.episodeListEpisodeCount(_episodes.length)),
+ if (unfinishedCount > 0) _chip(Icons.fiber_new_rounded, l.episodeListUnfinishedCount(unfinishedCount), highlight: true),
if (_autoDownloadEnabled) _chip(Icons.downloading_rounded, l.episodeListAutoDownloadChip),
if (_subscribed) _chip(Icons.notifications_active_rounded, l.episodeListSubscribedChip, highlight: true),
..._genres.take(3).map((g) => _chip(Icons.tag_rounded, g)),
if (_language.isNotEmpty) _chip(Icons.language_rounded, _language.toUpperCase()),
if (_explicit) _chip(Icons.explicit_rounded, l.episodeListExplicitChip),
if (_type.isNotEmpty && _type != 'episodic') _chip(Icons.list_rounded, _type[0].toUpperCase() + _type.substring(1)),
- ]),
+ ]);
+ }),
// Episodes section header
const SizedBox(height: 16),
diff --git a/lib/widgets/library_authors_tab.dart b/lib/widgets/library_authors_tab.dart
index d216dbde..8d6a2de9 100644
--- a/lib/widgets/library_authors_tab.dart
+++ b/lib/widgets/library_authors_tab.dart
@@ -7,16 +7,18 @@ class LibraryAuthorsTab extends StatelessWidget {
final List<Map<String, dynamic>> authors;
final bool isLoadingAuthors;
final bool authorsLoaded;
- final ScrollController scrollController;
final Future<void> Function() onRefresh;
+ final Widget? headerSliver;
+ final ScrollController? scrollController;
const LibraryAuthorsTab({
super.key,
required this.authors,
required this.isLoadingAuthors,
required this.authorsLoaded,
- required this.scrollController,
required this.onRefresh,
+ this.headerSliver,
+ this.scrollController,
});
@override
@@ -25,51 +27,69 @@ class LibraryAuthorsTab extends StatelessWidget {
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
+ final headers = <Widget>[if (headerSliver != null) headerSliver!];
+
+ Widget body;
if (isLoadingAuthors) {
- return const Center(child: CircularProgressIndicator());
- }
- if (authors.isEmpty && authorsLoaded) {
- return RefreshIndicator(
- onRefresh: onRefresh,
- child: CustomScrollView(
- physics: const AlwaysScrollableScrollPhysics(),
- slivers: [
- SliverFillRemaining(
- child: Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.people_outline_rounded,
- size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
- const SizedBox(height: 12),
- Text(l.libraryNoAuthorsFound,
- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
- ],
- ),
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ const SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(child: CircularProgressIndicator()),
+ ),
+ ],
+ );
+ } else if (authors.isEmpty && authorsLoaded) {
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.people_outline_rounded,
+ size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ const SizedBox(height: 12),
+ Text(l.libraryNoAuthorsFound,
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ ],
),
),
- ],
- ),
+ ),
+ ],
);
- }
-
- return RefreshIndicator(
- onRefresh: onRefresh,
- child: GridView.builder(
+ } else {
+ body = CustomScrollView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: responsiveGridCount(context),
- childAspectRatio: 0.68,
- crossAxisSpacing: 10,
- mainAxisSpacing: 10,
- ),
- itemCount: authors.length,
- itemBuilder: (context, index) {
- return GridAuthorTile(author: authors[index]);
- },
- ),
- );
+ slivers: [
+ ...headers,
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
+ sliver: SliverGrid(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: responsiveGridCount(context),
+ childAspectRatio: 0.68,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 10,
+ ),
+ delegate: SliverChildBuilderDelegate(
+ (context, index) => GridAuthorTile(author: authors[index]),
+ childCount: authors.length,
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ return RefreshIndicator(onRefresh: onRefresh, child: body);
}
}
diff --git a/lib/widgets/library_books_tab.dart b/lib/widgets/library_books_tab.dart
index 4113b0bd..df9d9fd4 100644
--- a/lib/widgets/library_books_tab.dart
+++ b/lib/widgets/library_books_tab.dart
@@ -7,7 +7,6 @@ class LibraryBooksTab extends StatelessWidget {
final List<Map<String, dynamic>> items;
final bool isLoadingPage;
final bool hasMore;
- final ScrollController scrollController;
final LibraryFilter filter;
final String? genreFilter;
final bool rectangleCovers;
@@ -15,18 +14,35 @@ class LibraryBooksTab extends StatelessWidget {
final Future<void> Function() onRefresh;
final VoidCallback onClearFilter;
+ /// Optional sliver inserted at the top of this tab's scroll view (typically
+ /// a SliverAppBar containing the shared library header). When non-null, the
+ /// tab is responsible for owning its own scroll position so the SliverAppBar
+ /// floats independently.
+ final Widget? headerSliver;
+
+ /// Called when the user scrolls within ~400px of the bottom; library_screen
+ /// owns the actual page-fetch logic.
+ final VoidCallback onLoadMore;
+
+ /// Optional explicit ScrollController. When tabs are kept alive in an
+ /// IndexedStack each one needs its own controller so scroll positions don't
+ /// collide on the PrimaryScrollController.
+ final ScrollController? scrollController;
+
const LibraryBooksTab({
super.key,
required this.items,
required this.isLoadingPage,
required this.hasMore,
- required this.scrollController,
required this.filter,
this.genreFilter,
required this.rectangleCovers,
required this.coverAspectRatio,
required this.onRefresh,
required this.onClearFilter,
+ required this.onLoadMore,
+ this.headerSliver,
+ this.scrollController,
});
@override
@@ -35,10 +51,22 @@ class LibraryBooksTab extends StatelessWidget {
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
+ final headers = <Widget>[if (headerSliver != null) headerSliver!];
+
+ Widget body;
if (items.isEmpty && isLoadingPage) {
- return const Center(child: CircularProgressIndicator());
- }
- if (items.isEmpty && !isLoadingPage) {
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ const SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(child: CircularProgressIndicator()),
+ ),
+ ],
+ );
+ } else if (items.isEmpty && !isLoadingPage) {
final filterMsg = switch (filter) {
LibraryFilter.inProgress => l.libraryNoBooksInProgress,
LibraryFilter.finished => l.libraryNoFinishedBooks,
@@ -49,67 +77,84 @@ class LibraryBooksTab extends StatelessWidget {
LibraryFilter.genre => l.libraryNoBooksInGenre(genreFilter ?? l.genre.toLowerCase()),
LibraryFilter.none => l.libraryNoBooks,
};
- return RefreshIndicator(
- onRefresh: onRefresh,
- child: CustomScrollView(
- physics: const AlwaysScrollableScrollPhysics(),
- slivers: [
- SliverFillRemaining(
- child: Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.library_books_outlined,
- size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
- const SizedBox(height: 12),
- Text(filterMsg,
- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
- if (filter != LibraryFilter.none) ...[
- const SizedBox(height: 8),
- GestureDetector(
- onTap: onClearFilter,
- child: Text(l.libraryClearFilter,
- style: tt.bodySmall?.copyWith(color: cs.primary)),
- ),
- ],
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.library_books_outlined,
+ size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ const SizedBox(height: 12),
+ Text(filterMsg,
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ if (filter != LibraryFilter.none) ...[
+ const SizedBox(height: 8),
+ GestureDetector(
+ onTap: onClearFilter,
+ child: Text(l.libraryClearFilter,
+ style: tt.bodySmall?.copyWith(color: cs.primary)),
+ ),
],
- ),
+ ],
),
),
- ],
- ),
+ ),
+ ],
);
- }
-
- return RefreshIndicator(
- onRefresh: onRefresh,
- child: GridView.builder(
+ } else {
+ body = CustomScrollView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: responsiveGridCount(context),
- childAspectRatio: rectangleCovers ? 0.48 : 0.68,
- crossAxisSpacing: 10,
- mainAxisSpacing: 10,
- ),
- itemCount: items.length + (hasMore ? 1 : 0),
- itemBuilder: (context, index) {
- if (index >= items.length) {
- return const Center(
- child: Padding(
- padding: EdgeInsets.all(16),
- child: CircularProgressIndicator(strokeWidth: 2),
+ slivers: [
+ ...headers,
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
+ sliver: SliverGrid(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: responsiveGridCount(context),
+ childAspectRatio: rectangleCovers ? 0.48 : 0.68,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 10,
+ ),
+ delegate: SliverChildBuilderDelegate(
+ (context, index) {
+ if (index >= items.length) {
+ return const Center(
+ child: Padding(
+ padding: EdgeInsets.all(16),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
+ final item = items[index];
+ if (item.containsKey('collapsedSeries')) {
+ return GridSeriesTile(item: item, coverAspectRatio: coverAspectRatio);
+ }
+ return GridBookTile(item: item, coverAspectRatio: coverAspectRatio);
+ },
+ childCount: items.length + (hasMore ? 1 : 0),
+ ),
),
- );
- }
- final item = items[index];
- if (item.containsKey('collapsedSeries')) {
- return GridSeriesTile(item: item, coverAspectRatio: coverAspectRatio);
+ ),
+ ],
+ );
+ }
+
+ return NotificationListener<ScrollNotification>(
+ onNotification: (n) {
+ if (n is ScrollUpdateNotification &&
+ n.metrics.pixels >= n.metrics.maxScrollExtent - 400) {
+ onLoadMore();
}
- return GridBookTile(item: item, coverAspectRatio: coverAspectRatio);
+ return false;
},
- ),
+ child: RefreshIndicator(onRefresh: onRefresh, child: body),
);
}
}
diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dart
index 6bd603c4..30d44ca6 100644
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@ -64,6 +64,8 @@ class _GridBookTileState extends State<GridBookTile> {
final isDownloaded = _dl.isDownloaded(itemId);
final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;
final isSubscribed = lib.isPodcastLibrary && lib.isPodcastSubscribed(itemId);
+ final unfinishedCount =
+ lib.isPodcastLibrary ? lib.getUnfinishedEpisodeCount(widget.item) : 0;
return GestureDetector(
onTap: () {
@@ -105,11 +107,34 @@ class _GridBookTileState extends State<GridBookTile> {
),
),
- // Subscribed bell
- if (isSubscribed)
+ // Unplayed-episode count badge (podcasts only)
+ if (unfinishedCount > 0)
Positioned(
top: 4,
right: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6, vertical: 2),
+ decoration: BoxDecoration(
+ color: cs.primary,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Text(
+ '$unfinishedCount',
+ style: TextStyle(
+ color: cs.onPrimary,
+ fontSize: 10,
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ ),
+ ),
+
+ // Subscribed bell (sits below unplayed badge when both show)
+ if (isSubscribed)
+ Positioned(
+ top: unfinishedCount > 0 ? 26 : 4,
+ right: 4,
child: Container(
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
@@ -124,7 +149,7 @@ class _GridBookTileState extends State<GridBookTile> {
// Explicit badge
if (isExplicit)
Positioned(
- top: isSubscribed ? 22 : 4,
+ top: (unfinishedCount > 0 ? 26 : 4) + (isSubscribed ? 22 : 0),
right: 4,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
@@ -288,37 +313,31 @@ class _StackedCovers extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l = AppLocalizations.of(context)!;
- final count = coverUrls.length.clamp(1, 4);
+ // Cap at 3 stacked covers (front + two back). 4 was visually busy and the
+ // extra image decodes + per-shadow blur repaints made the Series grid
+ // visibly janky during scroll.
+ final count = coverUrls.length.clamp(1, 3);
const inset = 5.0;
final totalOffset = count > 1 ? inset * (count - 1) : 0.0;
return AspectRatio(
aspectRatio: coverAspectRatio,
- child: Stack(
+ child: RepaintBoundary(
+ child: Stack(
children: [
- // Back covers (furthest back first so front paints on top)
+ // Back covers (furthest back first so front paints on top). Drop
+ // the per-back-cover BoxShadow blur — front cover's shadow is
+ // enough visual depth and blurred shadows are expensive.
for (int i = count - 1; i > 0; i--)
Positioned(
top: (totalOffset - i * inset),
right: (totalOffset - i * inset),
left: i * inset,
bottom: i * inset,
- child: DecoratedBox(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(10),
- boxShadow: [
- BoxShadow(
- color: Colors.black.withValues(alpha: 0.15),
- blurRadius: 2,
- offset: const Offset(-1, 1),
- ),
- ],
- ),
- child: ClipRRect(
- borderRadius: BorderRadius.circular(10),
- child: _coverImage(coverUrls[i]),
- ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: _coverImage(coverUrls[i]),
),
),
// Front cover (bottom-left)
@@ -421,6 +440,7 @@ class _StackedCovers extends StatelessWidget {
),
],
),
+ ),
);
}
diff --git a/lib/widgets/library_narrators_tab.dart b/lib/widgets/library_narrators_tab.dart
index b4b94225..80dc7a57 100644
--- a/lib/widgets/library_narrators_tab.dart
+++ b/lib/widgets/library_narrators_tab.dart
@@ -7,16 +7,18 @@ class LibraryNarratorsTab extends StatelessWidget {
final List<String> narrators;
final bool isLoading;
final bool loaded;
- final ScrollController scrollController;
final Future<void> Function() onRefresh;
+ final Widget? headerSliver;
+ final ScrollController? scrollController;
const LibraryNarratorsTab({
super.key,
required this.narrators,
required this.isLoading,
required this.loaded,
- required this.scrollController,
required this.onRefresh,
+ this.headerSliver,
+ this.scrollController,
});
@override
@@ -25,75 +27,95 @@ class LibraryNarratorsTab extends StatelessWidget {
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
+ final headers = <Widget>[if (headerSliver != null) headerSliver!];
+
+ Widget body;
if (isLoading) {
- return const Center(child: CircularProgressIndicator());
- }
- if (narrators.isEmpty && loaded) {
- return RefreshIndicator(
- onRefresh: onRefresh,
- child: CustomScrollView(
- physics: const AlwaysScrollableScrollPhysics(),
- slivers: [
- SliverFillRemaining(
- child: Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.mic_none_rounded,
- size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
- const SizedBox(height: 12),
- Text(l.libraryNoNarratorsFound,
- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
- ],
- ),
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ const SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(child: CircularProgressIndicator()),
+ ),
+ ],
+ );
+ } else if (narrators.isEmpty && loaded) {
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.mic_none_rounded,
+ size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ const SizedBox(height: 12),
+ Text(l.libraryNoNarratorsFound,
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ ],
),
),
- ],
- ),
+ ),
+ ],
);
- }
-
- return RefreshIndicator(
- onRefresh: onRefresh,
- child: ListView.separated(
+ } else {
+ body = CustomScrollView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
- itemCount: narrators.length,
- separatorBuilder: (_, __) => Divider(
- height: 1,
- thickness: 0.5,
- color: cs.outlineVariant.withValues(alpha: 0.4),
- ),
- itemBuilder: (context, index) {
- final name = narrators[index];
- return InkWell(
- borderRadius: BorderRadius.circular(8),
- onTap: () => showNarratorBooksSheet(context, narratorName: name),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 14),
- child: Row(
- children: [
- Icon(Icons.mic_rounded, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.6)),
- const SizedBox(width: 14),
- Expanded(
- child: Text(
- name,
- style: tt.bodyLarge?.copyWith(
- color: cs.onSurface,
- fontWeight: FontWeight.w500,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
+ slivers: [
+ ...headers,
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
+ sliver: SliverList.separated(
+ itemCount: narrators.length,
+ separatorBuilder: (_, __) => Divider(
+ height: 1,
+ thickness: 0.5,
+ color: cs.outlineVariant.withValues(alpha: 0.4),
+ ),
+ itemBuilder: (context, index) {
+ final name = narrators[index];
+ return InkWell(
+ borderRadius: BorderRadius.circular(8),
+ onTap: () => showNarratorBooksSheet(context, narratorName: name),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 14),
+ child: Row(
+ children: [
+ Icon(Icons.mic_rounded,
+ size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.6)),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Text(
+ name,
+ style: tt.bodyLarge?.copyWith(
+ color: cs.onSurface,
+ fontWeight: FontWeight.w500,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ Icon(Icons.chevron_right_rounded,
+ size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ],
),
),
- Icon(Icons.chevron_right_rounded, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
- ],
- ),
+ );
+ },
),
- );
- },
- ),
- );
+ ),
+ ],
+ );
+ }
+
+ return RefreshIndicator(onRefresh: onRefresh, child: body);
}
}
diff --git a/lib/widgets/library_series_tab.dart b/lib/widgets/library_series_tab.dart
index 0277c1ca..4b6d143b 100644
--- a/lib/widgets/library_series_tab.dart
+++ b/lib/widgets/library_series_tab.dart
@@ -7,20 +7,24 @@ class LibrarySeriesTab extends StatelessWidget {
final List<Map<String, dynamic>> seriesItems;
final bool isLoadingSeriesPage;
final bool hasMoreSeries;
- final ScrollController scrollController;
final bool rectangleCovers;
final double coverAspectRatio;
final Future<void> Function() onRefresh;
+ final VoidCallback onLoadMore;
+ final Widget? headerSliver;
+ final ScrollController? scrollController;
const LibrarySeriesTab({
super.key,
required this.seriesItems,
required this.isLoadingSeriesPage,
required this.hasMoreSeries,
- required this.scrollController,
required this.rectangleCovers,
required this.coverAspectRatio,
required this.onRefresh,
+ required this.onLoadMore,
+ this.headerSliver,
+ this.scrollController,
});
@override
@@ -29,59 +33,89 @@ class LibrarySeriesTab extends StatelessWidget {
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
+ final headers = <Widget>[if (headerSliver != null) headerSliver!];
+
+ Widget body;
if (seriesItems.isEmpty && isLoadingSeriesPage) {
- return const Center(child: CircularProgressIndicator());
- }
- if (seriesItems.isEmpty && !isLoadingSeriesPage) {
- return RefreshIndicator(
- onRefresh: onRefresh,
- child: CustomScrollView(
- physics: const AlwaysScrollableScrollPhysics(),
- slivers: [
- SliverFillRemaining(
- child: Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.collections_bookmark_outlined,
- size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
- const SizedBox(height: 12),
- Text(l.libraryNoSeriesFound,
- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
- ],
- ),
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ const SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(child: CircularProgressIndicator()),
+ ),
+ ],
+ );
+ } else if (seriesItems.isEmpty && !isLoadingSeriesPage) {
+ body = CustomScrollView(
+ controller: scrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ ...headers,
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.collections_bookmark_outlined,
+ size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ const SizedBox(height: 12),
+ Text(l.libraryNoSeriesFound,
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ ],
),
),
- ],
- ),
+ ),
+ ],
);
- }
-
- return RefreshIndicator(
- onRefresh: onRefresh,
- child: GridView.builder(
+ } else {
+ body = CustomScrollView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: responsiveGridCount(context),
- childAspectRatio: rectangleCovers ? 0.48 : 0.68,
- crossAxisSpacing: 10,
- mainAxisSpacing: 10,
- ),
- itemCount: seriesItems.length + (hasMoreSeries ? 1 : 0),
- itemBuilder: (context, index) {
- if (index >= seriesItems.length) {
- return const Center(
- child: Padding(
- padding: EdgeInsets.all(16),
- child: CircularProgressIndicator(strokeWidth: 2),
+ slivers: [
+ ...headers,
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
+ sliver: SliverGrid(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: responsiveGridCount(context),
+ childAspectRatio: rectangleCovers ? 0.48 : 0.68,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 10,
),
- );
- }
- return GridSeriesTileDirect(series: seriesItems[index], coverAspectRatio: coverAspectRatio);
- },
- ),
+ delegate: SliverChildBuilderDelegate(
+ (context, index) {
+ if (index >= seriesItems.length) {
+ return const Center(
+ child: Padding(
+ padding: EdgeInsets.all(16),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
+ return GridSeriesTileDirect(
+ series: seriesItems[index], coverAspectRatio: coverAspectRatio);
+ },
+ childCount: seriesItems.length + (hasMoreSeries ? 1 : 0),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ return NotificationListener<ScrollNotification>(
+ onNotification: (n) {
+ if (n is ScrollUpdateNotification &&
+ n.metrics.pixels >= n.metrics.maxScrollExtent - 400) {
+ onLoadMore();
+ }
+ return false;
+ },
+ child: RefreshIndicator(onRefresh: onRefresh, child: body),
);
}
}
diff --git a/lib/widgets/scroll_reveal.dart b/lib/widgets/scroll_reveal.dart
new file mode 100644
index 00000000..88ce0016
--- /dev/null
+++ b/lib/widgets/scroll_reveal.dart
@@ -0,0 +1,169 @@
+import 'package:flutter/material.dart';
+
+/// Drives a continuous 0..1 reveal value from a scroll position so headers
+/// and the bottom nav can hide/reveal in lockstep with finger movement.
+///
+/// 1.0 = fully visible, 0.0 = fully hidden. Snap to nearest end on scroll
+/// stop using a short ease, so partial states never persist.
+class ScrollRevealDriver {
+ ScrollRevealDriver({
+ required TickerProvider vsync,
+ this.hideBudgetPx = 60.0,
+ Duration snapDuration = const Duration(milliseconds: 200),
+ Curve snapCurve = Curves.easeOutCubic,
+ }) : _snapCurve = snapCurve {
+ _snapController = AnimationController(vsync: vsync, duration: snapDuration);
+ _snapController.addListener(_onSnapTick);
+ }
+
+ /// Pixels of accumulated scroll delta that take the bar from shown to hidden.
+ final double hideBudgetPx;
+ final Curve _snapCurve;
+
+ /// Continuous 0..1. Bind your SizeTransition / SlideTransition to this.
+ final ValueNotifier<double> notifier = ValueNotifier(1.0);
+
+ late final AnimationController _snapController;
+ double _snapStart = 1.0;
+ double _snapEnd = 1.0;
+
+ ScrollController? _attached;
+ double _lastOffset = 0.0;
+ bool _enabled = true;
+
+ /// Sign of the most recent meaningful scroll delta: +1 = scrolling down
+ /// (hide direction), -1 = scrolling up (show direction). Used by `settle`
+ /// so a stop mid-scroll snaps in the direction the user was already going,
+ /// rather than always snapping to the nearest 0/1 endpoint.
+ int _lastDir = 0;
+ double _lastPixels = 0.0;
+
+ /// Hook the driver to the currently visible scroll controller. Switching
+ /// tabs should call this with the new controller; the previous one is
+ /// detached and the offset baseline is rebased so the bar doesn't jump.
+ void attach(ScrollController controller) {
+ if (identical(_attached, controller)) return;
+ detach();
+ _attached = controller;
+ _lastOffset = controller.hasClients ? controller.offset : 0.0;
+ controller.addListener(_onScroll);
+ }
+
+ void detach() {
+ _attached?.removeListener(_onScroll);
+ _attached = null;
+ }
+
+ /// Force the bar fully visible without animation. Safe to call from
+ /// lifecycle events, tab switches, search activation, etc.
+ void resetToShown() {
+ _snapController.stop();
+ notifier.value = 1.0;
+ _lastOffset = _attached?.offset ?? 0.0;
+ _lastDir = 0;
+ }
+
+ /// Disable scroll-driven hiding (use during search). Snaps bar to shown
+ /// while disabled so the user always sees navigation.
+ void setEnabled(bool enabled) {
+ if (_enabled == enabled) return;
+ _enabled = enabled;
+ if (!enabled) resetToShown();
+ }
+
+ void _onScroll() {
+ if (!_enabled) return;
+ final c = _attached;
+ if (c == null || !c.hasClients) return;
+ final offset = c.offset;
+ final delta = offset - _lastOffset;
+ _lastOffset = offset;
+ _lastPixels = offset;
+
+ if (offset <= 0) {
+ if (notifier.value < 1.0) {
+ _snapController.stop();
+ notifier.value = 1.0;
+ }
+ return;
+ }
+ if (delta.abs() < 0.5) return;
+ _lastDir = delta > 0 ? 1 : -1;
+
+ final current = notifier.value;
+ final next = (current - delta / hideBudgetPx).clamp(0.0, 1.0);
+ // Skip no-op updates so we don't trigger an AppShell rebuild + Scaffold
+ // relayout on every scroll tick after the bar is already fully hidden or
+ // fully visible. This is the difference between buttery scroll and jank.
+ if ((current - next).abs() < 0.005) return;
+
+ _snapController.stop();
+ notifier.value = next;
+ }
+
+ /// Feed a scroll delta directly. Use when listening via NotificationListener
+ /// instead of attaching a ScrollController (e.g. across multiple per-tab
+ /// scroll views in an IndexedStack).
+ void noteScroll(double scrollDelta, double pixels) {
+ if (!_enabled) return;
+ _lastPixels = pixels;
+ if (pixels <= 0) {
+ if (notifier.value < 1.0) {
+ _snapController.stop();
+ notifier.value = 1.0;
+ }
+ return;
+ }
+ if (scrollDelta.abs() < 0.5) return;
+ _lastDir = scrollDelta > 0 ? 1 : -1;
+ final current = notifier.value;
+ final next = (current - scrollDelta / hideBudgetPx).clamp(0.0, 1.0);
+ if ((current - next).abs() < 0.005) return;
+ _snapController.stop();
+ notifier.value = next;
+ }
+
+ /// Animate to the end matching the last scroll direction (so a stop while
+ /// the user was still scrolling down hides the bar; a stop while scrolling
+ /// up shows it). At the very top of the scroll, always show. Wire to
+ /// ScrollEndNotification.
+ void settle() {
+ if (!_enabled) {
+ notifier.value = 1.0;
+ return;
+ }
+ final v = notifier.value;
+ final c = _attached;
+ final atTop = (c != null && c.hasClients && c.offset <= 0) ||
+ (c == null && _lastPixels <= 0);
+ final double target;
+ if (atTop) {
+ target = 1.0;
+ } else if (_lastDir < 0) {
+ target = 1.0; // scrolling up — finish revealing
+ } else if (_lastDir > 0) {
+ target = 0.0; // scrolling down — finish hiding
+ } else {
+ // No recorded direction (rare): fall back to nearest end.
+ target = v >= 0.5 ? 1.0 : 0.0;
+ }
+ if ((v - target).abs() < 0.001) return;
+ _snapStart = v;
+ _snapEnd = target;
+ _snapController
+ ..value = 0.0
+ ..forward();
+ }
+
+ void _onSnapTick() {
+ final t = _snapCurve.transform(_snapController.value);
+ notifier.value = _snapStart + (_snapEnd - _snapStart) * t;
+ }
+
+ void dispose() {
+ detach();
+ _snapController.removeListener(_onSnapTick);
+ _snapController.dispose();
+ notifier.dispose();
+ }
+}
diff --git a/pubspec.lock b/pubspec.lock
index 131aecef..40ec7cbc 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -551,10 +551,10 @@ packages:
dependency: transitive
description:
name: matcher
- sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6"
+ sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
url: "https://pub.dev"
source: hosted
- version: "0.12.18"
+ version: "0.12.19"
material_color_utilities:
dependency: transitive
description:
@@ -1036,10 +1036,10 @@ packages:
dependency: transitive
description:
name: test_api
- sha256: "93167629bfc610f71560ab9312acdda4959de4df6fac7492c89ff0d3886f6636"
+ sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a"
url: "https://pub.dev"
source: hosted
- version: "0.7.9"
+ version: "0.7.10"
timezone:
dependency: transitive
description: