A cross platform Audiobookshelf client for Android and iOS
Dart
Add genre home sections, persist section detail grid view
Nathan Poulsonf8991d360a74
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex d1c728d0..65689d40 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -1209,6 +1209,14 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {_hiddenSectionIds = hiddenJson.toSet();}_applyDefaultPlaylistCollectionHiding = false;+ // Load persisted genre sections+ final genreJson = await ScopedPrefs.getStringList('home_genre_sections_$libId');+ _addedGenres = genreJson.toSet();+ _genreSections = {};+ // Fetch items for each added genre in background+ for (final genre in _addedGenres) {+ _fetchGenreSectionItems(genre);+ }}Future<void> _saveSectionPrefs() async {@@ -1238,6 +1246,47 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {static const _defaultHiddenSections = {'newest-authors', 'recent-series'};+ // ── Genre home sections ──++ Set<String> get addedGenres => _addedGenres;++ Future<void> _fetchGenreSectionItems(String genre) async {+ if (_api == null || _selectedLibraryId == null) return;+ final filterValue = base64Encode(utf8.encode(genre));+ final data = await _api!.getLibraryItems(+ _selectedLibraryId!,+ filter: 'genres.$filterValue',+ limit: 20,+ sort: 'addedAt',+ desc: 1,+ );+ if (data == null) return;+ final results = data['results'] as List<dynamic>? ?? [];+ _genreSections[genre] = results;+ notifyListeners();+ }++ Future<void> addGenreSection(String genre) async {+ if (_addedGenres.contains(genre)) return;+ _addedGenres.add(genre);+ final libId = _selectedLibraryId ?? '';+ await ScopedPrefs.setStringList('home_genre_sections_$libId', _addedGenres.toList());+ await _fetchGenreSectionItems(genre);+ notifyListeners();+ }++ Future<void> removeGenreSection(String genre) async {+ _addedGenres.remove(genre);+ _genreSections.remove(genre);+ final sectionId = 'genre:$genre';+ _sectionOrder.remove(sectionId);+ _hiddenSectionIds.remove(sectionId);+ final libId = _selectedLibraryId ?? '';+ await ScopedPrefs.setStringList('home_genre_sections_$libId', _addedGenres.toList());+ await _saveSectionPrefs();+ notifyListeners();+ }+List<Map<String, dynamic>> getOrderedHomeSections() {final allSections = <String, Map<String, dynamic>>{};@@ -1271,6 +1320,17 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {};}+ for (final genre in _addedGenres) {+ final id = 'genre:$genre';+ final items = _genreSections[genre] ?? [];+ allSections[id] = {+ 'id': id,+ 'label': genre,+ 'type': 'book',+ 'entities': items,+ };+ }+allSections.removeWhere((id, _) => _hiddenSectionIds.contains(id));if (_applyDefaultPlaylistCollectionHiding) {allSections.removeWhere((id, _) =>@@ -1291,6 +1351,10 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {final id = 'collection:${(c as Map)['id']}';if (allSections.containsKey(id)) result.add(allSections[id]!);}+ for (final genre in _addedGenres) {+ final id = 'genre:$genre';+ if (allSections.containsKey(id)) result.add(allSections[id]!);+ }return result;}@@ -1325,6 +1389,12 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {'label': 'Server Collection - ${cm['name'] as String? ?? 'Collection'}',});}+ for (final genre in _addedGenres) {+ result.add({+ 'id': 'genre:$genre',+ 'label': genre,+ });+ }return result;}diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dartindex b8dbb1aa..017cf816 100644--- a/lib/providers/_lp_state.dart+++ b/lib/providers/_lp_state.dart@@ -45,6 +45,11 @@ mixin _StateMixin on ChangeNotifier {Set<String> _hiddenSectionIds = {};bool _applyDefaultPlaylistCollectionHiding = false;+ /// Genre sections added by the user (genre name -> cached items).+ Map<String, List<dynamic>> _genreSections = {};+ /// Persisted set of genre names the user has added as home sections.+ Set<String> _addedGenres = {};+final Map<String, Map<String, dynamic>> _seriesBooksCache = {};final Map<String, Map<String, dynamic>> _seriesTabCache = {};final Map<String, Map<String, dynamic>> _subSeriesCache = {};diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dartindex 0a23361a..95415cf2 100644--- a/lib/screens/home_screen.dart+++ b/lib/screens/home_screen.dart@@ -572,6 +572,16 @@ class _HomeScreenState extends State<HomeScreen> {titleTap = () => CollectionDetailSheet.show(context, section['_collectionId'] as String);sectionIcon = Icons.collections_bookmark_rounded;+ } else if (id.startsWith('genre:')) {+ sectionIcon = Icons.label_outline_rounded;+ final sectionLabel = label as String;+ titleTap = () => SectionDetailSheet.show(+ context,+ title: sectionLabel,+ icon: sectionIcon,+ entities: entities,+ coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,+ );} else {sectionIcon = _sectionIcons[id] ?? Icons.album_outlined;final sectionLabel = label as String;diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex 93d80caf..f75707ee 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -296,6 +296,9 @@ class PlayerSettings {static Future<bool> getRectangleCovers() => _get('rectangleCovers', false);static Future<void> setRectangleCovers(bool value) => _set('rectangleCovers', value, notify: true);+ static Future<bool> getSectionGridView() => _get('sectionGridView', false);+ static Future<void> setSectionGridView(bool value) => _set('sectionGridView', value);+static Future<bool> getCoverPlayButton() => _get('coverPlayButton', false);static Future<void> setCoverPlayButton(bool value) => _set('coverPlayButton', value, notify: true);diff --git a/lib/widgets/home_customize_sheet.dart b/lib/widgets/home_customize_sheet.dartindex fefb4398..b6ac17ed 100644--- a/lib/widgets/home_customize_sheet.dart+++ b/lib/widgets/home_customize_sheet.dart@@ -1,6 +1,7 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:provider/provider.dart';+import '../providers/auth_provider.dart';import '../providers/library_provider.dart';class HomeCustomizeSheet extends StatefulWidget {@@ -90,6 +91,93 @@ class _HomeCustomizeSheetState extends State<HomeCustomizeSheet> {});}+ Future<void> _showAddGenre(BuildContext context, LibraryProvider lib, ColorScheme cs, TextTheme tt) async {+ final api = context.read<AuthProvider>().apiService;+ final libraryId = lib.selectedLibraryId;+ if (api == null || libraryId == null) return;++ final filterData = await api.getLibraryFilterData(libraryId);+ if (filterData == null || !context.mounted) return;++ final genres = (filterData['genres'] as List<dynamic>? ?? [])+ .map((g) => g is Map ? (g['name'] as String? ?? '') : g.toString())+ .where((g) => g.isNotEmpty)+ .toList()+ ..sort();++ final alreadyAdded = lib.addedGenres;++ if (!context.mounted) return;+ await showModalBottomSheet(+ context: context,+ isScrollControlled: true,+ useSafeArea: true,+ backgroundColor: cs.surface,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),+ ),+ builder: (ctx) => DraggableScrollableSheet(+ initialChildSize: 0.5,+ minChildSize: 0.3,+ maxChildSize: 0.85,+ expand: false,+ builder: (ctx, sc) => Column(children: [+ const SizedBox(height: 8),+ Center(child: Container(+ width: 40, height: 4,+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.24),+ borderRadius: BorderRadius.circular(2),+ ),+ )),+ const SizedBox(height: 16),+ Text('Add Genre Section', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),+ const SizedBox(height: 4),+ Text('Pick a genre to show on your home screen',+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),+ const SizedBox(height: 12),+ Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3), indent: 20, endIndent: 20),+ Expanded(+ child: genres.isEmpty+ ? Center(child: Text('No genres found', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)))+ : ListView.builder(+ controller: sc,+ padding: const EdgeInsets.symmetric(vertical: 8),+ itemCount: genres.length,+ itemBuilder: (ctx, i) {+ final genre = genres[i];+ final added = alreadyAdded.contains(genre);+ return ListTile(+ dense: true,+ leading: Icon(Icons.label_outline_rounded, size: 18, color: cs.onSurfaceVariant),+ title: Text(genre, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),+ trailing: added+ ? Icon(Icons.check_rounded, size: 18, color: cs.primary)+ : null,+ onTap: added ? null : () async {+ await lib.addGenreSection(genre);+ _initialized = false; // force re-init to pick up the new section+ if (ctx.mounted) Navigator.pop(ctx);+ if (mounted) setState(() {});+ },+ );+ },+ ),+ ),+ ]),+ ),+ );+ }++ Future<void> _removeGenre(String genre, LibraryProvider lib) async {+ await lib.removeGenreSection(genre);+ setState(() {+ final sectionId = 'genre:$genre';+ _sections.removeWhere((s) => s['id'] == sectionId);+ _hiddenIds.remove(sectionId);+ });+ }+Future<void> _save(LibraryProvider lib) async {await lib.saveSectionOrder(_sections.map((s) => s['id']!).toList());// Sync hidden state: apply our local set to the provider@@ -142,11 +230,22 @@ class _HomeCustomizeSheetState extends State<HomeCustomizeSheet> {fontWeight: FontWeight.w600, color: cs.onSurface,)),const Spacer(),+ GestureDetector(+ onTap: () => _showAddGenre(context, lib, cs, tt),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),+ child: Icon(Icons.add_rounded, size: 24, color: cs.primary),+ ),+ ),+ const SizedBox(width: 12),GestureDetector(onTap: () => _save(lib),- child: Text('Done', style: tt.labelMedium?.copyWith(- color: cs.primary, fontWeight: FontWeight.w600,- )),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6),+ child: Text('Done', style: tt.labelLarge?.copyWith(+ color: cs.primary, fontWeight: FontWeight.w600,+ )),+ ),),]),),@@ -183,11 +282,14 @@ class _HomeCustomizeSheetState extends State<HomeCustomizeSheet> {final isHidden = _hiddenIds.contains(id);final isPlaylist = id.startsWith('playlist:');final isCollection = id.startsWith('collection:');+ final isGenre = id.startsWith('genre:');final icon = isPlaylist? Icons.playlist_play_rounded: isCollection? Icons.collections_bookmark_rounded- : (_sectionIcons[id] ?? Icons.album_outlined);+ : isGenre+ ? Icons.label_outline_rounded+ : (_sectionIcons[id] ?? Icons.album_outlined);return Container(key: ValueKey(id),@@ -210,6 +312,15 @@ class _HomeCustomizeSheetState extends State<HomeCustomizeSheet> {: cs.onSurface,)),trailing: Row(mainAxisSize: MainAxisSize.min, children: [+ if (isGenre)+ GestureDetector(+ onTap: () => _removeGenre(id.substring(6), lib),+ child: Padding(+ padding: const EdgeInsets.all(8),+ child: Icon(Icons.remove_circle_outline_rounded, size: 18,+ color: Colors.red.withValues(alpha: 0.6)),+ ),+ ),GestureDetector(onTap: () {setState(() {diff --git a/lib/widgets/section_detail_sheet.dart b/lib/widgets/section_detail_sheet.dartindex ba2e3fae..1d2f009f 100644--- a/lib/widgets/section_detail_sheet.dart+++ b/lib/widgets/section_detail_sheet.dart@@ -57,6 +57,19 @@ class SectionDetailSheet extends StatefulWidget {class _SectionDetailSheetState extends State<SectionDetailSheet> {bool _gridView = false;+ @override+ void initState() {+ super.initState();+ PlayerSettings.getSectionGridView().then((v) {+ if (mounted && v != _gridView) setState(() => _gridView = v);+ });+ }++ void _toggleGridView() {+ setState(() => _gridView = !_gridView);+ PlayerSettings.setSectionGridView(_gridView);+ }+@overrideWidget build(BuildContext context) {final cs = Theme.of(context).colorScheme;@@ -79,7 +92,7 @@ class _SectionDetailSheetState extends State<SectionDetailSheet> {style: tt.labelMedium?.copyWith(color: cs.onSurfaceVariant)),const SizedBox(width: 12),GestureDetector(- onTap: () => setState(() => _gridView = !_gridView),+ onTap: _toggleGridView,child: Icon(_gridView ? Icons.view_list_rounded : Icons.grid_view_rounded,size: 20, color: cs.onSurfaceVariant,