A cross platform Audiobookshelf client for Android and iOS
Dart
Embed ebook reader on card flip back
Barnabas174c11e8ce5d
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dartindex d9e61e10..2d64acb5 100644--- a/lib/widgets/absorbing_card.dart+++ b/lib/widgets/absorbing_card.dart@@ -11,6 +11,7 @@ import '../screens/app_shell.dart';import '../services/audio_player_service.dart';import '../services/download_service.dart';import 'absorbing_shared.dart';+import 'ebook_reader_view.dart';import 'card_edge_progress_bar.dart';import 'card_progress_bar.dart';import 'card_playback_controls.dart';@@ -33,8 +34,14 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliduration: const Duration(milliseconds: 600),);bool get _showingBack => _flipController.value > 0.5;+ // Lazy-mount the back face so non-readers don't pay the WebView startup cost.+ // Once mounted it stays alive across flips (kept paginated in IndexedStack).+ bool _backInitialized = false;void _toggleFlip() {if (_flipController.isAnimating) return;+ if (!_backInitialized) {+ setState(() => _backInitialized = true);+ }if (_showingBack) {_flipController.reverse();} else {@@ -47,6 +54,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliImageProvider? _coverProvider; // cached for re-deriving on theme changebool _isStarting = false;List<dynamic>? _fetchedChapters;+ Map<String, dynamic>? _fetchedEbookFile;StreamSubscription<Duration>? _chapterTrackSub;int _lastChapterIdx = -1;ui.Image? _blurredCover; // Precached blurred background@@ -75,8 +83,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}String get _author => _metadata['authorName'] as String? ?? '';double get _duration => (_media['duration'] as num?)?.toDouble() ?? 0;+ Map<String, dynamic>? get _ebookFile =>+ (_media['ebookFile'] as Map<String, dynamic>?) ?? _fetchedEbookFile;String? get _ebookExt {- final ebookFile = _media['ebookFile'] as Map<String, dynamic>?;+ final ebookFile = _ebookFile;if (ebookFile == null) return null;final fn = (ebookFile['metadata'] as Map<String, dynamic>?)?['filename'] as String??? ebookFile['name'] as String?;@@ -208,9 +218,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}Future<void> _fetchChaptersIfNeeded() async {- // If chapters are already available, skip- if (_chapters.isNotEmpty) return;- // Fetch full item to get chapters+ // Skip when the inline item already has both chapters and ebookFile+ final inlineEbook = _media['ebookFile'] as Map<String, dynamic>?;+ if (_chapters.isNotEmpty && inlineEbook != null) return;+ // Fetch full item to fill in whatever's missingfinal auth = context.read<AuthProvider>();final api = auth.apiService;if (api == null) return;@@ -218,6 +229,11 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClifinal fullItem = await api.getLibraryItem(_itemId);if (fullItem != null && mounted) {final media = fullItem['media'] as Map<String, dynamic>? ?? {};+ // Cache ebookFile if the inline item didn't have it+ if (inlineEbook == null) {+ final ef = media['ebookFile'] as Map<String, dynamic>?;+ if (ef != null) setState(() => _fetchedEbookFile = ef);+ }// Books: chapters at media levelvar chapters = media['chapters'] as List<dynamic>? ?? [];// Podcasts: chapters on the specific episode@@ -322,6 +338,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli_blurredCover?.dispose();_blurredCover = null;_fetchedChapters = null;+ _fetchedEbookFile = null;_lastChapterIdx = -1;_fetchChaptersIfNeeded();}@@ -465,28 +482,36 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}final showBookBar = (!_isPodcastEpisode || _chapters.isNotEmpty) && (!lib.isPodcastLibrary || _chapters.isNotEmpty);++ // Build both faces ONCE per parent rebuild (not per animation frame).+ // The AnimatedBuilder below only updates the rotation matrix; the heavy+ // child trees (front content + embedded reader) are stable references.+ final frontFace = _buildFront(context, cs, accent, isDark, l, lib, progress, chapterIdx, totalChapters, bookProgress, showBookBar);+ final backFace = _backInitialized+ ? Transform(+ alignment: Alignment.center,+ // Counter-rotate so back content reads correctly when card is fully flipped.+ transform: Matrix4.identity()..rotateY(3.1415926535),+ child: _buildBack(context, cs, accent, isDark),+ )+ : const SizedBox.shrink();+return AnimatedBuilder(animation: _flipController,- builder: (context, _) {+ builder: (context, child) {final t = _flipController.value;final angle = t * 3.1415926535;- final showingBack = t > 0.5;- final transform = Matrix4.identity()- ..setEntry(3, 2, 0.0015) // perspective- ..rotateY(angle);- // The back face also rotates with the same matrix; counter-rotate its- // contents by pi so it reads correctly when on top.- final backChildTransform = Matrix4.identity()..rotateY(3.1415926535);return Transform(alignment: Alignment.center,- transform: transform,- child: showingBack- ? Transform(- alignment: Alignment.center,- transform: backChildTransform,- child: _buildBack(context, cs, accent, isDark),- )- : _buildFront(context, cs, accent, isDark, l, lib, progress, chapterIdx, totalChapters, bookProgress, showBookBar),+ transform: Matrix4.identity()+ ..setEntry(3, 2, 0.0015) // perspective+ ..rotateY(angle),+ child: IndexedStack(+ alignment: Alignment.center,+ sizing: StackFit.passthrough,+ index: t > 0.5 ? 1 : 0,+ children: [frontFace, backFace],+ ),);},);@@ -961,9 +986,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliWidget _buildBack(BuildContext context, ColorScheme cs, Color accent, bool isDark) {final tt = Theme.of(context).textTheme;+ final ebookFile = _ebookFile;return Container(decoration: BoxDecoration(- color: isDark ? Colors.black.withValues(alpha: 0.85) : Colors.white.withValues(alpha: 0.95),+ color: isDark ? Colors.black : Colors.white,borderRadius: BorderRadius.circular(24),border: Border.all(color: accent.withValues(alpha: 0.15), width: 1),),@@ -971,28 +997,31 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliborderRadius: BorderRadius.circular(23),child: Stack(children: [- Padding(- padding: const EdgeInsets.all(24),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(_title, style: tt.headlineSmall?.copyWith(fontWeight: FontWeight.w700, color: cs.onSurface)),- if (_author.isNotEmpty) ...[- const SizedBox(height: 6),- Text(_author, style: tt.titleMedium?.copyWith(color: cs.onSurface.withValues(alpha: 0.7))),- ],- const SizedBox(height: 16),- Divider(color: cs.onSurface.withValues(alpha: 0.15)),- const SizedBox(height: 16),- Text('Back of card', style: tt.titleSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6), fontWeight: FontWeight.w600)),- const SizedBox(height: 8),- Text(- 'This is where the ebook reader will live. Tap the flip icon to return to the player.',- style: tt.bodyMedium?.copyWith(color: cs.onSurface.withValues(alpha: 0.8)),+ if (ebookFile != null)+ EbookReaderView(+ key: ValueKey('embedded-reader-$_itemId'),+ itemId: _itemId,+ title: _title,+ ebookFile: ebookFile,+ embedded: true,+ onClose: _toggleFlip,+ )+ else+ Padding(+ padding: const EdgeInsets.all(24),+ child: Center(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(Icons.menu_book_rounded, size: 36, color: cs.onSurface.withValues(alpha: 0.4)),+ const SizedBox(height: 12),+ Text('No ebook attached', style: tt.titleSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6))),+ ],),- ],+ ),),- ),+ // Always-visible flip-back affordance, since the reader's own+ // controls are hidden until tapped.Positioned(top: 8,right: 8,diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 251575d3..15f9569f 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -37,7 +37,7 @@ import 'collection_picker_sheet.dart';import 'absorb_wave_icon.dart';import 'edit_metadata_sheet.dart';import 'stackable_sheet.dart';-import '../screens/ebook_reader_screen.dart';+import 'ebook_reader_view.dart';// ─── BOOK DETAIL BOTTOM SHEET ───────────────────────────────@@ -985,7 +985,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {void _openEbookReader(BuildContext context, AuthProvider auth, Map<String, dynamic> ebookFile, String title) {Navigator.of(context, rootNavigator: true).push(MaterialPageRoute(- builder: (_) => EbookReaderScreen(+ builder: (_) => EbookReaderView(itemId: widget.itemId,title: title,ebookFile: ebookFile,diff --git a/lib/screens/ebook_reader_screen.dart b/lib/widgets/ebook_reader_view.dartsimilarity index 93%rename from lib/screens/ebook_reader_screen.dartrename to lib/widgets/ebook_reader_view.dartindex 8e50fde9..c4eb441a 100644--- a/lib/screens/ebook_reader_screen.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -13,23 +13,36 @@ import '../services/audio_player_service.dart';import '../services/ebook_annotation_service.dart';import '../services/scoped_prefs.dart';-class EbookReaderScreen extends StatefulWidget {+class EbookReaderView extends StatefulWidget {final String itemId;final String title;final Map<String, dynamic> ebookFile;-- const EbookReaderScreen({+ /// When true, renders without a Scaffold wrapper / SafeArea / SystemChrome+ /// changes — for use inside another widget like the absorbing card back.+ final bool embedded;+ /// Replaces the back button's behavior. Defaults to Navigator.pop in+ /// full-screen mode; in embedded mode the host should provide one (e.g. to+ /// flip the card back to the front face).+ final VoidCallback? onClose;+ /// Only shown in embedded mode. Tap surfaces an "expand to full screen"+ /// affordance the host can wire up.+ final VoidCallback? onExpand;++ const EbookReaderView({super.key,required this.itemId,required this.title,required this.ebookFile,+ this.embedded = false,+ this.onClose,+ this.onExpand,});@override- State<EbookReaderScreen> createState() => _EbookReaderScreenState();+ State<EbookReaderView> createState() => _EbookReaderViewState();}-class _EbookReaderScreenState extends State<EbookReaderScreen> {+class _EbookReaderViewState extends State<EbookReaderView> {EpubController? _epubController;bool _loading = true;String? _error;@@ -88,7 +101,9 @@ class _EbookReaderScreenState extends State<EbookReaderScreen> {_fontSize = await ScopedPrefs.getInt(_kFontSize) ?? 16;_lineHeight = await ScopedPrefs.getDouble(_kLineHeight) ?? 1.4;_margin = await ScopedPrefs.getInt(_kMargin) ?? 16;- _isPaginated = await ScopedPrefs.getBool(_kPaginated) ?? true;+ // Embedded view always uses scrolled layout — paginated mode doesn't fit+ // the small card and the host owns the page-flip metaphor.+ _isPaginated = widget.embedded ? false : (await ScopedPrefs.getBool(_kPaginated) ?? true);if (mounted) setState(() {});}@@ -164,10 +179,16 @@ class _EbookReaderScreenState extends State<EbookReaderScreen> {}void _setFullscreen(bool fullscreen) {+ if (widget.embedded) return; // host owns system chromeif (fullscreen) {SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);} else {- SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);+ // Explicitly show top + bottom bars. edgeToEdge alone doesn't reliably+ // undo immersiveSticky on every Android version.+ SystemChrome.setEnabledSystemUIMode(+ SystemUiMode.manual,+ overlays: SystemUiOverlay.values,+ );}}@@ -1011,6 +1032,30 @@ class _EbookReaderScreenState extends State<EbookReaderScreen> {);}+ /// Wraps a body in a Scaffold for full-screen mode, or returns it directly+ /// (sized to fill the parent) for embedded mode.+ Widget _wrap(Widget body, Color bg, {PreferredSizeWidget? appBar}) {+ if (widget.embedded) {+ return ColoredBox(color: bg, child: body);+ }+ return Scaffold(backgroundColor: bg, appBar: appBar, body: body);+ }++ /// SafeArea is only needed in full-screen mode — embedded callers manage+ /// their own insets.+ Widget _maybeSafeArea({required Widget child, bool top = true, bool bottom = true}) {+ if (widget.embedded) return child;+ return SafeArea(top: top, bottom: bottom, child: child);+ }++ void _handleClose() {+ if (widget.onClose != null) {+ widget.onClose!();+ } else {+ Navigator.pop(context);+ }+ }+@overrideWidget build(BuildContext context) {final cs = Theme.of(context).colorScheme;@@ -1018,35 +1063,36 @@ class _EbookReaderScreenState extends State<EbookReaderScreen> {final bg = isDark ? Colors.black : Colors.white;if (_loading) {- return Scaffold(- backgroundColor: bg,+ return _wrap(+ const Center(child: CircularProgressIndicator(strokeWidth: 2)),+ bg,appBar: AppBar(title: Text(widget.title, maxLines: 1, overflow: TextOverflow.ellipsis),backgroundColor: Colors.transparent,),- body: const Center(child: CircularProgressIndicator(strokeWidth: 2)),);}if (_error != null || _cachedFile == null) {- return Scaffold(- appBar: AppBar(title: Text(widget.title)),- body: Center(+ return _wrap(+ Center(child: Padding(padding: const EdgeInsets.all(32),child: Text(_error ?? 'Unknown error', textAlign: TextAlign.center,style: TextStyle(color: cs.onSurfaceVariant)),),),+ bg,+ appBar: AppBar(title: Text(widget.title)),);}- return Scaffold(- backgroundColor: bg,- body: Stack(- children: [+ // EpubViewer + overlays. SafeAreas around the viewer and overlays are+ // skipped in embedded mode (the host card already insets us).+ final viewerBody = Stack(+ children: [// Epub viewer with safe area padding for camera cutouts- SafeArea(+ _maybeSafeArea(child: SizedBox.expand(child: EpubViewer(key: ValueKey(_viewerKey),@@ -1126,16 +1172,25 @@ class _EbookReaderScreenState extends State<EbookReaderScreen> {colors: [bg.withValues(alpha: 0.9), bg.withValues(alpha: 0.0)],),),- child: SafeArea(+ child: _maybeSafeArea(bottom: false,child: Padding(padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),child: Row(children: [IconButton(- icon: Icon(Icons.arrow_back_rounded, color: cs.onSurface),- onPressed: () => Navigator.pop(context),+ icon: Icon(+ widget.embedded ? Icons.flip_to_front_rounded : Icons.arrow_back_rounded,+ color: cs.onSurface,+ ),+ onPressed: _handleClose,),+ if (widget.embedded && widget.onExpand != null)+ IconButton(+ icon: Icon(Icons.fullscreen_rounded, color: cs.onSurface),+ tooltip: 'Expand',+ onPressed: widget.onExpand,+ ),Expanded(child: Text(widget.title,@@ -1200,7 +1255,7 @@ class _EbookReaderScreenState extends State<EbookReaderScreen> {colors: [bg.withValues(alpha: 0.9), bg.withValues(alpha: 0.0)],),),- child: SafeArea(+ child: _maybeSafeArea(top: false,child: Padding(padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),@@ -1247,7 +1302,7 @@ class _EbookReaderScreenState extends State<EbookReaderScreen> {Positioned(left: 0,right: 0,- bottom: MediaQuery.of(context).padding.bottom + 16,+ bottom: (widget.embedded ? 0 : MediaQuery.of(context).padding.bottom) + 16,child: Center(child: Material(elevation: 8,@@ -1295,8 +1350,8 @@ class _EbookReaderScreenState extends State<EbookReaderScreen> {),),],- ),- );+ );+ return _wrap(viewerBody, bg);}}