From 68631cf067636eb950119bbf9c57ee0471cc75e1 Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:17:22 +0700 Subject: [PATCH] feat(material): connect the Library tools and chip the month headers DESIGN.md asks Material library toolbars for a connected button group instead of loose buttons, date-grouped lists for a centered date chip between short rails, and related controls to share one silhouette. - Sort, Filters and the list/grid switch on the Songs, Singles and Albums pages form one connected M3EButtonGroup with nothing selected. Sort keeps the current order as its label, Filters keeps its label, badge and long-press reset, and the view switch keeps its tooltip. The group is 44dp on phones and 40dp on desktop, and a padded hit area keeps the 48dp target. The desktop sort menu still opens below the sort button. Mornye and reduced motion keep separate buttons. - Section headers become a centered chip on secondaryContainer between two outlineVariant rails, with primaryContainer for the current month. Sections remember their month, so the header does not parse labels. The header stays opaque for pinning and keeps its header semantics. - Material empty Library pages drop the Home button, which repeats the navigation destination; the empty Playlists page offers Create playlist instead. --- lib/screens/queue_tab.dart | 4 +- lib/screens/queue_tab_filter_widgets.dart | 50 ++-- lib/screens/queue_tab_sections.dart | 194 ++++++++++++-- lib/screens/queue_tab_widgets.dart | 185 +++++++++++++ test/library_toolbar_test.dart | 307 ++++++++++++++++++++++ 5 files changed, 704 insertions(+), 36 deletions(-) create mode 100644 test/library_toolbar_test.dart diff --git a/lib/screens/queue_tab.dart b/lib/screens/queue_tab.dart index 436a3bf24..98828fcde 100644 --- a/lib/screens/queue_tab.dart +++ b/lib/screens/queue_tab.dart @@ -1,7 +1,9 @@ import 'dart:async'; import 'dart:io'; -import 'package:flutter/foundation.dart' show ValueListenable; +import 'package:flutter/foundation.dart' show ValueListenable, clampDouble; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart' + show BoxHitTestResult, BoxParentData, RenderShiftedBox; import 'package:mornye/widgets/app_alert_dialog.dart'; import 'package:mornye/widgets/app_choice_chip.dart'; import 'package:mornye/widgets/app_content_card.dart'; diff --git a/lib/screens/queue_tab_filter_widgets.dart b/lib/screens/queue_tab_filter_widgets.dart index f35b0f735..13e01ae55 100644 --- a/lib/screens/queue_tab_filter_widgets.dart +++ b/lib/screens/queue_tab_filter_widgets.dart @@ -353,10 +353,10 @@ extension _QueueTabFilterWidgets on _QueueTabState { context, context.l10n.queueTrackCount(totalTrackCount), [ - if (rootLibrary && !_isSelectionMode) _buildSortButton(context), - if (!_isSelectionMode) _buildFilterButton(context), if (rootLibrary && !_isSelectionMode) - _buildViewModeButton(context, historyViewMode), + ..._buildLibraryTools(context, viewMode: historyViewMode) + else if (!_isSelectionMode) + _buildFilterButton(context), // The root Library creates playlists from the Playlists page. if (!rootLibrary && !_isSelectionMode && @@ -382,8 +382,10 @@ extension _QueueTabFilterWidgets on _QueueTabState { context, context.l10n.queueAlbumCount(totalAlbumCount), [ - if (rootLibrary) _buildSortButton(context), - _buildFilterButton(context), + if (rootLibrary) + ..._buildLibraryTools(context) + else + _buildFilterButton(context), ], ), ), @@ -755,10 +757,10 @@ extension _QueueTabFilterWidgets on _QueueTabState { context, context.l10n.queueTrackCount(totalTrackCount), [ - if (rootLibrary && !_isSelectionMode) _buildSortButton(context), - if (!_isSelectionMode) _buildFilterButton(context), if (rootLibrary && !_isSelectionMode) - _buildViewModeButton(context, historyViewMode), + ..._buildLibraryTools(context, viewMode: historyViewMode) + else if (!_isSelectionMode) + _buildFilterButton(context), // The root Library creates playlists from the Playlists page. if (!rootLibrary && !_isSelectionMode && @@ -1047,17 +1049,35 @@ extension _QueueTabFilterWidgets on _QueueTabState { icon = Icons.history; } + if (context.isMornye) { + return EmptyState( + icon: icon, + title: message, + message: subtitle, + // Every empty branch here means "you have not downloaded anything of + // this kind yet", so the way forward is always search. + action: ExpressiveButton( + onPressed: () => ShellNavigationService.requestTab(ShellTab.home), + icon: const Icon(Icons.search), + child: Text(context.l10n.navHome), + ), + ); + } + + // Material names the next step in the copy. Home already sits in the + // navigation bar, so only creating the first playlist, which the empty + // Playlists page does not otherwise offer, gets a button. return EmptyState( icon: icon, title: message, message: subtitle, - // Every empty branch here means "you have not downloaded anything of - // this kind yet", so the way forward is always search. - action: ExpressiveButton( - onPressed: () => ShellNavigationService.requestTab(ShellTab.home), - icon: const Icon(Icons.search), - child: Text(context.l10n.navHome), - ), + action: filterMode == 'playlists' + ? ExpressiveButton( + onPressed: () => _showCreatePlaylistDialog(context), + icon: const Icon(Icons.add), + child: Text(context.l10n.collectionCreatePlaylist), + ) + : null, ); } diff --git a/lib/screens/queue_tab_sections.dart b/lib/screens/queue_tab_sections.dart index f401a4db3..3ba00753a 100644 --- a/lib/screens/queue_tab_sections.dart +++ b/lib/screens/queue_tab_sections.dart @@ -2,7 +2,7 @@ part of 'queue_tab.dart'; /// A run of consecutive rows sharing one section label. class _LibrarySection { - const _LibrarySection(this.label, this.start, this.end); + const _LibrarySection(this.label, this.start, this.end, {this.month}); final String label; final int start; @@ -10,7 +10,16 @@ class _LibrarySection { /// Exclusive. final int end; + /// A date in the month a date-sorted section covers; null for other sorts. + final DateTime? month; + int get length => end - start; + + /// Whether this section covers the month of [now]. + bool coversMonthOf(DateTime now) { + final month = this.month; + return month != null && month.year == now.year && month.month == now.month; + } } final _letterPattern = RegExp(r'[\p{L}]', unicode: true); @@ -122,6 +131,9 @@ extension _QueueTabSections on _QueueTabState { return _cachedTrackSections; } final sections = <_LibrarySection>[]; + // Month sections keep a date, so a header can tell the current month + // without parsing its label. + final dated = _dateSorts.contains(_sortMode); String? label; var start = 0; for (var i = 0; i < items.length; i++) { @@ -129,13 +141,27 @@ extension _QueueTabSections on _QueueTabState { if (i == 0) { label = next; } else if (next != label) { - sections.add(_LibrarySection(label!, start, i)); + sections.add( + _LibrarySection( + label!, + start, + i, + month: dated ? items[start].addedAt : null, + ), + ); label = next; start = i; } } if (items.isNotEmpty) { - sections.add(_LibrarySection(label!, start, items.length)); + sections.add( + _LibrarySection( + label!, + start, + items.length, + month: dated ? items[start].addedAt : null, + ), + ); } _sectionItems = items; _sectionSort = _sortMode; @@ -189,9 +215,10 @@ extension _QueueTabSections on _QueueTabState { } /// The sort modes as a checked menu below the sort button, on desktop. - bool _showSortMenu(BuildContext context) { + /// [anchor] is the button when [context] is not. + bool _showSortMenu(BuildContext context, {BuildContext? anchor}) { final position = isDesktopPlatform - ? contextMenuPositionBelow(context) + ? contextMenuPositionBelow(anchor ?? context) : null; if (position == null) return false; showContextMenu( @@ -219,6 +246,56 @@ extension _QueueTabSections on _QueueTabState { return true; } + /// Sort, filter and, given a [viewMode], the list/grid switch of a Library + /// page. Material 3 Expressive joins them in one connected button group + /// with the labels and tooltips of the separate buttons, which Mornye and + /// reduced motion keep. + List _buildLibraryTools(BuildContext context, {String? viewMode}) { + if (!materialExpressiveEnabled(context)) { + return [ + _buildSortButton(context), + _buildFilterButton(context), + if (viewMode != null) _buildViewModeButton(context, viewMode), + ]; + } + final l10n = context.l10n; + final filterCount = _activeFilterCount; + final grid = viewMode == 'grid'; + return [ + _LibraryToolGroup( + tools: [ + _LibraryTool( + icon: const AppIcon(Icons.sort), + label: _sortLabel(context, _sortMode), + // The menu anchors below the button but opens from the page, so + // it does not inherit the button's text and icon styles. + onPressed: (button) => _showSortSheet(context, anchor: button), + ), + _LibraryTool( + icon: Badge( + isLabelVisible: filterCount > 0, + label: Text('$filterCount'), + child: const AppIcon(Icons.filter_list), + ), + label: l10n.libraryFilterTitle, + onPressed: (_) => _showFilterSheet(context), + onLongPress: filterCount > 0 ? _resetFilters : null, + ), + if (viewMode != null) + _LibraryTool( + icon: AppIcon(grid ? Icons.view_list : Icons.grid_view), + tooltip: grid + ? l10n.appearanceHistoryViewList + : l10n.appearanceHistoryViewGrid, + onPressed: (_) => ref + .read(settingsProvider.notifier) + .setHistoryViewMode(grid ? 'list' : 'grid'), + ), + ], + ), + ]; + } + /// Switches song pages between the list and the cover grid. Widget _buildViewModeButton(BuildContext context, String viewMode) { final grid = viewMode == 'grid'; @@ -243,8 +320,11 @@ extension _QueueTabSections on _QueueTabState { builder: (context) => AppScrollableSheet(builder: builder), ); - Future _showSortSheet(BuildContext context) async { - if (_showSortMenu(context)) return; + Future _showSortSheet( + BuildContext context, { + BuildContext? anchor, + }) async { + if (_showSortMenu(context, anchor: anchor)) return; final selected = await _showLibraryOptionsSheet( context, builder: (sheetContext, scrollController) => AppBottomSheet( @@ -472,6 +552,7 @@ class _LibrarySectionList extends StatelessWidget { @override Widget build(BuildContext context) { + final now = DateTime.now(); final starts = []; final headers = []; var count = leadCount; @@ -498,7 +579,10 @@ class _LibrarySectionList extends StatelessWidget { final hasHeader = section.label.isNotEmpty; final offset = index - starts[low - 1]; if (hasHeader && offset == 0) { - return _LibrarySectionHeader(label: section.label); + return _LibrarySectionHeader( + label: section.label, + current: section.coversMonthOf(now), + ); } final row = offset - (hasHeader ? 1 : 0); return rowBuilder(section.start + row, section); @@ -508,29 +592,99 @@ class _LibrarySectionList extends StatelessWidget { } /// Pinned label above a section of library rows. +/// +/// Material shows the label in a centered chip between two short rails, so +/// the grouping reads apart from the rows; the current month's chip takes +/// the primary container. Mornye keeps a text header. class _LibrarySectionHeader extends StatelessWidget { - const _LibrarySectionHeader({required this.label}); + const _LibrarySectionHeader({required this.label, this.current = false}); final String label; + /// Whether the section covers the current month. + final bool current; + + static const _railWidth = 24.0; + static const _railHeight = 4.0; + @override Widget build(BuildContext context) { final theme = Theme.of(context); + if (context.isMornye) { + return ColoredBox( + color: theme.scaffoldBackgroundColor, + child: Padding( + padding: const EdgeInsets.fromLTRB(20, 12, 20, 6), + child: Semantics( + header: true, + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.w700, + color: theme.colorScheme.primary, + ), + ), + ), + ), + ); + } + final colors = theme.colorScheme; + final tokens = context.tokens; + const rail = SizedBox(width: _railWidth, height: _railHeight); + final railDecoration = ShapeDecoration( + color: colors.outlineVariant, + shape: const StadiumBorder(), + ); + // Opaque, so the pinned header covers the rows scrolling under it. return ColoredBox( color: theme.scaffoldBackgroundColor, child: Padding( - padding: const EdgeInsets.fromLTRB(20, 12, 20, 6), - child: Semantics( - header: true, - child: Text( - label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.titleSmall?.copyWith( - fontWeight: FontWeight.w700, - color: theme.colorScheme.primary, + padding: EdgeInsets.fromLTRB( + tokens.gapLg, + tokens.gapMd, + tokens.gapLg, + tokens.gapSm, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + DecoratedBox(decoration: railDecoration, child: rail), + SizedBox(width: tokens.gapSm), + Flexible( + child: DecoratedBox( + decoration: ShapeDecoration( + color: current + ? colors.primaryContainer + : colors.secondaryContainer, + shape: const StadiumBorder(), + ), + child: Padding( + // A 32dp chip at the default text size. + padding: EdgeInsets.symmetric( + horizontal: tokens.gapMd, + vertical: 6, + ), + child: Semantics( + header: true, + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.labelLarge?.copyWith( + color: current + ? colors.onPrimaryContainer + : colors.onSecondaryContainer, + ), + ), + ), + ), + ), ), - ), + SizedBox(width: tokens.gapSm), + DecoratedBox(decoration: railDecoration, child: rail), + ], ), ), ); diff --git a/lib/screens/queue_tab_widgets.dart b/lib/screens/queue_tab_widgets.dart index 2f9ece3f1..ffb5bc544 100644 --- a/lib/screens/queue_tab_widgets.dart +++ b/lib/screens/queue_tab_widgets.dart @@ -25,6 +25,191 @@ class _QueueItemSliverRow extends ConsumerWidget { } } +/// One tool of a [_LibraryToolGroup]. +class _LibraryTool { + const _LibraryTool({ + required this.icon, + required this.onPressed, + this.label, + this.tooltip, + this.onLongPress, + }); + + final Widget icon; + final String? label; + final String? tooltip; + + /// Receives the tool button's own context, which a menu can anchor below. + final ValueChanged onPressed; + final VoidCallback? onLongPress; +} + +/// A Library page's tools (sort, filter, view) as one connected Material 3 +/// Expressive button group, so the related controls read as one object. +/// The group is 44dp tall on phones and 40dp for desktop pointer input; +/// both keep the 48dp touch target. +class _LibraryToolGroup extends StatefulWidget { + const _LibraryToolGroup({required this.tools}); + + final List<_LibraryTool> tools; + + @override + State<_LibraryToolGroup> createState() => _LibraryToolGroupState(); +} + +class _LibraryToolGroupState extends State<_LibraryToolGroup> { + // The button group attaches each node to its tool's button, which makes + // the node's context the button's own. + final _focusNodes = []; + + FocusNode _focusNodeAt(int index) { + while (_focusNodes.length <= index) { + _focusNodes.add(FocusNode(debugLabel: 'Library tool $index')); + } + return _focusNodes[index]; + } + + BuildContext _toolContext(int index) => + _focusNodeAt(index).context ?? context; + + /// Runs the long press of the tool under the pointer, if it has one. + void _handleLongPress(LongPressStartDetails details) { + for (final (index, tool) in widget.tools.indexed) { + final box = _focusNodeAt(index).context?.findRenderObject(); + if (box is! RenderBox || !box.hasSize) continue; + final x = box.globalToLocal(details.globalPosition).dx; + if (x >= 0 && x < box.size.width) { + tool.onLongPress?.call(); + return; + } + } + } + + @override + void dispose() { + for (final node in _focusNodes) { + node.dispose(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final tools = widget.tools; + final height = isDesktopPlatform ? 40.0 : 44.0; + return GestureDetector( + onLongPressStart: tools.any((tool) => tool.onLongPress != null) + ? _handleLongPress + : null, + excludeFromSemantics: true, + child: _TouchTargetPadding( + minHeight: context.tokens.minTouchTarget, + child: MaterialExpressiveScope( + child: M3EButtonGroup( + type: M3EButtonGroupType.connected, + style: M3EButtonStyle.filled, + size: M3EButtonSize.sm.copyWith(height: height), + // Tools are actions, not options: nothing stays selected, and a + // press reports the tool through the selection callback. + onSelectedIndexChanged: (index) { + if (index != null) tools[index].onPressed(_toolContext(index)); + }, + actions: [ + for (final (index, tool) in tools.indexed) + M3EButtonGroupAction( + icon: tool.icon, + label: tool.label == null ? null : Text(tool.label!), + tooltip: tool.tooltip, + focusNode: _focusNodeAt(index), + ), + ], + ), + ), + ), + ); + } +} + +/// Grows [child] to [minHeight] and sends a touch above or below it to the +/// nearest point of [child], so a compact control keeps its full touch +/// target. +class _TouchTargetPadding extends SingleChildRenderObjectWidget { + const _TouchTargetPadding({required this.minHeight, required super.child}); + + final double minHeight; + + @override + _RenderTouchTargetPadding createRenderObject(BuildContext context) => + _RenderTouchTargetPadding(minHeight); + + @override + void updateRenderObject( + BuildContext context, + _RenderTouchTargetPadding renderObject, + ) { + renderObject.minHeight = minHeight; + } +} + +class _RenderTouchTargetPadding extends RenderShiftedBox { + _RenderTouchTargetPadding(this._minHeight) : super(null); + + double _minHeight; + + set minHeight(double value) { + if (value == _minHeight) return; + _minHeight = value; + markNeedsLayout(); + } + + Size _paddedSize(BoxConstraints constraints, Size childSize) => + constraints.constrain( + Size( + childSize.width, + childSize.height < _minHeight ? _minHeight : childSize.height, + ), + ); + + @override + Size computeDryLayout(covariant BoxConstraints constraints) => _paddedSize( + constraints, + child?.getDryLayout(constraints.loosen()) ?? Size.zero, + ); + + @override + void performLayout() { + final child = this.child; + if (child == null) { + size = _paddedSize(constraints, Size.zero); + return; + } + child.layout(constraints.loosen(), parentUsesSize: true); + size = _paddedSize(constraints, child.size); + (child.parentData! as BoxParentData).offset = Offset( + 0, + (size.height - child.size.height) / 2, + ); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + final child = this.child; + if (child == null) return false; + final offset = (child.parentData! as BoxParentData).offset; + final bottom = child.size.height - 1; + final local = Offset( + position.dx - offset.dx, + clampDouble(position.dy - offset.dy, 0, bottom < 0 ? 0 : bottom), + ); + return result.addWithPaintOffset( + offset: position - local, + position: position, + hitTest: (result, transformed) => + child.hitTest(result, position: transformed), + ); + } +} + enum _CollectionEntryType { wishlist, loved, favoriteArtists, playlist } class _CollectionEntry { diff --git a/test/library_toolbar_test.dart b/test/library_toolbar_test.dart new file mode 100644 index 000000000..6acec9df4 --- /dev/null +++ b/test/library_toolbar_test.dart @@ -0,0 +1,307 @@ +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:intl/intl.dart' show DateFormat; +import 'package:material_3_expressive/material_3_expressive.dart' + show M3EButton, M3EButtonGroup, M3EButtonGroupType; +import 'package:mornye/l10n/l10n.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/library_collections_provider.dart'; +import 'package:mornye/providers/local_library_provider.dart'; +import 'package:mornye/providers/settings_provider.dart'; +import 'package:mornye/screens/queue_tab.dart'; +import 'package:mornye/services/history_database.dart'; +import 'package:mornye/services/library_database.dart'; +import 'package:mornye/theme/app_theme.dart'; +import 'package:mornye/theme/mornye_theme.dart'; +import 'package:mornye/utils/desktop_platform.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:sqflite/sqflite.dart'; + +class _Settings extends SettingsNotifier { + // The Rewind banner animates for as long as it is shown; keep it off so + // the page settles. + @override + AppSettings build() => const AppSettings( + defaultLibraryView: 'all', + historyViewMode: 'list', + listeningStatisticsEnabled: false, + ); +} + +/// Downloaded songs added on [dates]. With a queue item present and the +/// database page empty, the Library renders this in-memory snapshot. +class _History extends DownloadHistoryNotifier { + _History(this.dates); + + final List dates; + + @override + DownloadHistoryState build() => DownloadHistoryState( + items: [ + for (final (index, date) in dates.indexed) + DownloadHistoryItem( + id: 'song-$index', + trackName: 'Song $index', + artistName: 'Artist', + albumName: 'Album $index', + filePath: '/music/song-$index.flac', + service: 'example-provider', + downloadedAt: date, + ), + ], + totalCount: dates.length, + ); +} + +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() => DownloadQueueState(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + final previousFactory = databaseFactoryOrNull; + databaseFactory = databaseFactorySqflitePlugin; + addTearDown(() => databaseFactory = previousFactory); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + const paths = MethodChannel('plugins.flutter.io/path_provider'); + messenger.setMockMethodCallHandler(paths, (_) async => '/test/documents'); + addTearDown(() => messenger.setMockMethodCallHandler(paths, null)); + // An empty database: every page query returns no rows. + const sqlite = MethodChannel('com.tekartik.sqflite'); + final versions = {}; + messenger.setMockMethodCallHandler(sqlite, (call) async { + final args = (call.arguments as Map?) ?? {}; + if (call.method == 'openDatabase') { + final id = versions.length + 1; + versions[id] = (args['path'] as String).endsWith('history.db') + ? HistoryDatabase.schemaVersion + : LibraryDatabase.schemaVersion; + return {'id': id}; + } + final sql = args['sql'] as String? ?? ''; + if (call.method == 'execute' && sql.contains('CREATE VIRTUAL TABLE')) { + throw PlatformException(code: 'sqlite_error', message: 'no fts5'); + } + if (call.method != 'query') return null; + if (sql.toLowerCase().contains('pragma user_version')) { + return { + 'columns': ['user_version'], + 'rows': [ + [versions[args['id']]], + ], + }; + } + return {'columns': [], 'rows': >[]}; + }); + addTearDown(() => messenger.setMockMethodCallHandler(sqlite, null)); + }); + tearDown(() => debugDesktopPlatformOverride = null); + + Future pumpLibrary( + WidgetTester tester, { + bool desktop = false, + bool mornye = false, + bool reduceMotion = false, + List? dates, + }) async { + debugDesktopPlatformOverride = desktop; + tester.view.physicalSize = const Size(1280, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final queue = DownloadQueueLookup.fromItems([ + DownloadItem( + id: 'completed', + track: const Track( + id: 'song', + name: 'Song', + artistName: 'Artist', + albumName: 'Album', + duration: 1000, + ), + service: 'example-provider', + status: DownloadStatus.completed, + createdAt: DateTime(2026), + ), + ]); + await tester.pumpWidget( + ProviderScope( + overrides: [ + settingsProvider.overrideWith(_Settings.new), + downloadHistoryProvider.overrideWith( + () => _History(dates ?? [DateTime(2026, 1, 10)]), + ), + localLibraryProvider.overrideWith(_Local.new), + libraryCollectionsProvider.overrideWith(_Collections.new), + downloadQueueProvider.overrideWith(_Queue.new), + downloadQueueLookupProvider.overrideWithValue(queue), + ], + child: MaterialApp( + theme: mornye + ? MornyeTheme.build(Brightness.light) + : AppTheme.light(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(disableAnimations: reduceMotion), + child: child!, + ), + // Mornye opens Songs as a section page from its Library root. + home: Scaffold(body: QueueTab(librarySection: mornye ? 'all' : null)), + ), + ), + ); + // A loading indicator spins while the database page is pending, so the + // page never settles; pump for a bounded time instead. + for (var i = 0; i < 20; i++) { + await tester.pump(const Duration(milliseconds: 50)); + } + } + + AppLocalizations l10nOf(WidgetTester tester) => + AppLocalizations.of(tester.element(find.byType(QueueTab))); + + Finder toolButton(String? tooltip, {String? label}) => find + .byWidgetPredicate( + (widget) => + widget is M3EButton && + (tooltip == null || widget.tooltip == tooltip) && + (label == null || + (widget.label is Text && + (widget.label! as Text).data == label)), + ) + .hitTestable(); + + for (final desktop in [false, true]) { + testWidgets('Material joins sort, filter and view in one connected group ' + '(desktop: $desktop)', (tester) async { + await pumpLibrary(tester, desktop: desktop); + final l10n = l10nOf(tester); + + final groups = find.byType(M3EButtonGroup); + expect(groups, findsOneWidget); + final group = tester.widget(groups); + expect(group.type, M3EButtonGroupType.connected); + expect(group.actions, hasLength(3)); + // Sort keeps its label so the current order stays visible. + expect( + (group.actions[0].label! as Text).data, + l10n.libraryFilterSortLatest, + ); + expect((group.actions[1].label! as Text).data, l10n.libraryFilterTitle); + expect(group.actions[2].tooltip, l10n.appearanceHistoryViewGrid); + expect(group.actions[2].label, isNull); + // Nothing in the toolbar stays selected. + expect(group.selectedIndex, isNull); + + // A compact visual that keeps the 48dp touch target. + expect(tester.getSize(groups).height, desktop ? 40 : 44); + final sort = toolButton(null, label: l10n.libraryFilterSortLatest); + expect(sort, findsOneWidget); + final above = tester.getRect(sort).topCenter - const Offset(0, 1); + expect( + tester.hitTestOnBinding(above).path.map((entry) => entry.target), + contains(tester.renderObject(sort)), + ); + }); + } + + testWidgets('the desktop sort menu opens below the sort button', ( + tester, + ) async { + await pumpLibrary(tester, desktop: true); + final l10n = l10nOf(tester); + final sort = toolButton(null, label: l10n.libraryFilterSortLatest); + final sortRect = tester.getRect(sort); + + await tester.tap(sort); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 50)); + } + + final oldest = find.text(l10n.libraryFilterSortOldest); + expect(oldest, findsOneWidget); + // The menu shifts left to stay inside the window, so only its top is + // tied to the button. + expect(tester.getRect(oldest).top, greaterThanOrEqualTo(sortRect.bottom)); + }); + + testWidgets('the view tool switches the Library to the grid', (tester) async { + await pumpLibrary(tester); + final l10n = l10nOf(tester); + + await tester.tap(toolButton(l10n.appearanceHistoryViewGrid)); + await tester.pump(); + + final container = ProviderScope.containerOf( + tester.element(find.byType(QueueTab)), + ); + expect(container.read(settingsProvider).historyViewMode, 'grid'); + }); + + testWidgets('reduced motion keeps the separate Material buttons', ( + tester, + ) async { + await pumpLibrary(tester, reduceMotion: true); + final l10n = l10nOf(tester); + + expect(find.byType(M3EButtonGroup), findsNothing); + expect(find.text(l10n.libraryFilterSortLatest), findsOneWidget); + expect(find.text(l10n.libraryFilterTitle), findsOneWidget); + }); + + testWidgets('Mornye keeps its filter button', (tester) async { + await pumpLibrary(tester, mornye: true); + final l10n = l10nOf(tester); + + expect(find.byType(M3EButtonGroup), findsNothing); + expect(find.text(l10n.libraryFilterTitle), findsOneWidget); + }); + + testWidgets('month headers are chips; the current month is primary', ( + tester, + ) async { + final now = DateTime.now(); + await pumpLibrary(tester, dates: [DateTime(2020, 1, 10), now]); + final handle = tester.ensureSemantics(); + final colors = Theme.of(tester.element(find.byType(QueueTab))).colorScheme; + + Color? chipColor(String label) { + final chip = find + .ancestor(of: find.text(label), matching: find.byType(DecoratedBox)) + .first; + final decoration = tester.widget(chip).decoration; + return (decoration as ShapeDecoration).color; + } + + final current = DateFormat.yMMMM('en').format(now); + expect(chipColor(current), colors.primaryContainer); + expect(chipColor('January 2020'), colors.secondaryContainer); + expect( + tester.getSemantics(find.text('January 2020')), + isSemantics(isHeader: true), + ); + handle.dispose(); + }); +}