A cross platform Audiobookshelf client for Android and iOS
Dart
Speed up the web app and turn Absorbing into a desktop player
Barnabas172173039d3d
diff --git a/deploy/nginx/default.conf.template b/deploy/nginx/default.conf.templateindex cf4ea64f..532e4941 100644--- a/deploy/nginx/default.conf.template+++ b/deploy/nginx/default.conf.template@@ -16,6 +16,19 @@ server {root /usr/share/nginx/html;client_max_body_size 10240M;+ gzip on;+ gzip_comp_level 6;+ gzip_min_length 1024;+ gzip_proxied any;+ gzip_vary on;+ gzip_types+ application/javascript+ application/json+ application/manifest+json+ application/wasm+ image/svg+xml+ text/css;+location = /absorb {return 308 /absorb/;}diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dartindex c8776eba..eeb98850 100644--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@ -13,6 +13,7 @@ import '../services/scoped_prefs.dart';import '../widgets/absorb_page_header.dart';import '../main.dart' show flatNotifier, gradientIntensityNotifier, rootNavigatorKey;import '../widgets/absorbing_card.dart';+import '../widgets/card_chapters_sheet.dart';import '../widgets/offline_status_icon.dart';import '../widgets/overlay_toast.dart';import '../widgets/series_books_sheet.dart';@@ -23,14 +24,16 @@ import '../l10n/app_localizations.dart';import '../services/wording.dart';import '../utils/desktop_workspace.dart';-const double kAbsorbingQueuePaneBreakpoint = 1180;+const double kAbsorbingSidePanelOpenBreakpoint = 1180;-bool shouldEmbedAbsorbingQueue(double paneWidth) =>- paneWidth >= kAbsorbingQueuePaneBreakpoint;+bool shouldOpenAbsorbingSidePanelByDefault(double paneWidth) =>+ paneWidth >= kAbsorbingSidePanelOpenBreakpoint;double absorbingQueuePaneWidth(double paneWidth) =>(paneWidth * 0.32).clamp(340.0, 400.0).toDouble();+enum DesktopAbsorbingPanelTab { chapters, queue }+class AbsorbingScreen extends StatefulWidget {const AbsorbingScreen({super.key});@@ -193,6 +196,15 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {}final _desktopQueueScrollController = ScrollController();+ bool? _desktopPanelOpen;+ DesktopAbsorbingPanelTab _desktopPanelTab = DesktopAbsorbingPanelTab.chapters;+ AbsorbingChapterData? _desktopChapterData;+ String? _desktopVisibleItemKey;++ void _handleDesktopChapterData(AbsorbingChapterData data) {+ if (!mounted || data.itemKey != _desktopVisibleItemKey) return;+ setState(() => _desktopChapterData = data);+ }String? _lastPlayingId;String? _lastPlayingEpisodeId;@@ -667,8 +679,6 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {child: SafeArea(child: Builder(builder: (context) {final desktopWorkspace = isDesktopWorkspace(context);- final embedDesktopQueue = desktopWorkspace &&- shouldEmbedAbsorbingQueue(MediaQuery.sizeOf(context).width);final offlineIcon = OfflineStatusIcon(onTapWhenOnline: () {lib.setManualOffline(true);@@ -730,8 +740,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {: Icon(Icons.refresh_rounded, size: 18, color: muted),),),- if ((!desktopWorkspace || !embedDesktopQueue) &&- books.isNotEmpty) ...[+ if (!desktopWorkspace && books.isNotEmpty) ...[const SizedBox(width: 8),GestureDetector(onTap: () => _showReorderSheet(context, lib, books),@@ -817,66 +826,98 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {strokeWidth: 2,color: cs.onSurface.withValues(alpha: 0.24))): LayoutBuilder(builder: (context, constraints) {- final showQueue = shouldEmbedAbsorbingQueue(- constraints.maxWidth,- );- final queueWidth = absorbingQueuePaneWidth(- constraints.maxWidth,- );+ if (books.isEmpty) {+ _desktopVisibleItemKey = null;+ return _emptyState(cs, tt, effectiveOffline, l);+ }++ final currentKey = _absorbingKey(books[0]);+ _desktopVisibleItemKey = currentKey;+ final panelOpen = _desktopPanelOpen ??=+ shouldOpenAbsorbingSidePanelByDefault(constraints.maxWidth);+ final panelWidth = absorbingQueuePaneWidth(constraints.maxWidth);+ final chapterData = _desktopChapterData?.itemKey == currentKey+ ? _desktopChapterData+ : null;return Row(crossAxisAlignment: CrossAxisAlignment.stretch,children: [Expanded(- child: books.isEmpty- ? _emptyState(cs, tt, effectiveOffline, l)- : Center(- child: ConstrainedBox(- constraints: const BoxConstraints(- maxWidth: 980),- child: SizedBox.expand(- child: Padding(- padding: const EdgeInsets.fromLTRB(- 12, 8, 12, 16),- child: RepaintBoundary(- child: AbsorbingCard(- key: _cardKey(- _absorbingKey(books[0])),- item: books[0],- player: _player,- ),- ),- ),- ),- ),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 16),+ child: RepaintBoundary(+ child: AbsorbingCard(+ key: _cardKey(currentKey),+ item: books[0],+ player: _player,+ presentation: AbsorbingCardPresentation.desktop,+ onChapterDataChanged: _handleDesktopChapterData,+ ),+ ),+ ),+ ),+ VerticalDivider(+ width: 1,+ thickness: 1,+ color: cs.outlineVariant.withValues(alpha: 0.45),+ ),+ SizedBox(+ width: 48,+ child: Align(+ alignment: Alignment.topCenter,+ child: Padding(+ padding: const EdgeInsets.only(top: 8),+ child: IconButton(+ key: const ValueKey('desktop-absorbing-panel-toggle'),+ tooltip: panelOpen+ ? MaterialLocalizations.of(context).closeButtonTooltip+ : l.absorbingManageQueue,+ onPressed: () => setState(+ () => _desktopPanelOpen = !panelOpen,),+ icon: Icon(+ panelOpen+ ? Icons.chevron_right_rounded+ : Icons.chevron_left_rounded,+ ),+ ),+ ),+ ),),- if (showQueue) ...[- VerticalDivider(- width: 1,- thickness: 1,- color: cs.outlineVariant.withValues(- alpha: 0.45,+ TweenAnimationBuilder<double>(+ tween: Tween(end: panelOpen ? 1 : 0),+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ builder: (context, widthFactor, child) => ClipRect(+ child: Align(+ alignment: Alignment.centerRight,+ widthFactor: widthFactor,+ child: child,),),- SizedBox(- width: queueWidth,- child: _AbsorbingQueuePanel(- embedded: true,- keys: books.map(_absorbingKey).toList(),- books: books,- lib: lib,- scrollController:- _desktopQueueScrollController,- absorbingKeyFn: _absorbingKey,- queueMode: _queueMode,- isMerged: _mergeLibraries,- isPodcast: lib.isPodcastLibrary,- currentItemId: _currentPlayerKey,- onQueueModeChanged: (mode) =>- _handleQueueModeChanged(lib, mode),+ child: SizedBox(+ width: panelWidth,+ child: _buildDesktopSidePanel(+ context,+ chapterData: chapterData,+ queuePanel: _AbsorbingQueuePanel(+ embedded: true,+ showHeader: false,+ keys: books.map(_absorbingKey).toList(),+ books: books,+ lib: lib,+ scrollController: _desktopQueueScrollController,+ absorbingKeyFn: _absorbingKey,+ queueMode: _queueMode,+ isMerged: _mergeLibraries,+ isPodcast: lib.isPodcastLibrary,+ currentItemId: _currentPlayerKey,+ onQueueModeChanged: (mode) =>+ _handleQueueModeChanged(lib, mode),+ ),),),- ],+ ),],);}),@@ -1066,6 +1107,97 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {? '${_player.currentItemId}-${_player.currentEpisodeId}': _player.currentItemId;+ Widget _buildDesktopSidePanel(+ BuildContext context, {+ required AbsorbingChapterData? chapterData,+ required Widget queuePanel,+ }) {+ final cs = Theme.of(context).colorScheme;+ final l = AppLocalizations.of(context)!;+ final chaptersPanel = chapterData == null+ ? Center(child: CircularProgressIndicator(+ strokeWidth: 2,+ color: cs.onSurface.withValues(alpha: 0.24),+ ))+ : chapterData.chapters.isEmpty+ ? Center(child: Padding(+ padding: const EdgeInsets.all(24),+ child: Text(+ chapterData.episodeId == null ? l.noChaptersBook : l.noChaptersPodcast,+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodyMedium?.copyWith(+ color: cs.onSurfaceVariant,+ ),+ ),+ ))+ : CardChaptersList(+ accent: cs.primary,+ chapters: chapterData.chapters,+ totalDuration: chapterData.totalDuration,+ currentPosition: chapterData.currentPosition,+ isPlaybackActive: chapterData.isPlaybackActive,+ isCastingThis: chapterData.isCastingThis,+ displaySpeed: chapterData.displaySpeed,+ player: _player,+ itemId: chapterData.itemId,+ );++ return ColoredBox(+ color: cs.surface.withValues(alpha: 0.72),+ child: Column(children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),+ child: SizedBox(+ width: double.infinity,+ child: SegmentedButton<DesktopAbsorbingPanelTab>(+ key: const ValueKey('desktop-absorbing-panel-tabs'),+ segments: [+ ButtonSegment(+ value: DesktopAbsorbingPanelTab.chapters,+ icon: const Icon(Icons.format_list_numbered_rounded),+ label: FittedBox(+ fit: BoxFit.scaleDown,+ child: Text(l.chapters, maxLines: 1),+ ),+ ),+ ButtonSegment(+ value: DesktopAbsorbingPanelTab.queue,+ icon: const Icon(Icons.queue_music_rounded),+ label: FittedBox(+ fit: BoxFit.scaleDown,+ child: Text(l.absorbingManageQueue, maxLines: 1),+ ),+ ),+ ],+ selected: {_desktopPanelTab},+ showSelectedIcon: false,+ onSelectionChanged: (selection) {+ if (selection.isEmpty) return;+ setState(() => _desktopPanelTab = selection.first);+ },+ ),+ ),+ ),+ Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.45)),+ Expanded(+ child: IndexedStack(+ index: _desktopPanelTab.index,+ children: [+ KeyedSubtree(+ key: const ValueKey('desktop-absorbing-chapters-panel'),+ child: chaptersPanel,+ ),+ KeyedSubtree(+ key: const ValueKey('desktop-absorbing-queue-panel'),+ child: queuePanel,+ ),+ ],+ ),+ ),+ ]),+ );+ }+void _showReorderSheet(BuildContext context, LibraryProvider lib, List<Map<String, dynamic>> books) {final keys = books.map((b) => _absorbingKey(b)).toList();final media = MediaQuery.of(context);@@ -1171,6 +1303,7 @@ class _AbsorbingQueuePanel extends StatefulWidget {/// True when the panel lives inline in the desktop workspace instead of a/// bottom sheet: no sheet chrome, no self-pops, reorders commit instantly.final bool embedded;+ final bool showHeader;const _AbsorbingQueuePanel({required this.keys,@@ -1184,6 +1317,7 @@ class _AbsorbingQueuePanel extends StatefulWidget {required this.onQueueModeChanged,required this.currentItemId,this.embedded = false,+ this.showHeader = true,});@override@@ -1570,6 +1704,7 @@ class _AbsorbingQueuePanelState extends State<_AbsorbingQueuePanel> {),)),// Header+ if (widget.showHeader)Padding(padding: const EdgeInsets.fromLTRB(16, 8, 8, 4),child: Row(children: [diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dartindex 18566cf9..9d880ed5 100644--- a/lib/screens/app_shell.dart+++ b/lib/screens/app_shell.dart@@ -856,11 +856,13 @@ class _AppShellState extends State<AppShell>),],),- bottomNavigationBar: DesktopNowPlayingBar(- player: _player,- library: lib,- onOpenNowPlaying: _switchToAbsorbing,- ),+ bottomNavigationBar: shouldShowDesktopNowPlayingBar(_currentIndex)+ ? DesktopNowPlayingBar(+ player: _player,+ library: lib,+ onOpenNowPlaying: _switchToAbsorbing,+ )+ : null,);}diff --git a/lib/screens/app_shell_navigation_policy.dart b/lib/screens/app_shell_navigation_policy.dartindex cbd27636..7b0c64a5 100644--- a/lib/screens/app_shell_navigation_policy.dart+++ b/lib/screens/app_shell_navigation_policy.dart@@ -9,3 +9,5 @@ bool shouldRestoreBookLibrary({podcastsShown &&selectedLibraryId == podcastLibraryId;}++bool shouldShowDesktopNowPlayingBar(int pageIndex) => pageIndex != 2;diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dartindex 8e2eb7ba..a56caf09 100644--- a/lib/widgets/absorbing_card.dart+++ b/lib/widgets/absorbing_card.dart@@ -24,10 +24,45 @@ import '../main.dart' show colorSourceNotifier, useColorEverywhereNotifier, manuimport '../utils/desktop_workspace.dart';import 'stable_cached_network_image.dart';+enum AbsorbingCardPresentation { card, desktop }++@immutable+class AbsorbingChapterData {+ final String itemKey;+ final String itemId;+ final String? episodeId;+ final List<dynamic> chapters;+ final double totalDuration;+ final double currentPosition;+ final bool isPlaybackActive;+ final bool isCastingThis;+ final double displaySpeed;++ const AbsorbingChapterData({+ required this.itemKey,+ required this.itemId,+ required this.episodeId,+ required this.chapters,+ required this.totalDuration,+ required this.currentPosition,+ required this.isPlaybackActive,+ required this.isCastingThis,+ required this.displaySpeed,+ });+}+class AbsorbingCard extends StatefulWidget {final Map<String, dynamic> item;final AudioPlayerService player;- const AbsorbingCard({super.key, required this.item, required this.player});+ final AbsorbingCardPresentation presentation;+ final ValueChanged<AbsorbingChapterData>? onChapterDataChanged;+ const AbsorbingCard({+ super.key,+ required this.item,+ required this.player,+ this.presentation = AbsorbingCardPresentation.card,+ this.onChapterDataChanged,+ });@overrideState<AbsorbingCard> createState() => AbsorbingCardState();@@ -71,6 +106,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClidouble _savedSpeed = 1.0; // per-book or default speed for inactive displayfinal ValueNotifier<bool> _edgeBarExpanded = ValueNotifier(false);String? _lastRenderLogSig;+ int? _lastChapterDataSignature;@overridebool get wantKeepAlive => true;@@ -118,6 +154,71 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClibool get _isPlaybackActive => _isActive || _isCastingThis;bool get _isPodcastEpisode => _isActive && widget.player.currentEpisodeId != null;+ String get _itemKey => _episodeId == null ? _itemId : '$_itemId-${_episodeId!}';++ void _publishChapterData() {+ final callback = widget.onChapterDataChanged;+ if (callback == null) return;++ final cast = ChromecastService();+ final chapters = _isCastingThis && cast.castingChapters.isNotEmpty+ ? cast.castingChapters+ : _isActive && widget.player.chapters.isNotEmpty+ ? widget.player.chapters+ : _chapters;+ final totalDuration = _isCastingThis && cast.castingDuration > 0+ ? cast.castingDuration+ : _isActive && widget.player.totalDuration > 0+ ? widget.player.totalDuration+ : _effectiveDuration;+ final displaySpeed = _isCastingThis+ ? cast.castSpeed+ : _isActive+ ? widget.player.speed+ : _savedSpeed;+ final double currentPosition;+ if (_isCastingThis) {+ currentPosition = cast.castPosition.inMilliseconds / 1000.0;+ } else if (_isActive) {+ currentPosition = widget.player.position.inMilliseconds / 1000.0;+ } else {+ final lib = context.read<LibraryProvider>();+ final progress = _episodeId == null+ ? lib.getProgress(_itemId)+ : lib.getEpisodeProgress(_itemId, _episodeId!);+ currentPosition = progress * totalDuration;+ }+ final chapterHash = Object.hashAll(chapters.map((chapter) {+ if (chapter is! Map) return chapter.hashCode;+ return Object.hash(chapter['title'], chapter['start'], chapter['end']);+ }));+ final signature = Object.hash(+ _itemKey,+ chapterHash,+ totalDuration,+ _isPlaybackActive,+ _isCastingThis,+ displaySpeed,+ );+ if (signature == _lastChapterDataSignature) return;+ _lastChapterDataSignature = signature;++ final data = AbsorbingChapterData(+ itemKey: _itemKey,+ itemId: _itemId,+ episodeId: _episodeId,+ chapters: List<dynamic>.unmodifiable(chapters),+ totalDuration: totalDuration,+ currentPosition: currentPosition,+ isPlaybackActive: _isPlaybackActive,+ isCastingThis: _isCastingThis,+ displaySpeed: displaySpeed,+ );+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && _itemKey == data.itemKey) callback(data);+ });+ }+// For inactive podcast show cards: recentEpisode is embedded in the continue-listening entityMap<String, dynamic>? get _recentEpisode => widget.item['recentEpisode'] as Map<String, dynamic>?;@@ -433,6 +534,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli_fetchedChapters = null;_fetchedEbookFile = null;_lastChapterIdx = -1;+ _lastChapterDataSignature = null;_lastSeenUpdatedAt = context.read<LibraryProvider>().itemUpdatedAt(_itemId);_fetchChaptersIfNeeded();// The per-show speed is item state too - without this, a card recycled@@ -468,7 +570,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli_rederiveCoverScheme();// Precache the blurred version of the cover, but only when the blurred// background is actually in use (skip the work for gradient / off modes).- if (_cardBackground == 'blurred' &&+ if (widget.presentation != AbsorbingCardPresentation.desktop &&+ _cardBackground == 'blurred' &&_blurredCoverIdentity != coverIdentity &&_pendingBlurIdentity != coverIdentity) {_pendingBlurIdentity = coverIdentity;@@ -641,25 +744,28 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli// A chapterless book gets the same single-bar look as a chapterless// podcast: no top book bar, just the scrubber bar carrying the title.final showBookBar = _chapters.isNotEmpty;+ final desktopPresentation = widget.presentation == AbsorbingCardPresentation.desktop;+ _publishChapterData();return GestureDetector(- onVerticalDragEnd: (details) {+ onVerticalDragEnd: desktopPresentation ? null : (details) {final vy = details.primaryVelocity ?? 0;if (vy < -300) expandCard(context); // swipe up to expand},child: Container(- decoration: BoxDecoration(+ key: ValueKey(desktopPresentation ? 'desktop-absorbing-player' : 'absorbing-card-shell'),+ decoration: desktopPresentation ? null : BoxDecoration(borderRadius: BorderRadius.circular(24),border: Border.all(color: accent.withValues(alpha: 0.15), width: 1),),child: ClipRRect(- borderRadius: BorderRadius.circular(23),+ borderRadius: desktopPresentation ? BorderRadius.zero : BorderRadius.circular(23),child: Stack(fit: StackFit.expand,children: [// Layer 1: Card background — blurred cover, color gradient, or plain surface- if (_cardBackground == 'off')+ if (!desktopPresentation && _cardBackground == 'off')ColoredBox(color: Theme.of(context).colorScheme.surface)- else if (_cardBackground == 'gradient')+ else if (!desktopPresentation && _cardBackground == 'gradient')DecoratedBox(decoration: BoxDecoration(gradient: LinearGradient(@@ -670,7 +776,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli),)// Pre-blurred cover background (cached bitmap — no per-frame blur)- else if (_blurredCover != null)+ else if (!desktopPresentation && _blurredCover != null)RepaintBoundary(child: RawImage(image: _blurredCover,@@ -679,7 +785,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliheight: double.infinity,),)- else if (coverUrl != null && coverIdentity != null)+ else if (!desktopPresentation && coverUrl != null && coverIdentity != null)// Fallback while blur is being computed: show unblurred cover dimmedRepaintBoundary(child: isLocalCover@@ -710,6 +816,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli),),// Layer 2: Scrim+ if (!desktopPresentation)Positioned.fill(child: DecoratedBox(decoration: BoxDecoration(@@ -1079,6 +1186,97 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli),);+ if (desktopPresentation) {+ final episodeTitle = _episodeId == null+ ? null+ : (_isActive ? widget.player.currentEpisodeTitle : _recentEpisode?['title'] as String?);+ final primaryTitle = episodeTitle?.trim().isNotEmpty == true ? episodeTitle! : _title;+ final contextLine = <String>[+ if (_episodeId != null && _title.trim().isNotEmpty) _title,+ if (_author.trim().isNotEmpty) _author,+ ].join(' • ');+ final desktopProgress = Semantics(+ label: 'Full book progress',+ child: KeyedSubtree(+ key: const ValueKey('desktop-book-progress'),+ child: CardDualProgressBar(+ player: widget.player,+ accent: accent,+ isActive: _isActive,+ staticProgress: progress,+ staticDuration: _effectiveDuration,+ chapters: _chapters,+ showBookBar: true,+ showChapterBar: _chapters.isNotEmpty,+ chapterName: _chapterName(chapterIdx),+ chapterIndex: chapterIdx,+ totalChapters: totalChapters,+ itemId: _itemId,+ compact: compact,+ ),+ ),+ );+ final details = Center(+ child: SingleChildScrollView(+ padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 640),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ primaryTitle,+ maxLines: 3,+ overflow: TextOverflow.ellipsis,+ style: tt.headlineSmall?.copyWith(fontWeight: FontWeight.w700, height: 1.12),+ ),+ if (contextLine.isNotEmpty) ...[+ const SizedBox(height: 8),+ Text(+ contextLine,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: tt.titleSmall?.copyWith(+ color: cs.onSurfaceVariant,+ fontWeight: FontWeight.w500,+ ),+ ),+ ],+ const SizedBox(height: 22),+ desktopProgress,+ SizedBox(height: compact ? 6 : 12),+ controlsRow,+ SizedBox(height: compact ? 8 : 16),+ buttonGrid,+ ],+ ),+ ),+ ),+ );++ if (cardConstraints.maxWidth >= 760) {+ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Expanded(flex: 5, child: coverArea),+ const SizedBox(width: 16),+ Expanded(flex: 7, child: details),+ ],+ ),+ );+ }++ return Column(+ children: [+ Expanded(flex: 5, child: coverArea),+ Expanded(flex: 7, child: details),+ ],+ );+ }+if (wide) {return Row(crossAxisAlignment: CrossAxisAlignment.stretch,@@ -1114,7 +1312,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli);}),// Edge progress bar (thin strip at top of card)- if (showBookBar)+ if (!desktopPresentation && showBookBar)Positioned(top: 0,left: 0,diff --git a/lib/widgets/card_chapters_sheet.dart b/lib/widgets/card_chapters_sheet.dartindex c6a85c39..07ddbd09 100644--- a/lib/widgets/card_chapters_sheet.dart+++ b/lib/widgets/card_chapters_sheet.dart@@ -29,114 +29,283 @@ void showChaptersSheet({final ch = chapters[i] as Map<String, dynamic>;final start = (ch['start'] as num?)?.toDouble() ?? 0;final end = (ch['end'] as num?)?.toDouble() ?? 0;- if (currentPosition >= start && currentPosition < end) { currentIdx = i; break; }+ if (currentPosition >= start && currentPosition < end) {+ currentIdx = i;+ break;+ }}- final cast = ChromecastService();-showAdaptiveSheetDialog(- context: context, useSafeArea: true,+ context: context,+ useSafeArea: true,backgroundColor: Colors.transparent,widthClass: DialogWidthClass.action,- initialChildSize: 0.6, minChildSize: 0.05, snap: true, maxChildSize: 0.9,+ initialChildSize: 0.6,+ minChildSize: 0.05,+ snap: true,+ maxChildSize: 0.9,builder: (ctx, sc) {- if (currentIdx > 0) {- WidgetsBinding.instance.addPostFrameCallback((_) {- final target = currentIdx * 48.0 - 48;- if (sc.hasClients) sc.jumpTo(target.clamp(0, sc.position.maxScrollExtent));- });- }- final l = AppLocalizations.of(ctx)!;- return Container(+ if (currentIdx > 0) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ final target = currentIdx * 48.0 - 48;+ if (sc.hasClients)+ sc.jumpTo(target.clamp(0, sc.position.maxScrollExtent));+ });+ }+ final l = AppLocalizations.of(ctx)!;+ return Container(decoration: BoxDecoration(color: Theme.of(context).bottomSheetTheme.backgroundColor,borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),- border: Border(top: BorderSide(color: accent.withValues(alpha: 0.2), width: 1)),+ border: Border(+ top: BorderSide(color: accent.withValues(alpha: 0.2), width: 1),+ ),+ ),+ child: Column(+ children: [+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 12),+ child: Container(+ width: 40,+ height: 4,+ decoration: BoxDecoration(+ color: Theme.of(+ context,+ ).colorScheme.onSurface.withValues(alpha: 0.24),+ borderRadius: BorderRadius.circular(2),+ ),+ ),+ ),+ Text(+ l.chaptersCount(chapters.length),+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600),+ ),+ const SizedBox(height: 8),+ Expanded(+ child: CardChaptersList(+ accent: accent,+ chapters: chapters,+ totalDuration: totalDuration,+ currentPosition: currentPosition,+ isPlaybackActive: isPlaybackActive,+ isCastingThis: isCastingThis,+ displaySpeed: displaySpeed,+ player: player,+ itemId: itemId,+ scrollController: sc,+ closeOnSelection: true,+ ),+ ),+ ],),- child: Column(children: [- Padding(padding: const EdgeInsets.symmetric(vertical: 12),- child: Container(width: 40, height: 4, decoration: BoxDecoration(color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),- Text(l.chaptersCount(chapters.length), style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),- const SizedBox(height: 8),- Expanded(child: ListView.builder(- controller: sc, itemCount: chapters.length,- itemBuilder: (_, i) {- final ch = chapters[i] as Map<String, dynamic>;- final chTitle = ch['title'] as String? ?? l.chapterNumber(i + 1);- final start = (ch['start'] as num?)?.toDouble() ?? 0;- final end = (ch['end'] as num?)?.toDouble() ?? 0;- final pos = isCastingThis- ? cast.castPosition.inMilliseconds / 1000.0- : (player.currentItemId != null ? player.position.inMilliseconds / 1000.0 : 0.0);- final isCurrent = isPlaybackActive && pos >= start && pos < end;- final isFinished = isPlaybackActive && pos >= end;- final pct = totalDuration > 0 ? (end / totalDuration * 100).round() : 0;- final cs = Theme.of(context).colorScheme;- return ListTile(- dense: true, selected: isCurrent,- selectedTileColor: accent.withValues(alpha: 0.1),- leading: SizedBox(width: 28, child: isFinished- ? Icon(Icons.check_rounded, size: 16, color: cs.onSurfaceVariant.withValues(alpha: 0.4))- : Text('${i + 1}', textAlign: TextAlign.center,- style: tt.labelMedium?.copyWith(fontWeight: isCurrent ? FontWeight.w700 : FontWeight.w400, color: isCurrent ? accent : cs.onSurfaceVariant))),- title: Text(chTitle,- style: tt.bodyMedium?.copyWith(fontWeight: isCurrent ? FontWeight.w600 : FontWeight.w400,- color: isCurrent ? cs.onSurface : isFinished ? cs.onSurface.withValues(alpha: 0.4) : cs.onSurface.withValues(alpha: 0.7))),- trailing: Row(mainAxisSize: MainAxisSize.min, children: [- Text('$pct%', style: tt.labelSmall?.copyWith(- color: isCurrent ? accent.withValues(alpha: 0.7) : cs.onSurface.withValues(alpha: 0.24), fontSize: 10, fontWeight: FontWeight.w600)),- const SizedBox(width: 8),- Text(fmtDur((end - start) / displaySpeed), style: tt.labelSmall?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant)),- ]),- onTap: () async {- if (isPlaybackActive) {- // Active card - jump directly- final seekDur = Duration(seconds: start.round());- if (isCastingThis) {- cast.seekTo(seekDur);- } else {- player.seekTo(seekDur);- }- Navigator.pop(ctx);- } else if (itemId != null) {- // Inactive card - confirm then start playback- final confirmed = await showDialog<bool>(context: ctx, builder: (dlg) => AlertDialog(- title: Text(l.cardChaptersPlayFromChapterTitle),- content: Text(l.cardChaptersPlayFromChapterContent(chTitle)),- actions: [- TextButton(onPressed: () => Navigator.pop(dlg, false), child: Text(l.cancel)),- FilledButton(onPressed: () => Navigator.pop(dlg, true), child: Text(l.cardChaptersPlay)),- ],- ));- if (confirmed != true || !ctx.mounted) return;- Navigator.pop(ctx); // Close chapter sheet first- final api = context.read<AuthProvider>().apiService;- if (api == null) return;- final lib = context.read<LibraryProvider>();- final fullItem = await api.getLibraryItem(itemId);- if (fullItem == null) return;- final media = fullItem['media'] as Map<String, dynamic>? ?? {};- final metadata = media['metadata'] as Map<String, dynamic>? ?? {};- final title = metadata['title'] as String? ?? '';- final author = metadata['authorName'] as String? ?? '';- final coverUrl = lib.getCoverUrl(itemId);- final dur = (media['duration'] is num) ? (media['duration'] as num).toDouble() : 0.0;- final chs = (media['chapters'] as List<dynamic>?) ?? [];- await player.playItem(- api: api, itemId: itemId,- title: title, author: author, coverUrl: coverUrl,- totalDuration: dur, chapters: chs,- startTime: start, forceStartTime: true,- libraryId: fullItem['libraryId'] as String?,- );- AppShell.goToAbsorbingGlobal();- }- },- );- },- )),- ]),);},);}++/// Chapter list shared by the card chapter sheet and embedded player panels.+///+/// Set [closeOnSelection] to false when the list is embedded in a persistent+/// desktop panel. Chapter taps will still seek or start playback without+/// closing the surrounding route.+class CardChaptersList extends StatelessWidget {+ final Color accent;+ final List<dynamic> chapters;+ final double totalDuration;+ final double currentPosition;+ final bool isPlaybackActive;+ final bool isCastingThis;+ final double displaySpeed;+ final AudioPlayerService player;+ final String? itemId;+ final ScrollController? scrollController;+ final bool closeOnSelection;++ const CardChaptersList({+ super.key,+ required this.accent,+ required this.chapters,+ required this.totalDuration,+ required this.currentPosition,+ required this.isPlaybackActive,+ required this.isCastingThis,+ required this.displaySpeed,+ required this.player,+ this.itemId,+ this.scrollController,+ this.closeOnSelection = false,+ });++ @override+ Widget build(BuildContext context) {+ final cast = ChromecastService();+ final Stream<Duration>? positionStream = isCastingThis+ ? cast.castPositionStream+ : isPlaybackActive+ ? player.absolutePositionStream+ : null;++ return StreamBuilder<Duration>(+ stream: positionStream,+ initialData: Duration(milliseconds: (currentPosition * 1000).round()),+ builder: (context, snapshot) {+ final position = isCastingThis+ ? cast.castPosition.inMilliseconds / 1000.0+ : isPlaybackActive+ ? (snapshot.data ?? player.position).inMilliseconds / 1000.0+ : currentPosition;+ final tt = Theme.of(context).textTheme;+ final cs = Theme.of(context).colorScheme;+ final l = AppLocalizations.of(context)!;++ return ListView.builder(+ controller: scrollController,+ itemCount: chapters.length,+ itemBuilder: (_, i) {+ final chapter = chapters[i] as Map<String, dynamic>;+ final chapterTitle =+ chapter['title'] as String? ?? l.chapterNumber(i + 1);+ final start = (chapter['start'] as num?)?.toDouble() ?? 0;+ final end = (chapter['end'] as num?)?.toDouble() ?? 0;+ final isCurrent =+ isPlaybackActive && position >= start && position < end;+ final isFinished = isPlaybackActive && position >= end;+ final percent = totalDuration > 0+ ? (end / totalDuration * 100).round()+ : 0;++ return ListTile(+ dense: true,+ selected: isCurrent,+ selectedTileColor: accent.withValues(alpha: 0.1),+ leading: SizedBox(+ width: 28,+ child: isFinished+ ? Icon(+ Icons.check_rounded,+ size: 16,+ color: cs.onSurfaceVariant.withValues(alpha: 0.4),+ )+ : Text(+ '${i + 1}',+ textAlign: TextAlign.center,+ style: tt.labelMedium?.copyWith(+ fontWeight: isCurrent+ ? FontWeight.w700+ : FontWeight.w400,+ color: isCurrent ? accent : cs.onSurfaceVariant,+ ),+ ),+ ),+ title: Text(+ chapterTitle,+ style: tt.bodyMedium?.copyWith(+ fontWeight: isCurrent ? FontWeight.w600 : FontWeight.w400,+ color: isCurrent+ ? cs.onSurface+ : isFinished+ ? cs.onSurface.withValues(alpha: 0.4)+ : cs.onSurface.withValues(alpha: 0.7),+ ),+ ),+ trailing: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ '$percent%',+ style: tt.labelSmall?.copyWith(+ color: isCurrent+ ? accent.withValues(alpha: 0.7)+ : cs.onSurface.withValues(alpha: 0.24),+ fontSize: 10,+ fontWeight: FontWeight.w600,+ ),+ ),+ const SizedBox(width: 8),+ Text(+ fmtDur((end - start) / displaySpeed),+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ ],+ ),+ onTap: () => _selectChapter(+ context,+ chapterTitle: chapterTitle,+ start: start,+ ),+ );+ },+ );+ },+ );+ }++ Future<void> _selectChapter(+ BuildContext context, {+ required String chapterTitle,+ required double start,+ }) async {+ final seekPosition = Duration(seconds: start.round());+ if (isPlaybackActive) {+ if (isCastingThis) {+ ChromecastService().seekTo(seekPosition);+ } else {+ player.seekTo(seekPosition);+ }+ if (closeOnSelection && context.mounted) Navigator.pop(context);+ return;+ }++ if (itemId == null) return;+ final l = AppLocalizations.of(context)!;+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (dialogContext) => AlertDialog(+ title: Text(l.cardChaptersPlayFromChapterTitle),+ content: Text(l.cardChaptersPlayFromChapterContent(chapterTitle)),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(dialogContext, false),+ child: Text(l.cancel),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(dialogContext, true),+ child: Text(l.cardChaptersPlay),+ ),+ ],+ ),+ );+ if (confirmed != true || !context.mounted) return;++ final auth = context.read<AuthProvider>();+ final lib = context.read<LibraryProvider>();+ if (closeOnSelection) Navigator.pop(context);+ final api = auth.apiService;+ if (api == null) return;++ final fullItem = await api.getLibraryItem(itemId!);+ if (fullItem == null) return;+ final media = fullItem['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final title = metadata['title'] as String? ?? '';+ final author = metadata['authorName'] as String? ?? '';+ final coverUrl = lib.getCoverUrl(itemId!);+ final duration = (media['duration'] is num)+ ? (media['duration'] as num).toDouble()+ : 0.0;+ final resolvedChapters = (media['chapters'] as List<dynamic>?) ?? [];+ await player.playItem(+ api: api,+ itemId: itemId!,+ title: title,+ author: author,+ coverUrl: coverUrl,+ totalDuration: duration,+ chapters: resolvedChapters,+ startTime: start,+ forceStartTime: true,+ libraryId: fullItem['libraryId'] as String?,+ );+ AppShell.goToAbsorbingGlobal();+ }+}