perf(shell): keep the window size and download count out of MainShell

MainShell read MediaQuery.sizeOf and watched the queued download count
in its own build. Every rebuild creates new _TabNavigator widgets, and
Navigator.didUpdateWidget calls changedExternalState on every route, so
each resize frame (and each mini player animation frame on desktop) and
each download count change rebuilt every page of every tab, hidden tabs
and pushed album or playlist pages included. The count part also hit
phones on every queued or finished download.

The navigation chrome now reads both in a Consumer below the shell and
receives the same tab view instance each time, so only the chrome
rebuilds. The scroll listeners read the collapse condition without
depending on the window size. Layout, badges and the rail/bar swap are
unchanged.

Measured with a page that reads neither value, pushed in the hidden
Library tab (test/main_shell_rebuild_test.dart, desktop and phone, both
styles): 10 resize frames rebuilt it 10 times before and 0 times now;
two download count changes rebuilt it twice before and 0 times now. The
tab navigators, Navigators and tab root pages keep their instances.
This commit is contained in:
zarzet committed 2026-11-01 19:19:10 +07:00
1 parent 67bd523704
commit e9d95d27fa
2 files changed
+672 -284

No files matched your search

+342 -284
View File
@@ -70,6 +70,11 @@ part 'main_shell_startup_prompts.dart';
final _log = AppLogger('MainShell');
/// The download count on the Library destination. Only the navigation
/// chrome watches it, so a finished download does not rebuild every tab.
int _watchQueuedCount(WidgetRef ref) =>
ref.watch(downloadQueueProvider.select((s) => s.queuedCount));
/// The tab at [index] in a style's destination order.
@visibleForTesting
ShellTab shellTabAt(
@@ -549,6 +554,20 @@ class _MainShellState extends ConsumerState<MainShell>
return media.data.viewInsets.bottom > 0;
}
/// Whether scrolling may collapse the Mornye tab bar at [width].
bool _canMinimizeChromeAt(double width, TextScaler textScaler) =>
!isDesktopPlatform &&
context.isMornye &&
!useNavigationRailForWidth(width) &&
textScaler.scale(15) <= 20;
/// [_canMinimizeChromeAt] for the window now, read without depending on
/// its size, so the tab pages' scroll listeners do not rebuild the shell.
bool get _canMinimizeChrome {
final media = context.getInheritedWidgetOfExactType<MediaQuery>()!.data;
return _canMinimizeChromeAt(media.size.width, media.textScaler);
}
Future<void> _handleBackPress() async {
final rootNavigator = Navigator.of(context, rootNavigator: true);
final handledByRootNavigator = await rootNavigator.maybePop();
@@ -889,9 +908,6 @@ class _MainShellState extends ConsumerState<MainShell>
settingsProvider.select((s) => s.listeningStatisticsEnabled),
(_, enabled) => listeningRecorder.setEnabled(enabled),
);
final queueState = ref.watch(
downloadQueueProvider.select((s) => s.queuedCount),
);
final showStore = ref.watch(
settingsProvider.select((s) => s.showExtensionStore),
);
@@ -949,8 +965,174 @@ class _MainShellState extends ConsumerState<MainShell>
if (_mornyeSettingsTab) const SettingsTab(key: ValueKey('tab-settings')),
];
final maxIndex = tabs.length - 1;
final selectedDestination = _currentIndex.clamp(0, maxIndex);
if (_currentIndex > maxIndex) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() => _currentIndex = maxIndex);
if (_pageController.hasClients) {
_pageController.jumpToPage(maxIndex);
}
}
});
}
Widget observeScroll(Widget child, int index) =>
NotificationListener<ScrollNotification>(
onNotification: (notification) {
// The chrome stays expanded while the keyboard is up.
if (_canMinimizeChrome &&
index == _currentIndex &&
!_keyboardVisible) {
return _mornyeChrome.handleScroll(notification);
}
return false;
},
child: child,
);
final pageView = KeyedSubtree(
key: _pageViewKey,
child: context.isMornye || isAndroidTv
? LazyTabView(
index: selectedDestination,
preloadKeys: isAndroidTv
? const {}
: {const ValueKey('tab-search')},
children: [
for (var index = 0; index < tabs.length; index++)
KeyedSubtree(
key: tabs[index].key,
child: observeScroll(tabs[index], index),
),
],
)
: FadeTransition(
opacity: _tabJumpOpacity,
child: ScaleTransition(
scale: _tabJumpScale,
child: PageView.builder(
controller: _pageController,
itemCount: tabs.length,
onPageChanged: _onPageChanged,
physics: const NeverScrollableScrollPhysics(),
// TickerMode mutes animations and lets visibility-aware widgets
// (e.g. MotionHeaderBanner) pause when their tab is hidden;
// kept-alive pages otherwise keep running offscreen.
itemBuilder: (context, index) => _KeepAliveTabPage(
key: ValueKey('page-$index'),
child: TickerMode(
enabled: index == _currentIndex,
child: observeScroll(tabs[index], index),
),
),
),
),
),
);
// From here only the navigation chrome follows the window size and the
// download count. It gets the same tab view each time, so neither
// rebuilds the shell or the routes of its tabs; pages read them
// themselves.
if (isAndroidTv) {
return DownloadQueueFeedback(
child: BackButtonListener(
onBackButtonPressed: () async {
await _handleBackPress();
return true;
},
child: Scaffold(
body: Consumer(
child: SelectionOverlayHost(child: pageView),
builder: (context, ref, body) => TvShell(
destinations: _navigationDestinations(
queuedCount: _watchQueuedCount(ref),
repoUpdatesCount: repoUpdatesCount,
showStore: showStore,
),
selectedIndex: selectedDestination,
onSelected: _onNavTap,
child: body!,
),
),
),
),
);
}
if (isDesktopPlatform) {
// Desktop windows: a rail (Material) or source-list sidebar (Mornye)
// with a persistent player; no bottom tabs or touch gestures.
final mornye = context.isMornye;
final selectedTab = _tabForIndex(selectedDestination, showStore);
return DownloadQueueFeedback(
child: DesktopLinkTransferNotices(
child: Scaffold(
body: Consumer(
// The selection bar floats over the pages, not the sidebar.
child: SelectionOverlayHost(child: pageView),
builder: (context, ref, body) {
final queuedCount = _watchQueuedCount(ref);
return DesktopShellLayout(
destinations: _desktopDestinations(
showStore: showStore,
// Mornye shows the queue on its Downloads link instead.
queueCount: mornye ? 0 : queuedCount,
repoUpdatesCount: repoUpdatesCount,
),
selected: selectedTab,
onSelected: _onShellTabRequested,
libraryLinks: mornye
? _desktopLibraryLinks(queueCount: queuedCount)
: const [],
// The Material rail opens playlists alone.
onOpenLibraryLink: _openDesktopLibraryLink,
onOpenProfile: mornye ? _openDesktopProfile : null,
body: body!,
);
},
),
),
),
);
}
final shell = SelectionOverlayHost(
child: BackButtonListener(
onBackButtonPressed: () async {
await _handleBackPress();
return true;
},
child: Consumer(
child: pageView,
builder: (context, ref, pageView) => _mobileScaffold(
context,
ref,
pageView: pageView!,
destinations: _navigationDestinations(
queuedCount: _watchQueuedCount(ref),
repoUpdatesCount: repoUpdatesCount,
showStore: showStore,
),
selectedDestination: selectedDestination,
maxIndex: maxIndex,
),
),
),
);
return DownloadQueueFeedback(child: shell);
}
/// Phone, tablet and TV destinations, with the download count on Library.
List<NavigationDestination> _navigationDestinations({
required int queuedCount,
required int repoUpdatesCount,
required bool showStore,
}) {
final l10n = context.l10n;
final destinations = <NavigationDestination>[
return <NavigationDestination>[
NavigationDestination(
icon: AppIcon(
context.isMornye ? CupertinoIcons.house_fill : Icons.home_outlined,
@@ -962,22 +1144,22 @@ class _MainShellState extends ConsumerState<MainShell>
icon: context.isMornye
? MornyeNavigationIcon(
icon: CupertinoIcons.square_stack_fill,
badgeCount: queueState,
badgeCount: queuedCount,
)
: AnimatedBadge(
count: queueState,
count: queuedCount,
child: Badge(
isLabelVisible: queueState > 0,
label: Text('$queueState'),
isLabelVisible: queuedCount > 0,
label: Text('$queuedCount'),
child: const AppIcon(Icons.library_music_outlined),
),
),
selectedIcon: SlidingIcon(
child: AnimatedBadge(
count: queueState,
count: queuedCount,
child: Badge(
isLabelVisible: queueState > 0,
label: Text('$queueState'),
isLabelVisible: queuedCount > 0,
label: Text('$queuedCount'),
child: const AppIcon(Icons.library_music),
),
),
@@ -1028,20 +1210,18 @@ class _MainShellState extends ConsumerState<MainShell>
label: l10n.navSettings,
),
];
}
final maxIndex = tabs.length - 1;
final selectedDestination = _currentIndex.clamp(0, maxIndex);
if (_currentIndex > maxIndex) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() => _currentIndex = maxIndex);
if (_pageController.hasClients) {
_pageController.jumpToPage(maxIndex);
}
}
});
}
/// The phone and tablet chrome around [pageView]: the bottom bar, or the
/// rail in wide windows, and the mini player.
Widget _mobileScaffold(
BuildContext context,
WidgetRef ref, {
required Widget pageView,
required List<NavigationDestination> destinations,
required int selectedDestination,
required int maxIndex,
}) {
final screenSize = MediaQuery.sizeOf(context);
final isTablet = screenSize.shortestSide >= 600;
// Material follows its expanded window class: landscape tablets get the
@@ -1053,286 +1233,164 @@ class _MainShellState extends ConsumerState<MainShell>
: useMaterialNavigationRailForWidth(screenSize.width);
final compactMornyeChrome =
context.isMornye && screenSize.width >= expandedLayoutBreakpoint;
final canMinimizeChrome =
!isDesktopPlatform &&
context.isMornye &&
!useNavigationRail &&
MediaQuery.textScalerOf(context).scale(15) <= 20;
final canMinimizeChrome = _canMinimizeChromeAt(
screenSize.width,
MediaQuery.textScalerOf(context),
);
Widget observeScroll(Widget child, int index) =>
NotificationListener<ScrollNotification>(
onNotification: (notification) {
// The chrome stays expanded while the keyboard is up.
if (canMinimizeChrome &&
index == _currentIndex &&
!_keyboardVisible) {
return _mornyeChrome.handleScroll(notification);
}
return false;
},
child: child,
);
final pageView = KeyedSubtree(
key: _pageViewKey,
child: context.isMornye || isAndroidTv
? LazyTabView(
index: selectedDestination,
preloadKeys: isAndroidTv
? const {}
: {const ValueKey('tab-search')},
return Scaffold(
extendBody: true,
// The tab view keeps one element across the rail<->bar structure
// swap via _pageViewKey so rotation doesn't remount tab navigators.
body: useNavigationRail
? Row(
children: [
for (var index = 0; index < tabs.length; index++)
KeyedSubtree(
key: tabs[index].key,
child: observeScroll(tabs[index], index),
SafeArea(
right: false,
bottom: false,
child: ExpressiveNavigationRail(
selectedIndex: selectedDestination,
onDestinationSelected: _onNavTap,
backgroundColor: Theme.of(
context,
).colorScheme.surfaceContainer,
destinations: destinations,
),
),
const VerticalDivider(width: 1),
// Width-based layout (centered columns, grids) measures
// the space beside the rail rather than the whole screen.
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
final mediaQuery = MediaQuery.of(context);
return MediaQuery(
data: mediaQuery
.copyWith(
size: Size(
constraints.maxWidth,
mediaQuery.size.height,
),
)
.removePadding(removeLeft: true),
child: pageView,
);
},
),
),
],
)
: FadeTransition(
opacity: _tabJumpOpacity,
child: ScaleTransition(
scale: _tabJumpScale,
child: PageView.builder(
controller: _pageController,
itemCount: tabs.length,
onPageChanged: _onPageChanged,
physics: const NeverScrollableScrollPhysics(),
// TickerMode mutes animations and lets visibility-aware widgets
// (e.g. MotionHeaderBanner) pause when their tab is hidden —
// kept-alive pages otherwise keep running offscreen.
itemBuilder: (context, index) => _KeepAliveTabPage(
key: ValueKey('page-$index'),
child: TickerMode(
enabled: index == _currentIndex,
child: observeScroll(tabs[index], index),
: pageView,
bottomNavigationBar: Builder(
builder: (context) {
if (context.isMornye) {
return ListenableBuilder(
listenable: Listenable.merge([
ShellNavigationService.chromeBrightness,
ShellNavigationService.chromeSurface,
]),
builder: (context, child) => Theme(
data: ShellNavigationService.chromeBrightness.value == null
? Theme.of(context)
: MornyeTheme.fromContext(
context,
brightness:
ShellNavigationService.chromeBrightness.value!,
chromeSurface:
ShellNavigationService.chromeSurface.value,
),
child: child!,
),
child: SafeArea(
top: false,
minimum: const EdgeInsets.fromLTRB(20, 0, 20, 8),
// iPadOS-style chrome: one compact, centered pill rather
// than a bar spread across a landscape tablet.
child: Center(
heightFactor: 1,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: compactMornyeChrome ? 600 : double.infinity,
),
child: useNavigationRail
? const MiniPlayer()
: ValueListenableBuilder<bool>(
valueListenable: _mornyeChrome,
builder: (context, collapsed, _) => MornyeBottomBar(
collapsed:
canMinimizeChrome &&
collapsed &&
MediaQuery.viewInsetsOf(context).bottom == 0,
destinations: destinations,
selectedIndex: selectedDestination,
onSelected: _onNavTap,
onHome: () => _onNavTap(0),
onSearch: ShellNavigationService.requestSearch,
blurEnabled: ref.watch(mornyeBlurEnabledProvider),
),
),
),
),
),
);
}
final blurEnabled = ref.watch(backdropBlurEnabledProvider);
// The mini player and the bar read as one surface, so the bar
// takes the playing track's artwork scheme too; with nothing
// playing both keep the app scheme. Only this scope listens
// to the track, so a cover change does not rebuild the shell.
return Consumer(
builder: (context, ref, child) => PlayerArtworkTheme(
artUri: ref.watch(
currentMediaItemProvider.select(
(item) => item.value?.artUri?.toString(),
),
),
child: child!,
),
);
if (isAndroidTv) {
return DownloadQueueFeedback(
child: BackButtonListener(
onBackButtonPressed: () async {
await _handleBackPress();
return true;
},
child: Scaffold(
body: TvShell(
destinations: destinations,
selectedIndex: selectedDestination,
onSelected: _onNavTap,
child: SelectionOverlayHost(child: pageView),
),
),
),
);
}
if (isDesktopPlatform) {
// Desktop windows: a rail (Material) or source-list sidebar (Mornye)
// with a persistent player; no bottom tabs or touch gestures.
final mornye = context.isMornye;
final selectedTab = _tabForIndex(selectedDestination, showStore);
final destinations = _desktopDestinations(
showStore: showStore,
// Mornye shows the queue on its Downloads link instead.
queueCount: mornye ? 0 : queueState,
repoUpdatesCount: repoUpdatesCount,
);
return DownloadQueueFeedback(
child: DesktopLinkTransferNotices(
child: Scaffold(
body: DesktopShellLayout(
destinations: destinations,
selected: selectedTab,
onSelected: _onShellTabRequested,
libraryLinks: mornye
? _desktopLibraryLinks(queueCount: queueState)
: const [],
// The Material rail opens playlists alone.
onOpenLibraryLink: _openDesktopLibraryLink,
onOpenProfile: mornye ? _openDesktopProfile : null,
// The selection bar floats over the pages, not the sidebar.
body: SelectionOverlayHost(child: pageView),
),
),
),
);
}
final shell = SelectionOverlayHost(
child: BackButtonListener(
onBackButtonPressed: () async {
await _handleBackPress();
return true;
},
child: Scaffold(
extendBody: true,
// The tab view keeps one element across the rail<->bar structure
// swap via _pageViewKey so rotation doesn't remount tab navigators.
body: useNavigationRail
? Row(
child: Builder(
builder: (context) {
final bottomBar = Column(
mainAxisSize: MainAxisSize.min,
children: [
SafeArea(
right: false,
bottom: false,
child: ExpressiveNavigationRail(
selectedIndex: selectedDestination,
const MiniPlayer(),
// The bar's container fill separates it; no divider,
// so the mini player and the bar read as one surface.
if (!useNavigationRail)
ExpressiveNavigationBar(
selectedIndex: _currentIndex.clamp(0, maxIndex),
onDestinationSelected: _onNavTap,
backgroundColor: Theme.of(
isTablet: isTablet,
backgroundColor: settingsGroupColor(
context,
).colorScheme.surfaceContainer,
).withValues(alpha: 0.72),
destinations: destinations,
),
),
const VerticalDivider(width: 1),
// Width-based layout (centered columns, grids) measures
// the space beside the rail rather than the whole screen.
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
final mediaQuery = MediaQuery.of(context);
return MediaQuery(
data: mediaQuery
.copyWith(
size: Size(
constraints.maxWidth,
mediaQuery.size.height,
),
)
.removePadding(removeLeft: true),
child: pageView,
);
},
),
),
],
)
: pageView,
bottomNavigationBar: Builder(
builder: (context) {
if (context.isMornye) {
return ListenableBuilder(
listenable: Listenable.merge([
ShellNavigationService.chromeBrightness,
ShellNavigationService.chromeSurface,
]),
builder: (context, child) => Theme(
data: ShellNavigationService.chromeBrightness.value == null
? Theme.of(context)
: MornyeTheme.fromContext(
context,
brightness:
ShellNavigationService.chromeBrightness.value!,
chromeSurface:
ShellNavigationService.chromeSurface.value,
),
child: child!,
),
child: SafeArea(
top: false,
minimum: const EdgeInsets.fromLTRB(20, 0, 20, 8),
// iPadOS-style chrome: one compact, centered pill rather
// than a bar spread across a landscape tablet.
child: Center(
heightFactor: 1,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: compactMornyeChrome ? 600 : double.infinity,
),
child: useNavigationRail
? const MiniPlayer()
: ValueListenableBuilder<bool>(
valueListenable: _mornyeChrome,
builder: (context, collapsed, _) =>
MornyeBottomBar(
collapsed:
canMinimizeChrome &&
collapsed &&
MediaQuery.viewInsetsOf(
context,
).bottom ==
0,
destinations: destinations,
selectedIndex: selectedDestination,
onSelected: _onNavTap,
onHome: () => _onNavTap(0),
onSearch:
ShellNavigationService.requestSearch,
blurEnabled: ref.watch(
mornyeBlurEnabledProvider,
),
),
),
),
),
);
// The backdrop blur re-filters everything scrolling
// underneath on every frame; low-end devices get an
// opaque base instead unless the user forces blur on in
// appearance settings.
if (!blurEnabled) {
return ColoredBox(
color: settingsGroupColor(context),
child: bottomBar,
);
}
return ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
blendMode: BlendMode.src,
child: bottomBar,
),
);
}
final blurEnabled = ref.watch(backdropBlurEnabledProvider);
// The mini player and the bar read as one surface, so the bar
// takes the playing track's artwork scheme too; with nothing
// playing both keep the app scheme. Only this scope listens
// to the track, so a cover change does not rebuild the shell.
return Consumer(
builder: (context, ref, child) => PlayerArtworkTheme(
artUri: ref.watch(
currentMediaItemProvider.select(
(item) => item.value?.artUri?.toString(),
),
),
child: child!,
),
child: Builder(
builder: (context) {
final bottomBar = Column(
mainAxisSize: MainAxisSize.min,
children: [
const MiniPlayer(),
// The bar's container fill separates it; no divider,
// so the mini player and the bar read as one surface.
if (!useNavigationRail)
ExpressiveNavigationBar(
selectedIndex: _currentIndex.clamp(0, maxIndex),
onDestinationSelected: _onNavTap,
isTablet: isTablet,
backgroundColor: settingsGroupColor(
context,
).withValues(alpha: 0.72),
destinations: destinations,
),
],
);
// The backdrop blur re-filters everything scrolling
// underneath on every frame; low-end devices get an
// opaque base instead unless the user forces blur on in
// appearance settings.
if (!blurEnabled) {
return ColoredBox(
color: settingsGroupColor(context),
child: bottomBar,
);
}
return ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
blendMode: BlendMode.src,
child: bottomBar,
),
);
},
),
);
},
),
),
},
),
);
},
),
);
return DownloadQueueFeedback(child: shell);
}
}
+330
View File
@@ -0,0 +1,330 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:mornye/l10n/app_localizations.dart';
import 'package:mornye/models/download_item.dart';
import 'package:mornye/models/settings.dart';
import 'package:mornye/models/track.dart';
import 'package:mornye/providers/download_queue_provider.dart';
import 'package:mornye/providers/explore_provider.dart';
import 'package:mornye/providers/extension_provider.dart';
import 'package:mornye/providers/library_collections_provider.dart';
import 'package:mornye/providers/local_library_provider.dart';
import 'package:mornye/providers/music_player_provider.dart';
import 'package:mornye/providers/recent_access_provider.dart';
import 'package:mornye/providers/settings_provider.dart';
import 'package:mornye/providers/system_volume_provider.dart';
import 'package:mornye/screens/home_tab.dart';
import 'package:mornye/screens/main_shell.dart';
import 'package:mornye/screens/queue_tab.dart';
import 'package:mornye/services/shell_navigation_service.dart';
import 'package:mornye/theme/app_theme.dart';
import 'package:mornye/theme/mornye_theme.dart';
import 'package:mornye/utils/desktop_platform.dart';
import 'package:mornye/widgets/desktop/desktop_commands.dart';
import 'package:mornye/widgets/desktop/desktop_navigation.dart';
import 'package:mornye/widgets/desktop/desktop_window.dart';
import 'package:mornye/widgets/expressive_navigation_bar.dart';
import 'package:mornye/widgets/mornye_bottom_bar.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const backend = MethodChannel('com.zarz.mornye/backend');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
setUp(() {
SharedPreferences.setMockInitialValues({});
messenger.setMockMethodCallHandler(backend, (_) async => null);
desktopSidebarCollapsed.value = false;
desktopSidebarLink.value = null;
});
tearDown(() {
messenger.setMockMethodCallHandler(backend, null);
debugDesktopPlatformOverride = null;
debugDesktopTitleBarInContentOverride = null;
desktopSidebarCollapsed.value = false;
desktopSidebarLink.value = null;
});
late _Queue queue;
Future<void> settle(WidgetTester tester) async {
for (var i = 0; i < 25; i++) {
await tester.pump(const Duration(milliseconds: 20));
}
}
Future<void> pumpShell(
WidgetTester tester, {
required bool desktop,
required bool mornye,
}) async {
debugDesktopPlatformOverride = desktop;
debugDesktopTitleBarInContentOverride = false;
tester.view.physicalSize = desktop
? const Size(1280, 800)
: const Size(430, 932);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final router = GoRouter(
routes: [GoRoute(path: '/', builder: (_, _) => const MainShell())],
);
addTearDown(router.dispose);
await tester.pumpWidget(
ProviderScope(
overrides: [
settingsProvider.overrideWith(_Settings.new),
extensionProvider.overrideWith(_Extensions.new),
exploreProvider.overrideWith(_Explore.new),
downloadHistoryProvider.overrideWith(_History.new),
recentAccessProvider.overrideWith(_Recent.new),
localLibraryProvider.overrideWith(_Local.new),
libraryCollectionsProvider.overrideWith(_Collections.new),
downloadQueueProvider.overrideWith(() => queue = _Queue()),
currentMediaItemProvider.overrideWithBuild(
(ref, notifier) => Stream.value(null),
),
playbackStateProvider.overrideWith(
(ref) => Stream.value(PlaybackState()),
),
systemVolumeProvider.overrideWith((ref) => Stream.value(0.5)),
desktopSidebarPlaylistsProvider.overrideWithValue(const []),
desktopSidebarProfileProvider.overrideWithValue(null),
],
child: MaterialApp.router(
theme: mornye ? MornyeTheme.build(Brightness.dark) : AppTheme.dark(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
routerConfig: router,
),
),
);
// A second frame before any time passes: Mornye's tab preload waits as
// an idle task, and the scheduler re-arms it with zero-delay timers
// while a frame callback is pending, which fake time never gets past.
await tester.pump();
await settle(tester);
}
/// Opens Library, pushes a probe page there and returns to Home, so the
/// Library tab is mounted, hidden and holds a pushed page.
Future<List<int>> pushProbeInLibrary(WidgetTester tester) async {
final builds = [0];
ShellNavigationService.requestTab(ShellTab.library);
await settle(tester);
expect(find.byType(QueueTab), findsOneWidget);
unawaited(
ShellNavigationService.libraryTabNavigatorKey.currentState!.push(
MaterialPageRoute<void>(builder: (_) => _ProbePage(builds)),
),
);
await settle(tester);
ShellNavigationService.requestTab(ShellTab.home);
await settle(tester);
expect(builds.single, greaterThan(0));
expect(
ShellNavigationService.activeTabNavigator(),
same(ShellNavigationService.homeTabNavigatorKey.currentState),
);
expect(find.byType(_ProbePage, skipOffstage: false), findsOneWidget);
return builds;
}
/// The widgets MainShell creates on every build (its tab navigators),
/// the Navigators those build, and the tab root pages the routes build.
/// An unchanged instance means its parent did not build again.
List<Widget> shellAndPages(WidgetTester tester) => [
for (final key in const ['tab-home', 'tab-library'])
tester.widget(find.byKey(ValueKey(key), skipOffstage: false).last),
...tester.widgetList(find.byType(Navigator, skipOffstage: false)),
...tester.widgetList(find.byType(HomeTab, skipOffstage: false)),
tester.widget(find.byType(QueueTab, skipOffstage: false)),
];
void expectSameInstances(List<Widget> before, List<Widget> after) {
expect(after, hasLength(before.length));
for (var i = 0; i < before.length; i++) {
expect(after[i], same(before[i]), reason: '${before[i]}');
}
}
for (final desktop in [true, false]) {
for (final mornye in [false, true]) {
final platform = desktop ? 'desktop' : 'phone';
final style = mornye ? 'Mornye' : 'Material';
testWidgets('resizing rebuilds no shell, route or page ($platform, '
'$style)', (tester) async {
await pumpShell(tester, desktop: desktop, mornye: mornye);
final probeBuilds = await pushProbeInLibrary(tester);
final builds = probeBuilds.single;
final before = shellAndPages(tester);
final start = tester.view.physicalSize;
for (var frame = 1; frame <= 10; frame++) {
tester.view.physicalSize = start + Offset(frame * 12, frame * -6);
await tester.pump(const Duration(milliseconds: 16));
}
await settle(tester);
expect(probeBuilds.single, builds);
expectSameInstances(before, shellAndPages(tester));
expect(tester.takeException(), isNull);
});
testWidgets('a download count change rebuilds only the badges '
'($platform, $style)', (tester) async {
await pumpShell(tester, desktop: desktop, mornye: mornye);
final probeBuilds = await pushProbeInLibrary(tester);
final builds = probeBuilds.single;
final before = shellAndPages(tester);
expect(find.text('3'), findsNothing);
queue.setQueued(3);
await settle(tester);
expect(find.text('3'), findsWidgets);
queue.setQueued(2);
await settle(tester);
expect(find.text('3'), findsNothing);
expect(find.text('2'), findsWidgets);
expect(probeBuilds.single, builds);
expectSameInstances(before, shellAndPages(tester));
expect(tester.takeException(), isNull);
});
}
}
for (final desktop in [true, false]) {
for (final mornye in [false, true]) {
testWidgets('Library learns each switch to and from its tab '
'(${desktop ? 'desktop' : 'phone'}, '
'${mornye ? 'Mornye' : 'Material'})', (tester) async {
await pumpShell(tester, desktop: desktop, mornye: mornye);
bool libraryActive() => tester
.widget<QueueTab>(find.byType(QueueTab, skipOffstage: false))
.isTabActive;
for (var round = 0; round < 2; round++) {
ShellNavigationService.requestTab(ShellTab.library);
await settle(tester);
expect(libraryActive(), isTrue);
ShellNavigationService.requestTab(ShellTab.home);
await settle(tester);
expect(libraryActive(), isFalse);
}
expect(tester.takeException(), isNull);
});
}
}
for (final mornye in [false, true]) {
testWidgets('a phone turned into a tablet still swaps the bar for the '
'rail (${mornye ? 'Mornye' : 'Material'})', (tester) async {
await pumpShell(tester, desktop: false, mornye: mornye);
unawaited(
ShellNavigationService.homeTabNavigatorKey.currentState!.push(
MaterialPageRoute<void>(builder: (_) => _ProbePage([0])),
),
);
await settle(tester);
final probe = tester.element(find.byType(_ProbePage));
final bar = find.byType(
mornye ? MornyeBottomBar : ExpressiveNavigationBar,
);
expect(bar, findsOneWidget);
expect(find.byType(ExpressiveNavigationRail), findsNothing);
// Past both styles' rail breakpoints.
tester.view.physicalSize = const Size(1500, 1000);
await settle(tester);
expect(find.byType(ExpressiveNavigationRail), findsOneWidget);
expect(bar, findsNothing);
// The tab pages moved with the tab view instead of starting over.
expect(tester.element(find.byType(_ProbePage)), same(probe));
expect(tester.takeException(), isNull);
});
}
}
/// A page that reads neither the window size nor the download queue, so it
/// builds again only when something above forces it.
class _ProbePage extends StatelessWidget {
const _ProbePage(this.builds);
final List<int> builds;
@override
Widget build(BuildContext context) {
builds[0]++;
return const SizedBox.expand();
}
}
class _Settings extends SettingsNotifier {
@override
AppSettings build() =>
const AppSettings(searchProvider: 'example', hasSearchedBefore: true);
}
class _Extensions extends ExtensionNotifier {
@override
ExtensionState build() => const ExtensionState(isInitialized: true);
}
class _Explore extends ExploreNotifier {
@override
ExploreState build() => const ExploreState();
}
class _History extends DownloadHistoryNotifier {
@override
DownloadHistoryState build() => DownloadHistoryState();
}
class _Recent extends RecentAccessNotifier {
@override
RecentAccessState build() => const RecentAccessState(isLoaded: true);
}
class _Local extends LocalLibraryNotifier {
@override
LocalLibraryState build() => LocalLibraryState();
}
class _Collections extends LibraryCollectionsNotifier {
@override
LibraryCollectionsState build() => LibraryCollectionsState(isLoaded: true);
}
class _Queue extends DownloadQueueNotifier {
@override
DownloadQueueState build() => const DownloadQueueState();
void setQueued(int count) => state = state.copyWith(
items: [
for (var i = 0; i < count; i++)
DownloadItem(
id: 'queued-$i',
track: Track(
id: 'track-$i',
name: 'Song $i',
artistName: 'Artist',
albumName: 'Album',
duration: 1000,
),
service: 'example-provider',
createdAt: DateTime(2026),
),
],
);
}