-
-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathlibrary_browse_tab.dart
More file actions
2106 lines (1900 loc) · 79 KB
/
Copy pathlibrary_browse_tab.dart
File metadata and controls
2106 lines (1900 loc) · 79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import '../../../media/ids.dart';
import 'package:flutter/material.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image_ce/cached_network_image.dart';
import '../../../media/library_first_character.dart';
import '../../../media/library_query.dart';
import '../../../media/media_backend.dart';
import '../../../media/media_item.dart';
import '../../../media/media_kind.dart';
import '../../../providers/multi_server_provider.dart';
import '../../../utils/media_server_http_client.dart';
import '../../../exceptions/media_server_exceptions.dart';
import '../../../focus/dpad_navigator.dart';
import '../../../focus/input_mode_tracker.dart';
import '../../../media/media_filter.dart';
import '../../../media/media_sort.dart';
import '../../../widgets/settings_builder.dart';
import '../../../services/image_cache_service.dart';
import '../../../services/library_query_translator.dart';
import '../../../services/plex_constants.dart';
import '../../../utils/error_message_utils.dart';
import '../../../utils/app_logger.dart';
import '../../../utils/grid_size_calculator.dart';
import '../../../utils/layout_constants.dart';
import '../../../utils/media_image_helper.dart';
import '../../../utils/provider_extensions.dart';
import '../alpha_jump_bar.dart';
import '../alpha_jump_helper.dart';
import '../alpha_scroll_handle.dart';
import '../library_browse_grouping.dart';
import '../library_alpha_bar_strategy.dart';
import '../library_alpha_scroll_metrics.dart';
import '../library_filter_sort_loader.dart';
import '../../../widgets/focusable_media_card.dart';
import '../../../widgets/focusable_filter_chip.dart';
import '../../../widgets/listenable_selector.dart';
import '../../../widgets/loading_indicator_box.dart';
import '../../../widgets/media_grid_delegate.dart';
import '../../../widgets/sliver_cross_axis_layout_builder.dart';
import '../../../widgets/media_card_list_layout.dart';
import '../../../widgets/bottom_sheet_page_scaffold.dart';
import '../../../widgets/overlay_sheet.dart';
import '../../../mixins/library_tab_focus_mixin.dart';
import '../../../services/plex_client.dart';
import '../folder_tree_view.dart';
import '../filters_bottom_sheet.dart';
import '../sort_bottom_sheet.dart';
import '../../../widgets/app_icon.dart';
import '../../../widgets/focusable_list_tile.dart';
import '../content_state_builder.dart';
import '../../../services/storage_service.dart';
import '../../../services/settings_service.dart';
import '../../../mixins/grid_focus_node_mixin.dart';
import '../../../mixins/item_updatable.dart';
import '../../../mixins/watch_state_aware.dart';
import '../../../mixins/deletion_aware.dart';
import '../../../mixins/paginated_item_loader.dart';
import '../../../widgets/card_inflation_budget.dart';
import '../../../widgets/skeleton_media_card.dart';
import '../../../widgets/sliver_child_memo.dart';
import '../../../widgets/app_refresh_indicator.dart';
import '../../../utils/deletion_notifier.dart';
import '../../../utils/global_key_utils.dart';
import '../../../utils/watch_state_notifier.dart';
import '../../../utils/platform_detector.dart';
import '../../../i18n/strings.g.dart';
import '../../main_screen.dart';
import 'base_library_tab.dart';
/// Browse tab for library screen
/// Shows library items with grouping, filtering, and sorting
class LibraryBrowseTab extends BaseLibraryTab<MediaItem> {
/// Invoked whenever the tab resets its inner scroll position to the top
/// (filter/sort change, library reload, etc.). Lets the parent resync the
/// outer floating header — see `_resetOuterScroll` in libraries_screen.
final VoidCallback? onResetScroll;
/// Notifies the parent when the active-filter state changes so the app
/// bar can badge the Library options action on mobile.
final ValueChanged<bool>? onFiltersActiveChanged;
final bool canGroupByFolders;
const LibraryBrowseTab({
super.key,
required super.library,
required this.canGroupByFolders,
super.viewMode,
super.density,
super.onDataLoaded,
super.isActive,
super.suppressAutoFocus,
super.onBack,
this.onResetScroll,
this.onFiltersActiveChanged,
});
@override
State<LibraryBrowseTab> createState() => _LibraryBrowseTabState();
}
class _LibraryBrowseTabState extends BaseLibraryTabState<MediaItem, LibraryBrowseTab>
with
ItemUpdatable,
LibraryTabFocusMixin,
GridFocusNodeMixin,
WatchStateAware,
DeletionAware,
PaginatedItemLoader<MediaItem, LibraryBrowseTab>,
SkeletonUpgradeScheduler {
@override
String? get itemServerId => widget.library.serverId;
String _toGlobalKey(String ratingKey, {required ServerId serverId}) => buildGlobalKey(serverId, ratingKey);
@override
String? get deletionServerId => widget.library.serverId;
@override
String? get watchStateServerId => widget.library.serverId;
@override
Set<String>? get watchedIds => loadedItems.values.map((e) => e.id).toSet();
@override
Set<String>? get watchedGlobalKeys {
if (loadedItems.isEmpty) return <String>{};
final keys = <String>{};
for (final item in loadedItems.values) {
final serverId = serverIdOrNull(item.serverId ?? widget.library.serverId);
if (serverId == null) return null;
keys.add(_toGlobalKey(item.id, serverId: serverId));
}
return keys;
}
@override
Set<String>? get deletionIds => loadedItems.values.map((e) => e.id).toSet();
@override
Set<String>? get deletionGlobalKeys {
if (loadedItems.isEmpty) return <String>{};
final keys = <String>{};
for (final item in loadedItems.values) {
final serverId = serverIdOrNull(item.serverId ?? widget.library.serverId);
if (serverId == null) return null;
keys.add(_toGlobalKey(item.id, serverId: serverId));
}
return keys;
}
@override
void onWatchStateChanged(WatchStateEvent event) {
if (event.changeType == WatchStateChangeType.progressUpdate ||
event.changeType == WatchStateChangeType.removedFromContinueWatching) {
return;
}
final affectedIds = {event.itemId, ...event.parentChain};
for (final item in loadedItems.values) {
if (affectedIds.contains(item.id)) {
unawaited(updateItem(item.id));
}
}
}
@override
void onDeletionEvent(DeletionEvent event) {
// Browse is online-only (the Libraries tab is hidden when offline), so it
// always reflects server-side content. A download-only deletion removes
// local files but leaves the item on the server, so it must not affect the
// browse grid. Without this guard, deleting every downloaded episode of a
// show drives its leafCount to zero and evicts the show from browse.
if (event.isDownloadOnly) return;
// If we have an item that matches the rating key exactly, remove it and rebuild indices
final matchEntry = loadedItems.entries.where((e) => e.value.id == event.itemId).firstOrNull;
if (matchEntry != null) {
setState(() {
removeLoadedItemAndShift(matchEntry.key);
});
return;
}
// If a child item was deleted, update our item to reflect that.
// If all children were deleted, remove our item.
// Otherwise, just update the counts.
for (final parentKey in event.parentChain) {
final parentEntry = loadedItems.entries.where((e) => e.value.id == parentKey).firstOrNull;
if (parentEntry != null) {
final item = parentEntry.value;
final newLeafCount = (item.leafCount ?? 1) - event.leafCount;
if (newLeafCount <= 0) {
setState(() {
removeLoadedItemAndShift(parentEntry.key);
});
} else {
setState(() {
loadedItems[parentEntry.key] = item.copyWith(leafCount: newLeafCount);
});
}
return;
}
}
// If neither the item nor its parents are loaded (evicted), the event
// was already filtered by DeletionAware's upstream check against
// deletionGlobalKeys/deletionIds, so this point is unreachable.
// The grid self-corrects when the next page fetch updates totalSize from
// the server response on the next scroll.
}
@override
String get focusNodeDebugLabel => 'browse_first_item';
@override
int get itemCount => totalSize;
@override
void updateItemInLists(String itemId, MediaItem updatedMetadata) {
for (final entry in loadedItems.entries) {
if (entry.value.id == itemId) {
loadedItems[entry.key] = updatedMetadata;
break;
}
}
}
// Browse-specific state (not in base class)
List<MediaFilter> _filters = [];
List<MediaSort> _sortOptions = [];
Map<String, String> _selectedFilters = {};
MediaSort? _selectedSort;
bool _isSortDescending = false;
String _selectedGrouping = 'all'; // all, seasons, episodes, folders
// Alpha jump bar state
List<LibraryFirstCharacter> _firstCharacters = [];
AlphaJumpHelper _alphaHelper = AlphaJumpHelper(const []);
late LibraryAlphaBarStrategy _alphaStrategy = _createAlphaStrategy();
/// On Jellyfin libraries the alpha bar acts as a filter (matches the
/// JF web client's UX). Holds the active letter (`#`, `A`–`Z`) or null
/// when no filter is applied.
String? _jellyfinAlphaPrefix;
/// Pre-fetched filter values for Jellyfin libraries — populated by
/// `_loadContent` and consumed by the FiltersBottomSheet so the sheet
/// doesn't need to call back into a Plex client for value listings.
Map<String, List<MediaFilterValue>> _jellyfinFilterValues = const {};
final ValueNotifier<int> _currentFirstVisibleIndex = ValueNotifier<int>(0);
LibraryAlphaScrollMetrics _scrollMetrics = LibraryAlphaScrollMetrics.empty;
/// Reuses card widgets across delegate swaps so tab-level setStates
/// (pagination, watch state, deletions) don't rebuild every realized card
/// inside grid layout.
final SliverChildMemo<MediaItem> _cardMemo = SliverChildMemo<MediaItem>();
/// Shared by focus-node eviction and card-memo pruning so the memo can
/// never outlive the focus nodes its cached cards capture.
static const int _focusNodeKeepCount = 200;
double _effectiveTopPadding = _gridTopPadding;
final GlobalKey _firstListItemKey = GlobalKey(debugLabel: 'first_library_list_item');
double? _measuredListRowHeight;
int? _listMetricsDensity;
bool? _listMetricsUsesWideRatio;
CardShape? _listMetricsShape;
final FocusNode _alphaJumpBarFocusNode = FocusNode(debugLabel: 'alpha_jump_bar');
// When the user taps a letter, pin the highlight so scroll-based recalculation
// doesn't immediately override it (e.g. when the letter has fewer items than a full row).
bool _hasJumpPin = false;
// True while a jump-triggered animateTo is in progress — suppresses all
// scroll-based letter recalculation to prevent flashing.
bool _isJumpScrolling = false;
// Incremented on each jump so that overlapping animations don't clobber each other.
int _jumpScrollGeneration = 0;
// Scroll activity tracking (for phone scroll handle and range-load gating)
final ValueNotifier<bool> _isScrollActive = ValueNotifier<bool>(false);
Timer? _scrollActivityTimer;
// Alpha bar update: throttle (leading edge) + trailing timer (ensures final position)
DateTime? _lastAlphaUpdate;
Timer? _alphaUpdateTimer;
/// Generation counter for the filter/sort loading phase of [_loadContent].
/// Separate from the mixin's pagination generation so a filter reload can
/// invalidate in-flight filter/sort fetches without touching item pagination.
int _contentRequestId = 0;
int _firstCharactersRequestId = 0;
static const int _fetchSize = 200;
static const int _jellyfinFetchSize = 72;
Timer? _scrollIdleTimer;
bool _rangeLoadScheduled = false;
bool _topScrollResetScheduled = false;
LibraryAlphaBarStrategy _createAlphaStrategy() {
final library = widget.library;
return LibraryAlphaBarStrategy.forBackend(
library.backend,
// Resolved on demand and only invoked by [PlexAlphaBarStrategy], which is
// only constructed when the library's backend is Plex — the bang is safe.
plexClientProvider: () {
final manager = context.read<MultiServerProvider>().serverManager;
final serverId = serverIdOrNull(library.serverId);
if (serverId == null) throw StateError('Plex library ${library.id} is missing a serverId');
return manager.getPlexClient(serverId)!;
},
libraryKey: library.id,
isShared: library.isShared,
);
}
@override
void didUpdateWidget(covariant LibraryBrowseTab oldWidget) {
// BaseLibraryTabState reloads during super.didUpdateWidget; refresh this
// first so first-character requests target the new backend/library.
if (oldWidget.library.globalKey != widget.library.globalKey ||
oldWidget.library.id != widget.library.id ||
oldWidget.library.backend != widget.library.backend ||
oldWidget.library.serverId != widget.library.serverId ||
oldWidget.library.isShared != widget.library.isShared) {
_alphaStrategy = _createAlphaStrategy();
}
super.didUpdateWidget(oldWidget);
if (oldWidget.canGroupByFolders != widget.canGroupByFolders) {
final normalized = _normalizeGrouping(_selectedGrouping);
if (normalized != _selectedGrouping) {
_selectedGrouping = normalized;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
unawaited(_loadItems());
unawaited(_loadFirstCharacters());
});
}
}
}
bool get _isJellyfinLibrary => widget.library.backend == MediaBackend.jellyfin;
int get _activeFetchSize => _isJellyfinLibrary ? _jellyfinFetchSize : _fetchSize;
// Focus nodes for filter chips
final FocusNode _groupingChipFocusNode = FocusNode(debugLabel: 'grouping_chip');
final FocusNode _filtersChipFocusNode = FocusNode(debugLabel: 'filters_chip');
final FocusNode _sortChipFocusNode = FocusNode(debugLabel: 'sort_chip');
// The inner CustomScrollView attaches its position to NestedScrollView's
// shared inner controller (via PrimaryScrollController), which has one
// position per kept-alive tab — making `controller.position` ambiguous and
// throw an assertion. We capture this tab's specific [ScrollPosition] from
// a Builder placed inside the slivers list, and address it directly for
// reads, listener attachment, and programmatic jumpTo/animateTo.
ScrollPosition? _innerPosition;
// Lets us trigger pull-to-refresh on the folder tree, which now lives as a
// sliver inside the same CustomScrollView (no longer self-owning RefreshIndicator).
final GlobalKey<FolderTreeViewState> _folderTreeKey = GlobalKey<FolderTreeViewState>();
void _bindInnerPosition(ScrollPosition? position) {
if (position == _innerPosition) return;
_innerPosition?.removeListener(_onScrollChanged);
_innerPosition = position;
_innerPosition?.addListener(_onScrollChanged);
}
@override
void dispose() {
disposePagination();
_scrollActivityTimer?.cancel();
_scrollIdleTimer?.cancel();
_alphaUpdateTimer?.cancel();
_innerPosition?.removeListener(_onScrollChanged);
// _innerPosition is owned by the inner CustomScrollView's Scrollable.
_groupingChipFocusNode.dispose();
_filtersChipFocusNode.dispose();
_sortChipFocusNode.dispose();
_alphaJumpBarFocusNode.dispose();
_currentFirstVisibleIndex.dispose();
_isScrollActive.dispose();
disposeGridFocusNodes();
super.dispose();
}
// Override tryFocus to use loadedItems instead of base class items list
@override
void tryFocus() {
if (widget.suppressAutoFocus) return;
// On mobile (touch mode), skip auto-focus to prevent ensureVisible()
// from interfering with TabBarView page animations
if (!InputModeTracker.isKeyboardMode(context)) return;
if (widget.isActive && hasLoadedData && !hasFocused) {
hasFocused = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) focusContentOrChrome();
});
}
}
// Override loadData to use our custom _loadContent
@override
Future<List<MediaItem>> loadData() async {
// This is called by base class loadItems(), but we override loadItems() entirely
// So this just returns empty - actual loading is done in _loadContent
return [];
}
// Override loadItems to use our custom loading with pagination
@override
Future<void> loadItems() async {
await _loadContent();
}
// Required abstract implementations from base class
@override
IconData get emptyIcon => Symbols.folder_open_rounded;
@override
String get emptyMessage => t.libraries.thisLibraryIsEmpty;
@override
String get errorContext => t.libraries.content;
// Override buildContent - not used since we override build()
@override
Widget buildContent(List<MediaItem> items) => const SizedBox.shrink();
/// Focus the first item in the grid/list/folder tree (for tab activation)
@override
void focusFirstItem() {
// In folder mode, items list is empty — focus the first folder tree item directly
if (_selectedGrouping == 'folders') {
void request() {
if (mounted && !firstItemFocusNode.hasFocus) {
firstItemFocusNode.requestFocus();
}
}
request();
WidgetsBinding.instance.addPostFrameCallback((_) => request());
return;
}
if (loadedItems.isNotEmpty) {
// Request immediately, then once more on the next frame to handle cases
// where the grid/list attaches after the initial focus attempt.
void request() {
if (mounted && loadedItems.isNotEmpty && !firstItemFocusNode.hasFocus) {
firstItemFocusNode.requestFocus();
}
}
request();
WidgetsBinding.instance.addPostFrameCallback((_) => request());
}
}
@override
bool get hasFocusableContent => _selectedGrouping == 'folders' || loadedItems.isNotEmpty;
@override
void focusContentOrChrome() {
if (hasFocusableContent) {
focusFirstItem();
} else {
focusChipsBar();
}
}
/// Height of the chips bar (padding + chip + padding)
static const double _chipsBarHeight = 32.0;
/// Focus the chips bar (for navigating from tab bar to content).
/// Called by libraries screen when pressing DOWN on tab bar.
void focusChipsBar() {
if (_usesMobileBrowseOptions) {
focusFirstItem();
return;
}
lastFocusedGridIndex = null;
_groupingChipFocusNode.requestFocus();
}
/// Show the mobile browse options sheet from the parent app bar.
void showBrowseOptionsSheet() {
if (!mounted) return;
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
final controller = OverlaySheetController.of(context);
controller.show(builder: (sheetContext) => _buildBrowseOptionsSheet(sheetContext));
}
/// Reset transient browse state before loading a different library.
void _resetForFullReload() {
_scrollActivityTimer?.cancel();
_scrollIdleTimer?.cancel();
_isScrollActive.value = false;
_hasJumpPin = false;
_isJumpScrolling = false;
_jumpScrollGeneration++;
_currentFirstVisibleIndex.value = 0;
_measuredListRowHeight = null;
// The browse tab state is kept alive across libraries, so ensure this
// tab's scroll resets to 0 (other tabs keep their own positions). Defer
// the jump because library changes call this from didUpdateWidget; jumping
// there dispatches scroll notifications while the AppBar is building.
_scheduleTopScrollReset();
}
void _scheduleTopScrollReset() {
if (_topScrollResetScheduled) return;
_topScrollResetScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_topScrollResetScheduled = false;
if (!mounted) return;
final pos = _innerPosition;
if (pos != null && pos.hasPixels && pos.pixels != 0) {
pos.jumpTo(0);
}
// Inner-only resets bypass NestedScrollView's natural delta surrender,
// leaving the outer floating header in its prior partially-hidden state.
widget.onResetScroll?.call();
});
}
Future<void> _loadContent() async {
final generation = ++_contentRequestId;
final firstCharactersGeneration = ++_firstCharactersRequestId;
_resetForFullReload();
_resetTopOfPageState();
_currentFirstVisibleIndex.value = 0;
// Plex returns categories from `/library/sections/{id}/filters` +
// `/sorts`; Jellyfin maps `/Items/Filters` into the same shape with
// values pre-cached and a hardcoded client-side sort list. Both flow
// through the unified [MediaServerClient.fetchLibraryFiltersWithValues].
final client = context.getMediaClientForLibrary(widget.library);
final loader = LibraryFilterSortLoader(clientFor: (_) => client);
try {
final storage = await StorageService.getInstance();
final savedFilters = storage.getLibraryFilters(sectionId: widget.library.globalKey);
final savedSort = storage.getLibrarySort(widget.library.globalKey);
final savedGrouping = storage.getLibraryGrouping(widget.library.globalKey);
// Resolve the restored grouping before the sort fetch — music groupings
// (albums/tracks) request their own per-type sort list.
final restoredGrouping = _normalizeGrouping(savedGrouping);
final sortLibraryType = _sortOptionsLibraryType(restoredGrouping);
final LoadedFiltersAndSorts loaded;
if (_isJellyfinLibrary) {
// `/Items/Filters` can be much slower than the paged `/Items` browse
// request on large Jellyfin libraries. Load only the local sort list
// before page 1, then fill filter values in the background.
final sorts = await client.fetchSortOptions(widget.library.id, libraryType: sortLibraryType);
loaded = LoadedFiltersAndSorts(filters: const [], sorts: sorts);
} else {
// Plex filters+sorts must resolve before items so saved-sort restoration
// can match a saved key against the just-loaded sort list, and so the
// first item fetch already includes the restored sort param.
loaded = await loader.load(widget.library, sortLibraryType: sortLibraryType);
}
if (generation != _contentRequestId || !mounted) return;
setState(() {
_filters = loaded.filters;
_sortOptions = loaded.sorts;
// Plex returns no cached values (filters fetched lazily per-category);
// assigning the empty map is a no-op for Plex and a real payload for Jellyfin.
_jellyfinFilterValues = loaded.cachedValues;
_selectedFilters = Map.from(savedFilters);
_selectedGrouping = restoredGrouping;
// Restore sort
if (savedSort != null) {
final sortKey = savedSort['key'] as String?;
if (sortKey != null) {
final sort = loaded.sorts.where((s) => s.key == sortKey).firstOrNull;
if (sort != null) {
_selectedSort = sort;
_isSortDescending = (savedSort['descending'] as bool?) ?? false;
}
}
}
});
_notifyFiltersActive();
if (_isJellyfinLibrary) {
_loadJellyfinFiltersInBackground(generation);
}
// Load items and first characters in parallel
// _loadItems manages its own requestId internally
await Future.wait([_loadItems(), _loadFirstCharacters(requestId: firstCharactersGeneration)]);
} catch (e) {
if (!mounted) return;
setState(() {
errorMessage = _getErrorMessage(e);
isLoading = false;
});
}
}
void _loadJellyfinFiltersInBackground(int generation) {
final client = context.getMediaClientForLibrary(widget.library);
unawaited(
client
.fetchLibraryFiltersWithValues(widget.library.id)
.then((result) {
if (generation != _contentRequestId || !mounted) return;
setState(() {
_filters = result.filters;
_jellyfinFilterValues = result.cachedValues;
});
})
.catchError((Object e, StackTrace st) {
appLogger.w('Jellyfin library filters failed; browse content remains available', error: e, stackTrace: st);
}),
);
}
/// Reports `_selectedFilters.isNotEmpty` to the parent post-frame, since
/// filter state also mutates during load paths driven by initState /
/// didUpdateWidget where a synchronous parent setState would throw.
void _notifyFiltersActive() {
final cb = widget.onFiltersActiveChanged;
if (cb == null) return;
final active = _selectedFilters.isNotEmpty;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) cb(active);
});
}
/// Initial UI state both Plex and Jellyfin paths need before fetching:
/// loading flag set, lists cleared, filter/sort caches reset.
void _resetTopOfPageState() {
setState(() {
isLoading = true;
errorMessage = null;
items = [];
resetPaginationState();
_filters = [];
_sortOptions = [];
_jellyfinFilterValues = const {};
_jellyfinAlphaPrefix = null;
_selectedFilters = {};
_selectedSort = null;
_isSortDescending = false;
_selectedGrouping = _getDefaultGrouping();
_firstCharacters = [];
_alphaHelper = AlphaJumpHelper(const []);
_scrollMetrics = LibraryAlphaScrollMetrics.empty;
_measuredListRowHeight = null;
});
_notifyFiltersActive();
}
/// Build the filter params map for API calls
Map<String, String> _buildFilterParams() {
final filterParams = Map<String, String>.from(_selectedFilters);
// Add grouping type filter (but not for 'all' or 'folders')
if (_selectedGrouping != 'all' && _selectedGrouping != 'folders') {
final typeId = _getGroupingTypeId();
if (typeId.isNotEmpty) {
filterParams['type'] = typeId;
}
} else if (_selectedGrouping == 'all' && widget.library.isShared) {
// Shared libraries: filter to video content only (exclude library section entries)
filterParams['type'] = PlexMetadataType.videoCsv;
}
// Add sort
if (_selectedSort != null) {
filterParams['sort'] = _selectedSort!.getSortKey(descending: _isSortDescending);
}
filterParams['includeCollections'] = '1';
// Jellyfin alpha-bar filter — picked up by DataAggregationService and
// converted to NameStartsWith / NameLessThan on the wire.
if (_jellyfinAlphaPrefix != null) {
filterParams['alphaPrefix'] = _jellyfinAlphaPrefix!;
}
return filterParams;
}
Future<void> _loadItems({bool preserveFocus = false}) async {
final generation = _contentRequestId;
setState(() {
isLoading = true;
items = [];
resetPaginationState();
// Increment content version when loading fresh content
// This invalidates the last focused index
gridContentVersion++;
cleanupGridFocusNodes(0);
// All focus nodes were just disposed; cached cards captured them.
_cardMemo.clear();
});
try {
final initialPage = await loadInitialPageWithStatus(_calculateInitialFetchSize());
if (!initialPage.applied || generation != _contentRequestId || !mounted) return;
setState(() {
isLoading = false;
});
hasLoadedData = true;
if (!preserveFocus) {
tryFocus();
}
// Notify parent
if (!preserveFocus && widget.onDataLoaded != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
widget.onDataLoaded!();
});
}
} catch (e) {
if (generation != _contentRequestId || !mounted) return;
setState(() {
errorMessage = _getErrorMessage(e);
isLoading = false;
});
}
}
@override
Future<LibraryPage<MediaItem>> fetchPage(int start, int size, AbortController? abort) async {
final client = context.getMediaClientForLibrary(widget.library);
final filterParams = _buildFilterParams();
final query = libraryQueryFromPlexMap(
map: filterParams,
libraryKind: filterParams.containsKey('type') ? null : widget.library.kind,
offset: start,
limit: size,
);
return client.fetchLibraryPagedContent(
widget.library.id,
query: query,
libraryKind: widget.library.kind,
abort: abort,
);
}
@override
void onPageLoaded(int start, List<MediaItem> pageItems) {
_prefetchImages(start, pageItems);
}
String _getDefaultGrouping() {
return defaultLibraryBrowseGrouping(widget.library);
}
String _normalizeGrouping(String? grouping) {
return normalizeLibraryBrowseGrouping(widget.library, grouping, canGroupByFolders: widget.canGroupByFolders);
}
String _getGroupingTypeId() {
switch (_selectedGrouping) {
case 'movies':
return '1';
case 'shows':
return '2';
case 'seasons':
return '3';
case 'episodes':
return '4';
case 'artists':
return '8';
case 'albums':
return '9';
case 'tracks':
return '10';
default:
return '';
}
}
/// `libraryType` for sort-option fetches. Plex music sections serve a
/// distinct sort list per type (`?type=9|10` for albums/tracks), so the
/// active grouping picks the type; every other grouping shares the
/// library's own list.
String _sortOptionsLibraryType(String grouping) {
return switch (grouping) {
browseGroupingAlbums => MediaKind.album.id,
browseGroupingTracks => MediaKind.track.id,
_ => widget.library.kind.id,
};
}
List<String> _getGroupingOptions() {
return libraryBrowseGroupingOptions(widget.library, canGroupByFolders: widget.canGroupByFolders);
}
String _getGroupingLabel(String grouping) {
switch (grouping) {
case 'movies':
return t.libraries.groupings.movies;
case 'shows':
return t.libraries.groupings.shows;
case 'seasons':
return t.libraries.groupings.seasons;
case 'episodes':
return t.libraries.groupings.episodes;
case 'artists':
return t.libraries.groupings.artists;
case 'albums':
return t.libraries.groupings.albums;
case 'tracks':
return t.libraries.groupings.tracks;
case 'folders':
return t.libraries.groupings.folders;
default:
return t.libraries.groupings.all;
}
}
String _getErrorMessage(dynamic error) {
if (error is MediaServerHttpException) {
return mapHttpErrorToMessage(error, context: t.libraries.content);
}
return mapUnexpectedErrorToMessage(error, context: t.libraries.content);
}
Widget _buildBrowseOptionsSheet(BuildContext sheetContext) {
final controller = OverlaySheetController.of(sheetContext);
return BottomSheetPageScaffold(
title: t.libraries.libraryOptions,
icon: Symbols.tune_rounded,
shrinkWrap: true,
child: ListView(
primary: false,
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 8),
children: [
FocusableListTile(
leading: const AppIcon(Symbols.category_rounded, fill: 1),
title: Text(t.libraries.groupings.title),
subtitle: Text(_getGroupingLabel(_selectedGrouping)),
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
onTap: () => _showGroupingOptionsPage(controller),
),
if (_isFiltersChipVisible)
FocusableListTile(
leading: const AppIcon(Symbols.filter_alt_rounded, fill: 1),
title: Text(
_selectedFilters.isEmpty
? t.libraries.filters
: t.libraries.filtersWithCount(count: _selectedFilters.length),
),
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
onTap: () => _showFiltersOptionsPage(controller),
),
if (_isSortChipVisible)
FocusableListTile(
leading: const AppIcon(Symbols.sort_rounded, fill: 1),
title: Text(t.libraries.sort),
subtitle: _selectedSort == null ? null : Text(_selectedSort!.title),
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
onTap: () => _showSortOptionsPage(controller),
),
],
),
);
}
void _showGroupingBottomSheet() {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
final controller = OverlaySheetController.of(context);
controller
.show<String>(
showDragHandle: true,
builder: (sheetContext) => Column(
mainAxisSize: .min,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
child: Text(
t.libraries.groupings.title,
style: Theme.of(sheetContext).textTheme.titleMedium,
maxLines: 1,
overflow: .ellipsis,
),
),
Flexible(
child: SingleChildScrollView(
child: Column(mainAxisSize: .min, children: _buildGroupingTiles((value) => controller.close(value))),
),
),
],
),
)
.then(_handleGroupingSelection);
}
void _showGroupingOptionsPage(OverlaySheetController controller) {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
controller
.push<String>(
builder: (_) =>
_buildGroupingBottomSheet(onBack: () => controller.pop(), onSelected: (value) => controller.close(value)),
)
.then(_handleGroupingSelection);
}
Widget _buildGroupingBottomSheet({required ValueChanged<String> onSelected, VoidCallback? onBack}) {
return BottomSheetPageScaffold(
title: t.libraries.groupings.title,
icon: Symbols.category_rounded,
onBack: onBack,
shrinkWrap: true,
child: ListView(
primary: false,
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 8),
children: _buildGroupingTiles(onSelected),
),
);
}
List<Widget> _buildGroupingTiles(ValueChanged<String> onSelected) {
final options = _getGroupingOptions();
return options.map((grouping) {
final isSelected = _selectedGrouping == grouping;
return FocusableListTile(
key: ValueKey(grouping),
dense: true,
leading: AppIcon(
isSelected ? Symbols.radio_button_checked_rounded : Symbols.radio_button_unchecked_rounded,
fill: 1,
),
title: Text(_getGroupingLabel(grouping)),
onTap: () => onSelected(grouping),
);
}).toList();
}
void _handleGroupingSelection(String? value) {
if (!mounted || value == null || value == _selectedGrouping || !_getGroupingOptions().contains(value)) return;
final sortTypeChanged = _sortOptionsLibraryType(value) != _sortOptionsLibraryType(_selectedGrouping);
setState(() {
_selectedGrouping = value;
});
StorageService.getInstance().then((storage) {
storage.saveLibraryGrouping(widget.library.globalKey, value);
});
if (sortTypeChanged) {
// Music groupings serve per-type sort lists; refresh the options (and
// drop a selected sort the new list doesn't offer) before fetching
// items so the first page can't carry a sort key of the wrong type.
unawaited(_reloadSortOptionsForGrouping());
return;
}
_loadItems();
_loadFirstCharacters();
}
/// Re-fetch the sort options for the just-selected grouping's type, then
/// load items. Only called when the grouping switch changed the sort type
/// (artist/album/track on music libraries).
Future<void> _reloadSortOptionsForGrouping() async {
final generation = _contentRequestId;
final grouping = _selectedGrouping;
var sorts = const <MediaSort>[];
try {
final client = context.getMediaClientForLibrary(widget.library);
sorts = await client.fetchSortOptions(widget.library.id, libraryType: _sortOptionsLibraryType(grouping));
} catch (e, st) {
appLogger.w('Failed to load sort options for grouping $grouping', error: e, stackTrace: st);
}
if (!mounted || generation != _contentRequestId || grouping != _selectedGrouping) return;
setState(() {
_sortOptions = sorts;
if (_selectedSort != null && sorts.every((s) => s.key != _selectedSort!.key)) {
_selectedSort = null;
_isSortDescending = false;
}
});
unawaited(_loadItems());
unawaited(_loadFirstCharacters());
}
void _showFiltersBottomSheet() {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
OverlaySheetController.of(context).show(builder: (_) => _buildFiltersBottomSheet());
}
void _showFiltersOptionsPage(OverlaySheetController controller) {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();