diff options
Diffstat (limited to 'lib/widgets/collection')
| -rw-r--r-- | lib/widgets/collection/app_bar.dart | 797 | ||||
| -rw-r--r-- | lib/widgets/collection/collection_grid.dart | 736 | ||||
| -rw-r--r-- | lib/widgets/collection/collection_page.dart | 230 | ||||
| -rw-r--r-- | lib/widgets/collection/draggable_thumb_label.dart | 83 | ||||
| -rw-r--r-- | lib/widgets/collection/entry_set_action_delegate.dart | 885 | ||||
| -rw-r--r-- | lib/widgets/collection/filter_bar.dart | 163 | ||||
| -rw-r--r-- | lib/widgets/collection/grid/headers/album.dart | 61 | ||||
| -rw-r--r-- | lib/widgets/collection/grid/headers/any.dart | 98 | ||||
| -rw-r--r-- | lib/widgets/collection/grid/headers/date.dart | 87 | ||||
| -rw-r--r-- | lib/widgets/collection/grid/headers/rating.dart | 24 | ||||
| -rw-r--r-- | lib/widgets/collection/grid/list_details.dart | 109 | ||||
| -rw-r--r-- | lib/widgets/collection/grid/list_details_theme.dart | 113 | ||||
| -rw-r--r-- | lib/widgets/collection/grid/section_layout.dart | 51 | ||||
| -rw-r--r-- | lib/widgets/collection/grid/tile.dart | 144 | ||||
| -rw-r--r-- | lib/widgets/collection/loading.dart | 50 | ||||
| -rw-r--r-- | lib/widgets/collection/query_bar.dart | 75 |
16 files changed, 3706 insertions, 0 deletions
diff --git a/lib/widgets/collection/app_bar.dart b/lib/widgets/collection/app_bar.dart new file mode 100644 index 0000000..0bf518f --- /dev/null +++ b/lib/widgets/collection/app_bar.dart @@ -0,0 +1,797 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/set_and.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/query.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/collection/entry_set_action_delegate.dart'; +import 'package:aves/widgets/collection/filter_bar.dart'; +import 'package:aves/widgets/collection/query_bar.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/move_button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/rate_button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/tag_button.dart'; +import 'package:aves/widgets/common/action_controls/togglers/favourite.dart'; +import 'package:aves/widgets/common/action_controls/togglers/title_search.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_subtitle.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_title.dart'; +import 'package:aves/widgets/common/basic/popup/container.dart'; +import 'package:aves/widgets/common/basic/popup/expansion_panel.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves/widgets/dialogs/tile_view_dialog.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class CollectionAppBar extends StatefulWidget { + final ValueNotifier<double> appBarHeightNotifier; + final ScrollController scrollController; + final CollectionLens collection; + + const CollectionAppBar({ + super.key, + required this.appBarHeightNotifier, + required this.scrollController, + required this.collection, + }); + + @override + State<CollectionAppBar> createState() => _CollectionAppBarState(); +} + +class _CollectionAppBarState extends State<CollectionAppBar> with RouteAware, SingleTickerProviderStateMixin, WidgetsBindingObserver { + final Set<StreamSubscription> _subscriptions = {}; + final EntrySetActionDelegate _actionDelegate = EntrySetActionDelegate(); + late AnimationController _browseToSelectAnimation; + final ValueNotifier<bool> _isSelectingNotifier = ValueNotifier(false); + final FocusNode _queryBarFocusNode = FocusNode(); + late final Listenable _queryFocusRequestNotifier; + double _statusBarHeight = 0; + + CollectionLens get collection => widget.collection; + + bool get isTrash => collection.filters.contains(TrashFilter.instance); + + CollectionSource get source => collection.source; + + Set<CollectionFilter> get visibleFilters => collection.filters.where((v) => !(v is QueryFilter && v.live) && v is! TrashFilter).toSet(); + + bool get showFilterBar => visibleFilters.isNotEmpty; + + static const _sortOptions = [ + EntrySortFactor.date, + EntrySortFactor.size, + EntrySortFactor.name, + EntrySortFactor.rating, + EntrySortFactor.duration, + EntrySortFactor.path, + ]; + + static const _sectionOptions = [ + EntrySectionFactor.album, + EntrySectionFactor.month, + EntrySectionFactor.day, + EntrySectionFactor.none, + ]; + + static const _layoutOptions = [ + TileLayout.mosaic, + TileLayout.grid, + TileLayout.list, + ]; + + static const _trashSelectionQuickActions = [ + EntrySetAction.delete, + EntrySetAction.restore, + ]; + + @override + void initState() { + super.initState(); + final query = context.read<Query>(); + _subscriptions.add(query.enabledStream.listen((e) => _updateAppBarHeight())); + _queryFocusRequestNotifier = query.focusRequestNotifier; + _queryFocusRequestNotifier.addListener(_onQueryFocusRequest); + _queryBarFocusNode.addListener(_onQueryBarFocusChanged); + _browseToSelectAnimation = AnimationController( + duration: context.read<DurationsData>().iconAnimation, + vsync: this, + ); + _isSelectingNotifier.addListener(_onActivityChanged); + _registerWidget(widget); + WidgetsBinding.instance.addObserver(this); + WidgetsBinding.instance.addPostFrameCallback((_) { + _updateStatusBarHeight(); + _onFilterChanged(); + }); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final route = ModalRoute.of(context); + if (route is PageRoute) { + AvesApp.pageRouteObserver.subscribe(this, route); + } + } + + @override + void didUpdateWidget(covariant CollectionAppBar oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _queryBarFocusNode.dispose(); + _queryFocusRequestNotifier.removeListener(_onQueryFocusRequest); + _queryBarFocusNode.removeListener(_onQueryBarFocusChanged); + _isSelectingNotifier.dispose(); + _browseToSelectAnimation.dispose(); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + WidgetsBinding.instance.removeObserver(this); + AvesApp.pageRouteObserver.unsubscribe(this); + super.dispose(); + } + + void _registerWidget(CollectionAppBar widget) { + widget.collection.filterChangeNotifier.addListener(_onFilterChanged); + } + + void _unregisterWidget(CollectionAppBar widget) { + widget.collection.filterChangeNotifier.removeListener(_onFilterChanged); + } + + @override + void didPushNext() { + // unfocus when navigating away, so that when navigating back, + // the query bar does not get back focus and bring the keyboard + _queryBarFocusNode.unfocus(); + } + + @override + void didChangeMetrics() { + // when top padding or text scale factor change + WidgetsBinding.instance.addPostFrameCallback((_) => _updateStatusBarHeight()); + } + + @override + Widget build(BuildContext context) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + final selection = context.watch<Selection<AvesEntry>>(); + final isSelecting = selection.isSelecting; + _isSelectingNotifier.value = isSelecting; + return NotificationListener<ScrollNotification>( + // cancel notification bubbling so that the draggable scroll bar + // does not misinterpret filter bar scrolling for collection scrolling + onNotification: (notification) => true, + child: AnimatedBuilder( + animation: collection.filterChangeNotifier, + builder: (context, child) { + final canRemoveFilters = appMode != AppMode.pickFilteredMediaInternal; + return Selector<Query, bool>( + selector: (context, query) => query.enabled, + builder: (context, queryEnabled, child) { + return Selector<Settings, List<EntrySetAction>>( + selector: (context, s) => s.collectionBrowsingQuickActions, + builder: (context, _, child) { + final useTvLayout = settings.useTvLayout; + final onFilterTap = canRemoveFilters ? collection.removeFilter : null; + return AvesAppBar( + contentHeight: appBarContentHeight, + pinned: context.select<Selection<AvesEntry>, bool>((selection) => selection.isSelecting), + leading: _buildAppBarLeading( + hasDrawer: appMode.canNavigate, + isSelecting: isSelecting, + ), + title: _buildAppBarTitle(isSelecting), + actions: (context, maxWidth) => useTvLayout ? [] : _buildActions(context, selection, maxWidth), + bottom: Column( + children: [ + if (useTvLayout) + SizedBox( + height: CaptionedButton.getTelevisionButtonHeight(context), + child: ListView( + padding: const EdgeInsets.symmetric(horizontal: 8), + scrollDirection: Axis.horizontal, + children: _buildActions(context, selection, double.infinity), + ), + ), + if (showFilterBar) + NotificationListener( + onNotification: (notification) { + if (notification is SelectFilterNotification) { + collection.addFilters({notification.filter}); + return true; + } else if (notification is DecomposeFilterNotification) { + final filter = notification.filter; + if (filter is DynamicAlbumFilter) { + final innerFilter = filter.filter; + final newFilters = innerFilter is SetAndFilter ? innerFilter.innerFilters : {innerFilter}; + collection.addFilters(newFilters); + collection.removeFilter(filter); + return true; + } + } + return false; + }, + child: FilterBar( + filters: visibleFilters, + onTap: onFilterTap, + onRemove: onFilterTap, + ), + ), + if (queryEnabled) + EntryQueryBar( + queryNotifier: context.select<Query, ValueNotifier<String>>((query) => query.queryNotifier), + focusNode: _queryBarFocusNode, + ), + ], + ), + transitionKey: isSelecting, + ); + }, + ); + }, + ); + }, + ), + ); + } + + double get appBarContentHeight { + final textScaler = MediaQuery.textScalerOf(context); + double height = textScaler.scale(kToolbarHeight); + if (settings.useTvLayout) { + height += CaptionedButton.getTelevisionButtonHeight(context); + } + if (showFilterBar) { + height += FilterBar.preferredHeight; + } + if (context.read<Query>().enabled) { + height += EntryQueryBar.getPreferredHeight(textScaler); + } + return height; + } + + Widget? _buildAppBarLeading({required bool hasDrawer, required bool isSelecting}) { + if (settings.useTvLayout) return null; + + if (!hasDrawer) { + return const CloseButton(); + } + + VoidCallback? onPressed; + String? tooltip; + if (isSelecting) { + onPressed = () => context.read<Selection<AvesEntry>>().browse(); + tooltip = MaterialLocalizations.of(context).backButtonTooltip; + } else { + onPressed = Scaffold.of(context).openDrawer; + tooltip = MaterialLocalizations.of(context).openAppDrawerTooltip; + } + return IconButton( + // key is expected by test driver + key: const Key('appbar-leading-button'), + icon: AnimatedIcon( + icon: AnimatedIcons.menu_arrow, + progress: _browseToSelectAnimation, + ), + onPressed: onPressed, + tooltip: tooltip, + ); + } + + Widget _buildAppBarTitle(bool isSelecting) { + final l10n = context.l10n; + + if (isSelecting) { + // `Selection` may not be available during hero + return Selector<Selection<AvesEntry>?, int>( + selector: (context, selection) => selection?.selectedItems.length ?? 0, + builder: (context, count, child) => Text( + count == 0 ? l10n.collectionSelectPageTitle : l10n.itemCount(count), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); + } else { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + Widget title = Text( + appMode.isPickingMedia ? l10n.collectionPickPageTitle : (isTrash ? l10n.binPageTitle : l10n.collectionPageTitle), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + if (appMode == AppMode.main) { + title = SourceStateAwareAppBarTitle( + title: title, + source: source, + ); + } + return InteractiveAppBarTitle( + onTap: appMode.canNavigate ? _goToSearch : null, + child: title, + ); + } + } + + List<Widget> _buildActions(BuildContext context, Selection<AvesEntry> selection, double maxWidth) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + final isSelecting = selection.isSelecting; + final selectedItemCount = selection.selectedItems.length; + + bool isVisible(EntrySetAction action) => _actionDelegate.isVisible( + action, + appMode: appMode, + isSelecting: isSelecting, + itemCount: collection.entryCount, + selectedItemCount: selectedItemCount, + isTrash: isTrash, + ); + bool canApply(EntrySetAction action) => _actionDelegate.canApply( + action, + isSelecting: isSelecting, + collection: collection, + selectedItemCount: selectedItemCount, + ); + + return settings.useTvLayout + ? _buildTelevisionActions( + context: context, + appMode: appMode, + selection: selection, + isVisible: isVisible, + canApply: canApply, + ) + : _buildMobileActions( + context: context, + appMode: appMode, + selection: selection, + maxWidth: maxWidth, + isVisible: isVisible, + canApply: canApply, + ); + } + + List<Widget> _buildTelevisionActions({ + required BuildContext context, + required AppMode appMode, + required Selection<AvesEntry> selection, + required bool Function(EntrySetAction action) isVisible, + required bool Function(EntrySetAction action) canApply, + }) { + final isSelecting = selection.isSelecting; + + return [ + ...EntrySetActions.general, + ...isSelecting ? EntrySetActions.pageSelection : EntrySetActions.pageBrowsing, + ].nonNulls.where(isVisible).map((action) { + final enabled = canApply(action); + return CaptionedButton( + iconButtonBuilder: (context, focusNode) => _buildButtonIcon( + context, + action, + enabled: enabled, + selection: selection, + focusNode: focusNode, + ), + captionText: _buildButtonCaption(context, action, enabled: enabled), + onPressed: enabled ? () => _onActionSelected(action) : null, + ); + }).toList(); + } + + static double _iconButtonWidth(BuildContext context) { + const defaultPadding = EdgeInsets.all(8); + const defaultIconSize = 24.0; + return defaultPadding.horizontal + MediaQuery.textScalerOf(context).scale(defaultIconSize); + } + + List<Widget> _buildMobileActions({ + required BuildContext context, + required AppMode appMode, + required Selection<AvesEntry> selection, + required double maxWidth, + required bool Function(EntrySetAction action) isVisible, + required bool Function(EntrySetAction action) canApply, + }) { + final availableCount = (maxWidth / _iconButtonWidth(context)).floor(); + + final isSelecting = selection.isSelecting; + final selectedItemCount = selection.selectedItems.length; + final hasSelection = selectedItemCount > 0; + + final browsingQuickActions = settings.collectionBrowsingQuickActions; + final selectionQuickActions = isTrash ? _trashSelectionQuickActions : settings.collectionSelectionQuickActions; + final quickActions = (isSelecting ? selectionQuickActions : browsingQuickActions).take(max(0, availableCount - 1)).toList(); + final quickActionButtons = quickActions.where(isVisible).map( + (action) => _buildButtonIcon(context, action, enabled: canApply(action), selection: selection), + ); + + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return [ + ...quickActionButtons, + PopupMenuButton<EntrySetAction>( + // key is expected by test driver + key: const Key('appbar-menu-button'), + itemBuilder: (context) { + bool _isValidForMenu(EntrySetAction? v) => v == null || (!quickActions.contains(v) && isVisible(v)); + final generalMenuItems = EntrySetActions.general.where(_isValidForMenu).map( + (action) => _toMenuItem(action, enabled: canApply(action), selection: selection), + ); + + final allContextualActions = isSelecting ? EntrySetActions.pageSelection : EntrySetActions.pageBrowsing; + final contextualMenuActions = allContextualActions.where(_isValidForMenu).fold(<EntrySetAction?>[], (prev, v) { + if (v == null && (prev.isEmpty || prev.last == null)) return prev; + return [...prev, v]; + }); + if (contextualMenuActions.isNotEmpty && contextualMenuActions.last == null) { + contextualMenuActions.removeLast(); + } + + final contextualMenuItems = <PopupMenuEntry<EntrySetAction>>[ + ...contextualMenuActions.map( + (action) { + if (action == null) return const PopupMenuDivider(); + return _toMenuItem(action, enabled: canApply(action), selection: selection); + }, + ), + if (isSelecting && !settings.isReadOnly && appMode == AppMode.main && !isTrash) + PopupMenuExpansionPanel<EntrySetAction>( + enabled: hasSelection, + value: 'edit', + icon: AIcons.edit, + title: context.l10n.collectionActionEdit, + items: [ + _buildRotateAndFlipMenuItems(context, canApply: canApply), + ...EntrySetActions.edit.where((v) => isVisible(v) && !quickActions.contains(v)).map((action) => _toMenuItem(action, enabled: canApply(action), selection: selection)), + ], + ), + ]; + + return [ + ...generalMenuItems, + if (contextualMenuItems.isNotEmpty) ...[ + const PopupMenuDivider(), + ...contextualMenuItems, + ], + ]; + }, + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + await _onActionSelected(action); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ]; + } + + Set<AvesEntry> _getExpandedSelectedItems(Selection<AvesEntry> selection) { + return selection.selectedItems.expand((entry) => entry.stackedEntries ?? {entry}).toSet(); + } + + // key is expected by test driver + Key _getActionKey(EntrySetAction action) => Key('menu-${action.name}'); + + Widget _buildButtonIcon( + BuildContext context, + EntrySetAction action, { + required bool enabled, + FocusNode? focusNode, + required Selection<AvesEntry> selection, + }) { + final blurred = settings.enableBlurEffect; + final onPressed = enabled ? () => _onActionSelected(action) : null; + switch (action) { + case EntrySetAction.toggleTitleSearch: + // `Query` may not be available during hero + return Selector<Query?, bool>( + selector: (context, query) => query?.enabled ?? false, + builder: (context, queryEnabled, child) { + return TitleSearchToggler( + queryEnabled: queryEnabled, + onPressed: onPressed, + focusNode: focusNode, + ); + }, + ); + case EntrySetAction.copy: + return MoveButton( + copy: true, + blurred: blurred, + onChooserValue: (album) => _actionDelegate.quickMove(context, album, copy: true), + onPressed: onPressed, + ); + case EntrySetAction.move: + return MoveButton( + copy: false, + blurred: blurred, + onChooserValue: (album) => _actionDelegate.quickMove(context, album, copy: false), + onPressed: onPressed, + ); + case EntrySetAction.editRating: + return RateButton( + blurred: blurred, + onChooserValue: (rating) => _actionDelegate.quickRate(context, rating), + focusNode: focusNode, + onPressed: onPressed, + ); + case EntrySetAction.editTags: + return TagButton( + blurred: blurred, + onChooserValue: (filter) => _actionDelegate.quickTag(context, filter), + focusNode: focusNode, + onPressed: onPressed, + ); + case EntrySetAction.toggleFavourite: + return FavouriteToggler( + entries: _getExpandedSelectedItems(selection), + focusNode: focusNode, + onPressed: onPressed, + ); + default: + return IconButton( + key: _getActionKey(action), + icon: action.getIcon(), + onPressed: onPressed, + focusNode: focusNode, + tooltip: action.getText(context), + ); + } + } + + Widget _buildButtonCaption( + BuildContext context, + EntrySetAction action, { + required bool enabled, + }) { + switch (action) { + case EntrySetAction.toggleTitleSearch: + return TitleSearchTogglerCaption( + enabled: enabled, + ); + default: + return CaptionedButtonText( + text: action.getText(context), + enabled: enabled, + ); + } + } + + PopupMenuItem<EntrySetAction> _toMenuItem(EntrySetAction action, {required bool enabled, required Selection<AvesEntry> selection}) { + late Widget child; + switch (action) { + case EntrySetAction.toggleTitleSearch: + child = TitleSearchToggler( + queryEnabled: context.read<Query>().enabled, + isMenuItem: true, + ); + case EntrySetAction.toggleFavourite: + child = FavouriteToggler( + entries: _getExpandedSelectedItems(selection), + isMenuItem: true, + ); + default: + child = MenuRow(text: action.getText(context), icon: action.getIcon()); + } + return PopupMenuItem( + key: _getActionKey(action), + value: action, + enabled: enabled, + child: child, + ); + } + + PopupMenuEntry<EntrySetAction> _buildRotateAndFlipMenuItems( + BuildContext context, { + required bool Function(EntrySetAction action) canApply, + }) { + Widget buildDivider() => const SizedBox( + height: 16, + child: VerticalDivider( + width: 1, + thickness: 1, + ), + ); + + Widget buildItem(EntrySetAction action) => Expanded( + child: Material( + color: Colors.transparent, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(8)), + ), + clipBehavior: Clip.antiAlias, + child: PopupMenuItem( + value: action, + enabled: canApply(action), + child: Tooltip( + message: action.getText(context), + child: Center(child: action.getIcon()), + ), + ), + ), + ); + + return PopupMenuItemContainer( + child: Row( + children: [ + buildDivider(), + buildItem(EntrySetAction.rotateCCW), + buildDivider(), + buildItem(EntrySetAction.rotateCW), + buildDivider(), + buildItem(EntrySetAction.flip), + buildDivider(), + ], + ), + ); + } + + void _onActivityChanged() { + if (context.read<Selection<AvesEntry>>().isSelecting) { + _browseToSelectAnimation.forward(); + } else { + _browseToSelectAnimation.reverse(); + } + } + + void _onFilterChanged() { + _updateAppBarHeight(); + + final filters = collection.filters; + if (filters.isNotEmpty) { + final selection = context.read<Selection<AvesEntry>>(); + if (selection.isSelecting) { + final toRemove = selection.selectedItems.where((entry) => !filters.every((f) => f.test(entry))).toSet(); + selection.removeFromSelection(toRemove); + } + } + } + + void _onQueryFocusRequest() => _queryBarFocusNode.requestFocus(); + + void _onQueryBarFocusChanged() { + if (_queryBarFocusNode.hasFocus) { + // the query bar is in the top sliver of the page scrollable, + // so when the bar text field gets focus and requests to be on screen, + // it will scroll to show it by default, but it may not end at the very top, + // so we do it manually for a more predicable end position + _scrollToTop(); + } + } + + void _scrollToTop() => widget.scrollController.jumpTo(0); + + void _updateStatusBarHeight() { + if (!mounted) { + return; + } + _statusBarHeight = MediaQuery.paddingOf(context).top; + _updateAppBarHeight(); + } + + void _updateAppBarHeight() { + widget.appBarHeightNotifier.value = _statusBarHeight + AvesAppBar.appBarHeightForContentHeight(appBarContentHeight); + } + + Future<void> _onActionSelected(EntrySetAction action) async { + switch (action) { + // general + case EntrySetAction.configureView: + await _configureView(); + case EntrySetAction.select: + context.read<Selection<AvesEntry>>().select(); + case EntrySetAction.selectAll: + context.read<Selection<AvesEntry>>().addToSelection(collection.sortedEntries); + case EntrySetAction.selectNone: + context.read<Selection<AvesEntry>>().clearSelection(); + // browsing + case EntrySetAction.searchCollection: + case EntrySetAction.toggleTitleSearch: + case EntrySetAction.addDynamicAlbum: + case EntrySetAction.addShortcut: + case EntrySetAction.setHome: + // browsing or selecting + case EntrySetAction.map: + case EntrySetAction.slideshow: + case EntrySetAction.stats: + case EntrySetAction.rescan: + case EntrySetAction.emptyBin: + // selecting + case EntrySetAction.share: + case EntrySetAction.delete: + case EntrySetAction.restore: + case EntrySetAction.copy: + case EntrySetAction.move: + case EntrySetAction.rename: + case EntrySetAction.convert: + case EntrySetAction.toggleFavourite: + case EntrySetAction.rotateCCW: + case EntrySetAction.rotateCW: + case EntrySetAction.flip: + case EntrySetAction.editDate: + case EntrySetAction.editLocation: + case EntrySetAction.editTitleDescription: + case EntrySetAction.editRating: + case EntrySetAction.editTags: + case EntrySetAction.removeMetadata: + _actionDelegate.onActionSelected(context, action); + } + } + + Future<void> _configureView() async { + final initialValue = ( + settings.collectionSortFactor, + settings.collectionSectionFactor, + settings.getTileLayout(CollectionPage.routeName), + settings.collectionSortReverse, + ); + final extentController = context.read<TileExtentController>(); + final value = await showDialog<(EntrySortFactor?, EntrySectionFactor?, TileLayout?, bool)>( + context: context, + builder: (context) { + return TileViewDialog<EntrySortFactor, EntrySectionFactor, TileLayout>( + initialValue: initialValue, + sortOptions: _sortOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + sectionOptions: _sectionOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + layoutOptions: _layoutOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + sortOrder: (factor, reverse) => factor.getOrderName(context, reverse), + canSection: (s, g, l) => s == EntrySortFactor.date, + tileExtentController: extentController, + ); + }, + routeSettings: const RouteSettings(name: TileViewDialog.routeName), + ); + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + if (value != null && initialValue != value) { + settings.collectionSortFactor = value.$1!; + settings.collectionSectionFactor = value.$2!; + settings.setTileLayout(CollectionPage.routeName, value.$3!); + settings.collectionSortReverse = value.$4; + } + } + + void _goToSearch() { + Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: collection.source, + parentCollection: collection, + ), + ), + ); + } +} diff --git a/lib/widgets/collection/collection_grid.dart b/lib/widgets/collection/collection_grid.dart new file mode 100644 index 0000000..3926a66 --- /dev/null +++ b/lib/widgets/collection/collection_grid.dart @@ -0,0 +1,736 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/app/permissions.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/collection/app_bar.dart'; +import 'package:aves/widgets/collection/draggable_thumb_label.dart'; +import 'package:aves/widgets/collection/grid/list_details_theme.dart'; +import 'package:aves/widgets/collection/grid/section_layout.dart'; +import 'package:aves/widgets/collection/grid/tile.dart'; +import 'package:aves/widgets/collection/loading.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/scrollbar.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/behaviour/routes.dart'; +import 'package:aves/widgets/common/behaviour/sloppy_scroll_physics.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/grid/draggable_thumb_label.dart'; +import 'package:aves/widgets/common/grid/item_tracker.dart'; +import 'package:aves/widgets/common/grid/scaling.dart'; +import 'package:aves/widgets/common/grid/sections/fixed/scale_grid.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:aves/widgets/common/grid/selector.dart'; +import 'package:aves/widgets/common/grid/sliver.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/identity/scroll_thumb.dart'; +import 'package:aves/widgets/common/providers/tile_extent_controller_provider.dart'; +import 'package:aves/widgets/common/providers/viewer_entry_provider.dart'; +import 'package:aves/widgets/common/thumbnail/decorated.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:aves/widgets/common/thumbnail/notifications.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves/widgets/navigation/nav_bar/nav_bar.dart'; +import 'package:aves/widgets/viewer/entry_viewer_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:intl/intl.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; + +class CollectionGrid extends StatefulWidget { + final String settingsRouteKey; + + static const double extentMin = 46; + static const double extentMax = 300; + static const double fixedExtentLayoutSpacing = 2; + static const double mosaicLayoutSpacing = 4; + + static int get columnCountDefault => settings.useTvLayout ? 6 : 4; + + const CollectionGrid({ + super.key, + required this.settingsRouteKey, + }); + + @override + State<CollectionGrid> createState() => _CollectionGridState(); +} + +class _CollectionGridState extends State<CollectionGrid> { + TileExtentController? _tileExtentController; + + String get settingsRouteKey => widget.settingsRouteKey; + + @override + void dispose() { + _tileExtentController?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final spacing = context.select<Settings, double>((v) => v.getTileLayout(settingsRouteKey) == TileLayout.mosaic ? CollectionGrid.mosaicLayoutSpacing : CollectionGrid.fixedExtentLayoutSpacing); + if (_tileExtentController?.spacing != spacing) { + _tileExtentController = TileExtentController( + settingsRouteKey: settingsRouteKey, + columnCountDefault: CollectionGrid.columnCountDefault, + extentMin: CollectionGrid.extentMin, + extentMax: CollectionGrid.extentMax, + spacing: spacing, + horizontalPadding: 2, + ); + } + return TileExtentControllerProvider( + controller: _tileExtentController!, + child: const _CollectionGridContent(), + ); + } +} + +class _CollectionGridContent extends StatefulWidget { + const _CollectionGridContent(); + + @override + State<_CollectionGridContent> createState() => _CollectionGridContentState(); +} + +class _CollectionGridContentState extends State<_CollectionGridContent> { + final ValueNotifier<AvesEntry?> _focusedItemNotifier = ValueNotifier(null); + final ValueNotifier<bool> _isScrollingNotifier = ValueNotifier(false); + final ValueNotifier<AppMode> _selectingAppModeNotifier = ValueNotifier(AppMode.pickFilteredMediaInternal); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => context.read<ViewerEntryNotifier>().value = null); + } + + @override + void dispose() { + _focusedItemNotifier.dispose(); + _isScrollingNotifier.dispose(); + _selectingAppModeNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final selectable = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canSelectMedia); + final settingsRouteKey = context.read<TileExtentController>().settingsRouteKey; + final tileLayout = context.select<Settings, TileLayout>((v) => v.getTileLayout(settingsRouteKey)); + return Consumer<CollectionLens>( + builder: (context, collection, child) { + final sectionedListLayoutProvider = ValueListenableBuilder<double>( + valueListenable: context.select<TileExtentController, ValueNotifier<double>>((controller) => controller.extentNotifier), + builder: (context, thumbnailExtent, child) { + assert(thumbnailExtent > 0); + return Selector<TileExtentController, (double, int, double, double)>( + selector: (context, c) => (c.viewportSize.width, c.columnCount, c.spacing, c.horizontalPadding), + builder: (context, c, child) { + final (scrollableWidth, columnCount, tileSpacing, horizontalPadding) = c; + final source = collection.source; + return GridTheme( + extent: thumbnailExtent, + child: EntryListDetailsTheme( + extent: thumbnailExtent, + child: ValueListenableBuilder<SourceState>( + valueListenable: source.stateNotifier, + builder: (context, sourceState, child) { + late final Duration tileAnimationDelay; + if (sourceState == SourceState.ready) { + // do not listen for animation delay change + final target = context.read<DurationsData>().staggeredAnimationPageTarget; + tileAnimationDelay = context.read<TileExtentController>().getTileAnimationDelay(target); + } else { + tileAnimationDelay = Duration.zero; + } + + return NotificationListener<OpenViewerNotification>( + onNotification: (notification) { + _goToViewer(collection, notification.entry); + return true; + }, + child: StreamBuilder( + stream: source.eventBus.on<AspectRatioChangedEvent>(), + builder: (context, snapshot) => SectionedEntryListLayoutProvider( + collection: collection, + selectable: selectable, + scrollableWidth: scrollableWidth, + tileLayout: tileLayout, + columnCount: columnCount, + spacing: tileSpacing, + horizontalPadding: horizontalPadding, + tileExtent: thumbnailExtent, + tileBuilder: (entry, tileSize) { + final extent = tileSize.shortestSide; + return AnimatedBuilder( + animation: favourites, + builder: (context, child) { + Widget tile = InteractiveTile( + key: ValueKey(entry.id), + collection: collection, + entry: entry, + thumbnailExtent: extent, + tileLayout: tileLayout, + isScrollingNotifier: _isScrollingNotifier, + ); + if (!settings.useTvLayout) return tile; + + return Focus( + onFocusChange: (focused) { + if (focused) { + _focusedItemNotifier.value = entry; + } else if (_focusedItemNotifier.value == entry) { + _focusedItemNotifier.value = null; + } + }, + child: ValueListenableBuilder<AvesEntry?>( + valueListenable: _focusedItemNotifier, + builder: (context, focusedItem, child) { + return AnimatedScale( + scale: focusedItem == entry ? 1 : .9, + curve: Curves.fastOutSlowIn, + duration: context.select<DurationsData, Duration>((v) => v.tvImageFocusAnimation), + child: child!, + ); + }, + child: tile, + ), + ); + }, + ); + }, + tileAnimationDelay: tileAnimationDelay, + child: child!, + ), + ), + ); + }, + child: child, + ), + ), + ); + }, + child: child, + ); + }, + child: _CollectionSectionedContent( + collection: collection, + isScrollingNotifier: _isScrollingNotifier, + scrollController: PrimaryScrollController.of(context), + tileLayout: tileLayout, + selectable: selectable, + ), + ); + return sectionedListLayoutProvider; + }, + ); + } + + Future<void> _goToViewer(CollectionLens collection, AvesEntry entry) async { + // track viewer entry for dynamic hero placeholder + final viewerEntryNotifier = context.read<ViewerEntryNotifier>(); + + // prevent navigating again to the same entry until fully back, + // as a workaround for the hero pop/push diversion animation issue + // (cf `ThumbnailImage` `Hero` usage) + if (viewerEntryNotifier.value == entry) return; + WidgetsBinding.instance.addPostFrameCallback((_) => viewerEntryNotifier.value = entry); + + final selection = context.read<Selection<AvesEntry>>(); + await Navigator.maybeOf(context)?.push( + TransparentMaterialPageRoute( + settings: const RouteSettings(name: EntryViewerPage.routeName), + pageBuilder: (context, a, sa) { + final viewerCollection = collection.copyWith( + listenToSource: false, + ); + Widget child = EntryViewerPage( + collection: viewerCollection, + initialEntry: entry, + ); + + if (selection.isSelecting) { + child = MultiProvider( + providers: [ + ListenableProvider<ValueNotifier<AppMode>>.value(value: _selectingAppModeNotifier), + ChangeNotifierProvider<Selection<AvesEntry>>.value(value: selection), + ], + child: child, + ); + } + + return child; + }, + ), + ); + + // reset track viewer entry + final animate = context.read<Settings>().animate; + if (animate) { + // TODO TLAD fix timing when transition is incomplete, e.g. when going back while going to the viewer + await Future.delayed(ADurations.pageTransitionExact * timeDilation); + } + viewerEntryNotifier.value = null; + } +} + +class _CollectionSectionedContent extends StatefulWidget { + final CollectionLens collection; + final ValueNotifier<bool> isScrollingNotifier; + final ScrollController scrollController; + final TileLayout tileLayout; + final bool selectable; + + const _CollectionSectionedContent({ + required this.collection, + required this.isScrollingNotifier, + required this.scrollController, + required this.tileLayout, + required this.selectable, + }); + + @override + State<_CollectionSectionedContent> createState() => _CollectionSectionedContentState(); +} + +class _CollectionSectionedContentState extends State<_CollectionSectionedContent> { + final ValueNotifier<double> _appBarHeightNotifier = ValueNotifier(0); + final GlobalKey _scrollableKey = GlobalKey(debugLabel: 'thumbnail-collection-scrollable'); + + CollectionLens get collection => widget.collection; + + TileLayout get tileLayout => widget.tileLayout; + + ScrollController get scrollController => widget.scrollController; + + @override + void initState() { + super.initState(); + _appBarHeightNotifier.addListener(_onAppBarHeightChanged); + } + + @override + void dispose() { + _appBarHeightNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final scrollView = AnimationLimiter( + child: _CollectionScrollView( + scrollableKey: _scrollableKey, + collection: collection, + appBar: CollectionAppBar( + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + collection: collection, + ), + appBarHeightNotifier: _appBarHeightNotifier, + isScrollingNotifier: widget.isScrollingNotifier, + scrollController: scrollController, + ), + ); + + final scaler = _CollectionScaler( + scrollableKey: _scrollableKey, + appBarHeightNotifier: _appBarHeightNotifier, + tileLayout: tileLayout, + child: scrollView, + ); + + final selector = GridSelectionGestureDetector<AvesEntry>( + scrollableKey: _scrollableKey, + selectable: widget.selectable, + items: collection.sortedEntries, + scrollController: scrollController, + appBarHeightNotifier: _appBarHeightNotifier, + child: scaler, + ); + + return GridItemTracker<AvesEntry>( + scrollableKey: _scrollableKey, + tileLayout: tileLayout, + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + child: selector, + ); + } + + void _onAppBarHeightChanged() => setState(() {}); +} + +class _CollectionScaler extends StatelessWidget { + final GlobalKey scrollableKey; + final ValueNotifier<double> appBarHeightNotifier; + final TileLayout tileLayout; + final Widget child; + + const _CollectionScaler({ + required this.scrollableKey, + required this.appBarHeightNotifier, + required this.tileLayout, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final (tileSpacing, horizontalPadding) = context.select<TileExtentController, (double, double)>((v) => (v.spacing, v.horizontalPadding)); + final brightness = Theme.of(context).brightness; + final borderColor = DecoratedThumbnail.borderColor(context); + final borderWidth = DecoratedThumbnail.borderWidth(context); + return GridScaleGestureDetector<AvesEntry>( + scrollableKey: scrollableKey, + tileLayout: tileLayout, + heightForWidth: (width) => width, + gridBuilder: (center, tileSize, child) => CustomPaint( + painter: FixedExtentGridPainter( + tileLayout: tileLayout, + tileCenter: center, + tileSize: tileSize, + spacing: tileSpacing, + horizontalPadding: horizontalPadding, + borderWidth: borderWidth, + borderRadius: Radius.zero, + color: borderColor, + textDirection: Directionality.of(context), + ), + child: child, + ), + scaledItemBuilder: (entry, tileSize) => EntryListDetailsTheme( + extent: tileSize.height, + child: Tile( + entry: entry, + thumbnailExtent: context.read<TileExtentController>().effectiveExtentMax, + tileLayout: tileLayout, + ), + ), + mosaicItemBuilder: (index, targetExtent) => DecoratedBox( + decoration: BoxDecoration( + color: ThumbnailImage.computeLoadingBackgroundColor(index * 10, brightness).withValues(alpha: .9), + border: Border.all( + color: borderColor, + width: borderWidth, + ), + ), + ), + child: child, + ); + } +} + +class _CollectionScrollView extends StatefulWidget { + final GlobalKey scrollableKey; + final CollectionLens collection; + final Widget appBar; + final ValueNotifier<double> appBarHeightNotifier; + final ValueNotifier<bool> isScrollingNotifier; + final ScrollController scrollController; + + const _CollectionScrollView({ + required this.scrollableKey, + required this.collection, + required this.appBar, + required this.appBarHeightNotifier, + required this.isScrollingNotifier, + required this.scrollController, + }); + + @override + State<_CollectionScrollView> createState() => _CollectionScrollViewState(); +} + +class _CollectionScrollViewState extends State<_CollectionScrollView> with WidgetsBindingObserver { + Timer? _scrollMonitoringTimer; + bool _checkingStoragePermission = false; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addObserver(this); + } + + @override + void didUpdateWidget(covariant _CollectionScrollView oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _unregisterWidget(widget); + _stopScrollMonitoringTimer(); + super.dispose(); + } + + void _registerWidget(_CollectionScrollView widget) { + widget.collection.filterChangeNotifier.addListener(_scrollToTop); + widget.collection.sortSectionChangeNotifier.addListener(_scrollToTop); + widget.scrollController.addListener(_onScrollChanged); + } + + void _unregisterWidget(_CollectionScrollView widget) { + widget.collection.filterChangeNotifier.removeListener(_scrollToTop); + widget.collection.sortSectionChangeNotifier.removeListener(_scrollToTop); + widget.scrollController.removeListener(_onScrollChanged); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed && _checkingStoragePermission) { + _checkingStoragePermission = false; + _isStoragePermissionGranted.then((granted) { + if (granted) { + widget.collection.source.init(scope: CollectionSource.fullScope); + } + }); + } + } + + @override + Widget build(BuildContext context) { + final scrollView = _buildScrollView(widget.appBar, widget.collection); + return settings.useTvLayout ? scrollView : _buildDraggableScrollView(scrollView, widget.collection); + } + + Widget _buildDraggableScrollView(Widget scrollView, CollectionLens collection) { + return ValueListenableBuilder<double>( + valueListenable: widget.appBarHeightNotifier, + builder: (context, appBarHeight, child) { + return Selector<MediaQueryData, double>( + selector: (context, mq) => mq.effectiveBottomPadding, + builder: (context, mqPaddingBottom, child) { + return Selector<Settings, bool>( + selector: (context, s) => s.enableBottomNavigationBar, + builder: (context, enableBottomNavigationBar, child) { + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + final showBottomNavigationBar = canNavigate && enableBottomNavigationBar; + final navBarHeight = showBottomNavigationBar ? AppBottomNavBar.height : 0; + return Selector<SectionedListLayout<AvesEntry>, List<SectionLayout>>( + selector: (context, layout) => layout.sectionLayouts, + builder: (context, sectionLayouts, child) { + final scrollController = widget.scrollController; + final offsetIncrementSnapThreshold = context.select<TileExtentController, double>((v) => (v.extentNotifier.value + v.spacing) / 4); + return DraggableScrollbar( + backgroundColor: Colors.white, + scrollThumbSize: Size(avesScrollThumbWidth, avesScrollThumbHeight), + scrollThumbBuilder: avesScrollThumbBuilder( + height: avesScrollThumbHeight, + backgroundColor: Colors.white, + ), + controller: scrollController, + dragOffsetSnapper: (scrollOffset, offsetIncrement) { + if (offsetIncrement > offsetIncrementSnapThreshold && scrollOffset < scrollController.position.maxScrollExtent) { + final section = sectionLayouts.firstWhereOrNull((section) => section.hasChildAtOffset(scrollOffset)); + if (section != null) { + if (section.maxOffset - section.minOffset < scrollController.position.viewportDimension) { + // snap to section header + return section.minOffset; + } else { + // snap to content row + final index = section.getMinChildIndexForScrollOffset(scrollOffset); + return section.indexToLayoutOffset(index); + } + } + } + return scrollOffset; + }, + crumbsBuilder: () => _getCrumbs(sectionLayouts), + padding: EdgeInsets.only( + // padding to keep scroll thumb between app bar above and nav bar below + top: appBarHeight, + bottom: navBarHeight + mqPaddingBottom, + ), + labelTextBuilder: (offsetY) => CollectionDraggableThumbLabel( + collection: collection, + offsetY: offsetY, + ), + crumbTextBuilder: (label) => DraggableCrumbLabel(label: label), + child: scrollView, + ); + }, + ); + }, + ); + }, + ); + }, + ); + } + + Widget _buildScrollView(Widget appBar, CollectionLens collection) { + return CustomScrollView( + key: widget.scrollableKey, + primary: true, + // workaround to prevent scrolling the app bar away + // when there is no content and we use `SliverFillRemaining` + physics: collection.isEmpty + ? const NeverScrollableScrollPhysics() + : SloppyScrollPhysics( + gestureSettings: MediaQuery.gestureSettingsOf(context), + parent: const AlwaysScrollableScrollPhysics(), + ), + cacheExtent: context.select<TileExtentController, double>((controller) => controller.effectiveExtentMax), + slivers: [ + appBar, + collection.isEmpty + ? SliverFillRemaining( + hasScrollBody: false, + child: _buildEmptyContent(collection), + ) + : const SectionedListSliver<AvesEntry>(), + const NavBarPaddingSliver(), + const BottomPaddingSliver(), + const TvTileGridBottomPaddingSliver(), + ], + ); + } + + Widget _buildEmptyContent(CollectionLens collection) { + final source = collection.source; + return ValueListenableBuilder<SourceState>( + valueListenable: source.stateNotifier, + builder: (context, sourceState, child) { + if (sourceState == SourceState.loading) { + return LoadingEmptyContent(source: source); + } + + return FutureBuilder<bool>( + future: _isStoragePermissionGranted, + builder: (context, snapshot) { + final granted = snapshot.data ?? true; + Widget? bottom = granted + ? null + : Padding( + padding: const EdgeInsets.only(top: 16), + child: AvesOutlinedButton( + label: context.l10n.collectionEmptyGrantAccessButtonLabel, + onPressed: () async { + if (await openAppSettings()) { + _checkingStoragePermission = true; + } + }, + ), + ); + + if (collection.filters.any((filter) => filter is FavouriteFilter)) { + return EmptyContent( + icon: AIcons.favourite, + text: context.l10n.collectionEmptyFavourites, + bottom: bottom, + ); + } + if (collection.filters.any((filter) => filter is MimeFilter && filter.mime == MimeTypes.anyVideo)) { + return EmptyContent( + icon: AIcons.video, + text: context.l10n.collectionEmptyVideos, + bottom: bottom, + ); + } + return EmptyContent( + icon: AIcons.image, + text: context.l10n.collectionEmptyImages, + bottom: bottom, + ); + }, + ); + }, + ); + } + + void _scrollToTop() => widget.scrollController.jumpTo(0); + + void _onScrollChanged() { + widget.isScrollingNotifier.value = true; + _stopScrollMonitoringTimer(); + _scrollMonitoringTimer = Timer(ADurations.collectionScrollMonitoringTimerDelay, () { + widget.isScrollingNotifier.value = false; + }); + } + + void _stopScrollMonitoringTimer() => _scrollMonitoringTimer?.cancel(); + + Map<double, String> _getCrumbs(List<SectionLayout> sectionLayouts) { + final crumbs = <double, String>{}; + if (sectionLayouts.length <= 1) return crumbs; + + final maxOffset = sectionLayouts.last.maxOffset; + void addAlbums(CollectionLens collection, List<SectionLayout> sectionLayouts, Map<double, String> crumbs) { + final source = collection.source; + sectionLayouts.forEach((section) { + final directory = (section.sectionKey as EntryAlbumSectionKey).directory; + if (directory != null) { + final label = source.getStoredAlbumDisplayName(context, directory); + crumbs[section.minOffset / maxOffset] = label; + } + }); + } + + final collection = widget.collection; + switch (collection.sortFactor) { + case EntrySortFactor.date: + switch (collection.sectionFactor) { + case EntrySectionFactor.album: + addAlbums(collection, sectionLayouts, crumbs); + case EntrySectionFactor.month: + case EntrySectionFactor.day: + final firstKey = sectionLayouts.first.sectionKey; + final lastKey = sectionLayouts.last.sectionKey; + if (firstKey is EntryDateSectionKey && lastKey is EntryDateSectionKey) { + final newest = firstKey.date; + final oldest = lastKey.date; + if (newest != null && oldest != null) { + final locale = context.locale; + final dateFormat = (newest.difference(oldest).inHumanDays).abs() > 365 ? DateFormat.y(locale) : DateFormat.MMM(locale); + String? lastLabel; + sectionLayouts.forEach((section) { + final date = (section.sectionKey as EntryDateSectionKey).date; + if (date != null) { + final label = dateFormat.format(date); + if (label != lastLabel) { + crumbs[section.minOffset / maxOffset] = label; + lastLabel = label; + } + } + }); + } + } + case EntrySectionFactor.none: + break; + } + case EntrySortFactor.name: + case EntrySortFactor.path: + addAlbums(collection, sectionLayouts, crumbs); + case EntrySortFactor.rating: + case EntrySortFactor.size: + case EntrySortFactor.duration: + break; + } + return crumbs; + } + + Future<bool> get _isStoragePermissionGranted => Future.wait(Permissions.storage.map((v) => v.status)).then((v) => v.any((status) => status.isGranted)); +} diff --git a/lib/widgets/collection/collection_page.dart b/lib/widgets/collection/collection_page.dart new file mode 100644 index 0000000..3d4d958 --- /dev/null +++ b/lib/widgets/collection/collection_page.dart @@ -0,0 +1,230 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/app_service.dart'; +import 'package:aves/services/intent_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/collection/collection_grid.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/notifications.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/double_back.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_fab.dart'; +import 'package:aves/widgets/common/providers/query_provider.dart'; +import 'package:aves/widgets/common/providers/selection_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/navigation/drawer/app_drawer.dart'; +import 'package:aves/widgets/navigation/nav_bar/nav_bar.dart'; +import 'package:aves/widgets/navigation/tv_rail.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CollectionPage extends StatefulWidget { + static const routeName = '/collection'; + + final CollectionSource source; + final Set<CollectionFilter?>? filters; + final bool Function(AvesEntry element)? highlightTest; + + const CollectionPage({ + super.key, + required this.source, + required this.filters, + this.highlightTest, + }); + + @override + State<CollectionPage> createState() => _CollectionPageState(); +} + +class _CollectionPageState extends State<CollectionPage> { + final Set<StreamSubscription> _subscriptions = {}; + late CollectionLens _collection; + final StreamController<DraggableScrollbarEvent> _draggableScrollBarEventStreamController = StreamController.broadcast(); + + @override + void initState() { + // do not seed this widget with the collection, but control its lifecycle here instead, + // as the collection properties may change and they should not be reset by a widget update (e.g. with theme change) + _collection = CollectionLens( + source: widget.source, + filters: widget.filters, + ); + super.initState(); + _subscriptions.add(settings.updateStream.where((event) => event.key == SettingKeys.enableBinKey).listen((_) { + if (!settings.enableBin) { + _collection.removeFilter(TrashFilter.instance); + } + })); + WidgetsBinding.instance.addPostFrameCallback((_) => _checkInitHighlight()); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _collection.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + final liveFilter = _collection.filters.firstWhereOrNull((v) => v is QueryFilter && v.live) as QueryFilter?; + return SelectionProvider<AvesEntry>( + child: Selector<Selection<AvesEntry>, bool>( + selector: (context, selection) => selection.selectedItems.isNotEmpty, + builder: (context, hasSelection, child) { + final body = QueryProvider( + startEnabled: settings.getShowTitleQuery(context.currentRouteName!), + initialQuery: liveFilter?.query, + child: Builder( + builder: (context) { + return AvesPopScope( + handlers: [ + APopHandler( + canPop: (context) => context.select<Selection<AvesEntry>, bool>((v) => !v.isSelecting), + onPopBlocked: (context) => context.read<Selection<AvesEntry>>().browse(), + ), + tvNavigationPopHandler, + doubleBackPopHandler, + ], + child: GestureAreaProtectorStack( + child: DirectionalSafeArea( + start: !useTvLayout, + top: false, + bottom: false, + child: const CollectionGrid( + // key is expected by test driver + key: Key('collection-grid'), + settingsRouteKey: CollectionPage.routeName, + ), + ), + ), + ); + }, + ), + ); + + Widget page; + if (useTvLayout) { + page = AvesScaffold( + body: Row( + children: [ + TvRail( + controller: context.read<TvRailController>(), + currentCollection: _collection, + ), + Expanded(child: body), + ], + ), + resizeToAvoidBottomInset: false, + extendBody: true, + ); + } else { + page = Selector<Settings, bool>( + selector: (context, s) => s.enableBottomNavigationBar, + builder: (context, enableBottomNavigationBar, child) { + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + final showBottomNavigationBar = canNavigate && enableBottomNavigationBar; + + return NotificationListener<DraggableScrollbarNotification>( + onNotification: (notification) { + _draggableScrollBarEventStreamController.add(notification.event); + return false; + }, + child: AvesScaffold( + body: body, + floatingActionButton: _buildFab(context, hasSelection), + drawer: canNavigate ? AppDrawer(currentCollection: _collection) : null, + bottomNavigationBar: showBottomNavigationBar + ? AppBottomNavBar( + events: _draggableScrollBarEventStreamController.stream, + currentCollection: _collection, + ) + : null, + resizeToAvoidBottomInset: false, + extendBody: true, + ), + ); + }, + ); + } + // this provider should be above `TvRail` + return ChangeNotifierProvider<CollectionLens>.value( + value: _collection, + child: page, + ); + }, + ), + ); + } + + Widget? _buildFab(BuildContext context, bool hasSelection) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + switch (appMode) { + case AppMode.pickMultipleMediaExternal: + return hasSelection + ? AvesFab( + tooltip: context.l10n.pickTooltip, + onPressed: () async { + final items = context.read<Selection<AvesEntry>>().selectedItems; + final uris = items.map((entry) => entry.uri).toList(); + try { + await IntentService.submitPickedItems(uris); + } on TooManyItemsException catch (_) { + await showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.tooManyItemsErrorDialogMessage), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + }, + ) + : null; + case AppMode.pickCollectionFiltersExternal: + return AvesFab( + tooltip: context.l10n.pickTooltip, + onPressed: () { + final filters = _collection.filters; + IntentService.submitPickedCollectionFilters(filters); + }, + ); + default: + return null; + } + } + + Future<void> _checkInitHighlight() async { + final highlightTest = widget.highlightTest; + if (highlightTest == null) return; + + final item = _collection.sortedEntries.firstWhereOrNull(highlightTest); + if (item == null) return; + + final delayDuration = context.read<DurationsData>().staggeredAnimationPageTarget; + await Future.delayed(delayDuration + ADurations.highlightScrollInitDelay); + + if (!mounted) return; + final animate = context.read<Settings>().animate; + context.read<HighlightInfo>().trackItem(item, animate: animate, highlightItem: item); + } +} diff --git a/lib/widgets/collection/draggable_thumb_label.dart b/lib/widgets/collection/draggable_thumb_label.dart new file mode 100644 index 0000000..1361316 --- /dev/null +++ b/lib/widgets/collection/draggable_thumb_label.dart @@ -0,0 +1,83 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/draggable_thumb_label.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CollectionDraggableThumbLabel extends StatelessWidget { + final CollectionLens collection; + final double offsetY; + + const CollectionDraggableThumbLabel({ + super.key, + required this.collection, + required this.offsetY, + }); + + @override + Widget build(BuildContext context) { + return DraggableThumbLabel<AvesEntry>( + offsetY: offsetY, + lineBuilder: (context, entry) { + switch (collection.sortFactor) { + case EntrySortFactor.date: + final date = entry.bestDate; + switch (collection.sectionFactor) { + case EntrySectionFactor.album: + return [ + DraggableThumbLabel.formatMonthThumbLabel(context, date), + if (_showAlbumName(context, entry)) _getAlbumName(context, entry), + ]; + case EntrySectionFactor.month: + case EntrySectionFactor.none: + return [ + DraggableThumbLabel.formatMonthThumbLabel(context, date), + ]; + case EntrySectionFactor.day: + return [ + DraggableThumbLabel.formatDayThumbLabel(context, date), + ]; + } + case EntrySortFactor.name: + final entryTitle = entry.bestTitle; + return [ + if (_showAlbumName(context, entry)) _getAlbumName(context, entry), + if (entryTitle != null) entryTitle, + ]; + case EntrySortFactor.rating: + return [ + RatingFilter.formatRating(context, entry.rating), + DraggableThumbLabel.formatMonthThumbLabel(context, entry.bestDate), + ]; + case EntrySortFactor.size: + final sizeBytes = entry.sizeBytes; + return [ + if (sizeBytes != null) formatFileSize(context.locale, sizeBytes, round: 0), + ]; + case EntrySortFactor.duration: + return [ + if (entry.durationMillis != null) entry.durationText, + ]; + case EntrySortFactor.path: + final entryFilename = entry.filenameWithoutExtension; + return [ + if (_showAlbumName(context, entry)) _getAlbumName(context, entry), + if (entryFilename != null) entryFilename, + ]; + } + }, + ); + } + + bool _hasMultipleSections(BuildContext context) => context.read<SectionedListLayout<AvesEntry>>().sections.length > 1; + + bool _showAlbumName(BuildContext context, AvesEntry entry) => _hasMultipleSections(context) && entry.directory != null; + + String _getAlbumName(BuildContext context, AvesEntry entry) => context.read<CollectionSource>().getStoredAlbumDisplayName(context, entry.directory!); +} diff --git a/lib/widgets/collection/entry_set_action_delegate.dart b/lib/widgets/collection/entry_set_action_delegate.dart new file mode 100644 index 0000000..89520bf --- /dev/null +++ b/lib/widgets/collection/entry_set_action_delegate.dart @@ -0,0 +1,885 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/entry/extensions/metadata_edition.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/set_and.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/model/naming_pattern.dart'; +import 'package:aves/model/query.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/analysis_controller.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/app_service.dart'; +import 'package:aves/services/common/image_op_events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/media_edit_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/utils/mime_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/entry_editor.dart'; +import 'package:aves/widgets/common/action_mixins/entry_storage.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/action_mixins/size_aware.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/dialogs/add_shortcut_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/convert_entry_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/rename_entry_set_page.dart'; +import 'package:aves/widgets/dialogs/filter_editors/create_dynamic_album_dialog.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/location_pick_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves/widgets/stats/stats_page.dart'; +import 'package:aves/widgets/viewer/slideshow_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class EntrySetActionDelegate with FeedbackMixin, PermissionAwareMixin, SizeAwareMixin, EntryEditorMixin, EntryStorageMixin, VaultAwareMixin { + bool isVisible( + EntrySetAction action, { + required AppMode appMode, + required bool isSelecting, + required int itemCount, + required int selectedItemCount, + required bool isTrash, + }) { + final canWrite = !settings.isReadOnly; + final isMain = appMode == AppMode.main; + final useTvLayout = settings.useTvLayout; + switch (action) { + // general + case EntrySetAction.configureView: + return true; + case EntrySetAction.select: + return appMode.canSelectMedia && !isSelecting; + case EntrySetAction.selectAll: + return (isSelecting && selectedItemCount < itemCount) || (!isSelecting && settings.collectionBrowsingQuickActions.contains(action)); + case EntrySetAction.selectNone: + return isSelecting && selectedItemCount == itemCount; + // browsing + case EntrySetAction.searchCollection: + return appMode.canNavigate && !isSelecting && !useTvLayout; + case EntrySetAction.toggleTitleSearch: + return !isSelecting && !useTvLayout; + case EntrySetAction.addShortcut: + return isMain && !isSelecting && !isTrash && device.canPinShortcut; + case EntrySetAction.addDynamicAlbum: + case EntrySetAction.setHome: + return isMain && !isSelecting && !isTrash && !useTvLayout; + case EntrySetAction.emptyBin: + return isMain && isTrash && canWrite; + // browsing or selecting + case EntrySetAction.map: + case EntrySetAction.slideshow: + case EntrySetAction.stats: + return isMain; + case EntrySetAction.rescan: + return isMain && isSelecting && !useTvLayout; + // selecting + case EntrySetAction.share: + case EntrySetAction.toggleFavourite: + return isMain && isSelecting && !isTrash; + case EntrySetAction.delete: + return isMain && isSelecting && canWrite; + case EntrySetAction.copy: + case EntrySetAction.move: + case EntrySetAction.rename: + case EntrySetAction.convert: + case EntrySetAction.rotateCCW: + case EntrySetAction.rotateCW: + case EntrySetAction.flip: + case EntrySetAction.editDate: + case EntrySetAction.editLocation: + case EntrySetAction.editTitleDescription: + case EntrySetAction.editRating: + case EntrySetAction.editTags: + case EntrySetAction.removeMetadata: + return isMain && isSelecting && !isTrash && canWrite; + case EntrySetAction.restore: + return isMain && isSelecting && isTrash && canWrite; + } + } + + bool canApply( + EntrySetAction action, { + required bool isSelecting, + required CollectionLens collection, + required int selectedItemCount, + }) { + final itemCount = collection.entryCount; + final hasItems = itemCount > 0; + final hasSelection = selectedItemCount > 0; + + switch (action) { + case EntrySetAction.configureView: + return true; + case EntrySetAction.select: + return hasItems; + case EntrySetAction.selectAll: + return selectedItemCount < itemCount || (!isSelecting && settings.collectionBrowsingQuickActions.contains(action)); + case EntrySetAction.selectNone: + return hasSelection; + case EntrySetAction.searchCollection: + case EntrySetAction.toggleTitleSearch: + case EntrySetAction.addShortcut: + case EntrySetAction.setHome: + return true; + case EntrySetAction.addDynamicAlbum: + return collection.filters.isNotEmpty; + case EntrySetAction.emptyBin: + return !isSelecting && hasItems; + case EntrySetAction.map: + case EntrySetAction.slideshow: + case EntrySetAction.stats: + case EntrySetAction.rescan: + return (!isSelecting && hasItems) || (isSelecting && hasSelection); + // selecting + case EntrySetAction.share: + case EntrySetAction.delete: + case EntrySetAction.restore: + case EntrySetAction.copy: + case EntrySetAction.move: + case EntrySetAction.rename: + case EntrySetAction.convert: + case EntrySetAction.toggleFavourite: + case EntrySetAction.rotateCCW: + case EntrySetAction.rotateCW: + case EntrySetAction.flip: + case EntrySetAction.editDate: + case EntrySetAction.editLocation: + case EntrySetAction.editTitleDescription: + case EntrySetAction.editRating: + case EntrySetAction.editTags: + case EntrySetAction.removeMetadata: + return hasSelection; + } + } + + void onActionSelected(BuildContext context, EntrySetAction action) { + reportService.log('$runtimeType handles $action'); + switch (action) { + // general + case EntrySetAction.configureView: + case EntrySetAction.select: + case EntrySetAction.selectAll: + case EntrySetAction.selectNone: + break; + // browsing + case EntrySetAction.searchCollection: + _goToSearch(context); + case EntrySetAction.toggleTitleSearch: + final routeName = context.currentRouteName!; + settings.setShowTitleQuery(routeName, !settings.getShowTitleQuery(routeName)); + context.read<Query>().toggle(); + case EntrySetAction.addDynamicAlbum: + _addDynamicAlbum(context); + case EntrySetAction.addShortcut: + _addShortcut(context); + case EntrySetAction.setHome: + _setHome(context); + // browsing or selecting + case EntrySetAction.map: + _goToMap(context); + case EntrySetAction.slideshow: + _goToSlideshow(context); + case EntrySetAction.stats: + _goToStats(context); + case EntrySetAction.rescan: + _rescan(context); + // selecting + case EntrySetAction.share: + _share(context); + case EntrySetAction.delete: + case EntrySetAction.emptyBin: + _delete(context); + case EntrySetAction.restore: + _move(context, moveType: MoveType.fromBin); + case EntrySetAction.copy: + _move(context, moveType: MoveType.copy); + case EntrySetAction.move: + _move(context, moveType: MoveType.move); + case EntrySetAction.rename: + _rename(context); + case EntrySetAction.convert: + _convert(context); + case EntrySetAction.toggleFavourite: + _toggleFavourite(context); + case EntrySetAction.rotateCCW: + _rotate(context, clockwise: false); + case EntrySetAction.rotateCW: + _rotate(context, clockwise: true); + case EntrySetAction.flip: + _flip(context); + case EntrySetAction.editDate: + editDate(context); + case EntrySetAction.editLocation: + _editLocation(context); + case EntrySetAction.editTitleDescription: + _editTitleDescription(context); + case EntrySetAction.editRating: + _editRating(context); + case EntrySetAction.editTags: + _editTags(context); + case EntrySetAction.removeMetadata: + _removeMetadata(context); + } + } + + void _browse(BuildContext context) { + context.read<Selection<AvesEntry>?>()?.browse(); + } + + Set<AvesEntry> _getTargetItems(BuildContext context) { + final selection = context.read<Selection<AvesEntry>>(); + final groupedEntries = (selection.isSelecting ? selection.selectedItems : context.read<CollectionLens>().sortedEntries); + return groupedEntries.expand((entry) => entry.stackedEntries ?? {entry}).toSet(); + } + + Future<void> _share(BuildContext context) async { + final entries = _getTargetItems(context); + try { + if (!await appService.shareEntries(entries)) { + await showNoMatchingAppDialog(context); + } + } on TooManyItemsException catch (_) { + await showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.tooManyItemsErrorDialogMessage), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + } + + void _rescan(BuildContext context) { + final entries = _getTargetItems(context); + + final controller = AnalysisController(canStartService: true, force: true); + final collection = context.read<CollectionLens>(); + collection.source.analyze(controller, entries: entries).then((_) => controller.dispose()); + + _browse(context); + } + + Future<void> _delete(BuildContext context) async { + final entries = _getTargetItems(context); + final byBinUsage = groupBy<AvesEntry, bool>(entries, (entry) { + final details = vaults.getVault(entry.directory); + return details?.useBin ?? settings.enableBin; + }); + var completed = true; + await Future.forEach(byBinUsage.entries, (kv) async { + completed &= await doDelete( + context: context, + entries: kv.value.toSet(), + enableBin: kv.key, + ); + }); + + if (completed) { + _browse(context); + } + } + + // returns whether it completed the action (with or without failures) + Future<bool> doDelete({ + required BuildContext context, + required Set<AvesEntry> entries, + required bool enableBin, + }) async { + final pureTrash = entries.every((entry) => entry.trashed); + if (enableBin && !pureTrash) { + return await doMove(context, moveType: MoveType.toBin, entries: entries); + } + + final l10n = context.l10n; + final source = context.read<CollectionSource>(); + final storageDirs = entries.map((e) => e.storageDirectory).nonNulls.toSet(); + final todoCount = entries.length; + + if (!await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.deleteForever, + message: l10n.deleteEntriesConfirmationDialogMessage(todoCount), + confirmationButtonLabel: l10n.deleteButtonLabel, + )) { + return false; + } + + if (!await checkStoragePermissionForAlbums(context, storageDirs, entries: entries)) return false; + + source.pauseMonitoring(); + final opId = mediaEditService.newOpId; + await showOpReport<ImageOpEvent>( + context: context, + opStream: mediaEditService.delete(opId: opId, entries: entries), + itemCount: todoCount, + onCancel: () => mediaEditService.cancelFileOp(opId), + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final deletedOps = successOps.where((op) => !op.skipped).toSet(); + final deletedUris = deletedOps.map((op) => op.uri).toSet(); + await source.removeEntries(deletedUris, includeTrash: true); + source.resumeMonitoring(); + + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedback(context, FeedbackType.warn, context.l10n.collectionDeleteFailureFeedback(count)); + } + + // cleanup + await storageService.deleteEmptyRegularDirectories(storageDirs); + }, + ); + return true; + } + + Future<void> quickMove(BuildContext context, String destinationAlbum, {required bool copy}) async { + if (!await unlockAlbum(context, destinationAlbum)) return; + + final entries = _getTargetItems(context); + final completed = await doQuickMove( + context, + moveType: copy ? MoveType.copy : MoveType.move, + entriesByDestination: { + destinationAlbum: entries, + }, + ); + + if (completed) { + _browse(context); + } + } + + Future<void> _move(BuildContext context, {required MoveType moveType}) async { + final entries = _getTargetItems(context); + final completed = await doMove(context, moveType: moveType, entries: entries); + + if (completed) { + _browse(context); + } + } + + Future<void> _rename(BuildContext context) async { + final entries = _getTargetItems(context).toList(); + + final pattern = await Navigator.maybeOf(context)?.push<NamingPattern>( + MaterialPageRoute( + settings: const RouteSettings(name: RenameEntrySetPage.routeName), + builder: (context) => RenameEntrySetPage( + entries: entries, + ), + ), + ); + if (pattern == null) return; + + final namingFutures = entries.mapIndexed((index, entry) async { + final newName = await pattern.apply(entry, index); + return MapEntry(entry, '$newName${entry.extension}'); + }); + final entriesToNewName = Map.fromEntries(await Future.wait(namingFutures)).whereNotNullValue(); + final completed = await rename(context, entriesToNewName: entriesToNewName, persist: true); + + if (completed) { + _browse(context); + } + } + + Future<void> _convert(BuildContext context) async { + final entries = _getTargetItems(context); + + final options = await showDialog<EntryConvertOptions>( + context: context, + builder: (context) => ConvertEntryDialog(entries: entries), + routeSettings: const RouteSettings(name: ConvertEntryDialog.routeName), + ); + if (options == null) return; + + switch (options.action) { + case EntryConvertAction.convert: + final completed = await doExport(context, entries, options); + if (completed) { + _browse(context); + } + case EntryConvertAction.convertMotionPhotoToStillImage: + final todoItems = entries.where((entry) => entry.isMotionPhoto).toSet(); + await _edit(context, todoItems, (entry) => entry.removeTrailerVideo()); + } + } + + Future<void> _toggleFavourite(BuildContext context) async { + final entries = _getTargetItems(context); + if (entries.every((entry) => entry.isFavourite)) { + await favourites.removeEntries(entries); + } else { + await favourites.add(entries); + } + + _browse(context); + } + + Future<void> _edit( + BuildContext context, + Set<AvesEntry> todoItems, + Future<Set<EntryDataType>> Function(AvesEntry entry) op, { + bool showResult = true, + }) async { + final selectionDirs = todoItems.map((e) => e.directory).nonNulls.toSet(); + final todoCount = todoItems.length; + + if (!await checkStoragePermissionForAlbums(context, selectionDirs, entries: todoItems)) return; + + Set<String> obsoleteTags = todoItems.expand((entry) => entry.tags).toSet(); + Set<String> obsoleteCountryCodes = todoItems.where((entry) => entry.hasAddress).map((entry) => entry.addressDetails?.countryCode).nonNulls.toSet(); + Set<String> obsoleteStateCodes = todoItems.where((entry) => entry.hasAddress).map((entry) => entry.addressDetails?.stateCode).nonNulls.toSet(); + + final dataTypes = <EntryDataType>{}; + final source = context.read<CollectionSource>(); + source.pauseMonitoring(); + var cancelled = false; + await showOpReport<ImageOpEvent>( + context: context, + opStream: Stream.fromIterable(todoItems).asyncMap((entry) async { + if (cancelled) { + return ImageOpEvent(success: true, skipped: true, uri: entry.uri); + } else { + final opDataTypes = await op(entry); + dataTypes.addAll(opDataTypes); + return ImageOpEvent(success: opDataTypes.isNotEmpty, skipped: false, uri: entry.uri); + } + }).asBroadcastStream(), + itemCount: todoCount, + onCancel: () => cancelled = true, + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final editedOps = successOps.where((op) => !op.skipped).toSet(); + source.resumeMonitoring(); + + unawaited(source.refreshUris(editedOps.map((op) => op.uri).toSet()).then((_) { + // invalidate filters derived from values before edition + // this invalidation must happen after the source is refreshed, + // otherwise filter chips may eagerly rebuild in between with the old state + if (obsoleteCountryCodes.isNotEmpty) { + source.invalidateCountryFilterSummary(countryCodes: obsoleteCountryCodes); + } + if (obsoleteStateCodes.isNotEmpty) { + source.invalidateStateFilterSummary(stateCodes: obsoleteStateCodes); + } + if (obsoleteTags.isNotEmpty) { + source.invalidateTagFilterSummary(tags: obsoleteTags); + } + })); + + if (dataTypes.contains(EntryDataType.aspectRatio)) { + source.onAspectRatioChanged(); + } + + if (showResult) { + final l10n = context.l10n; + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedback(context, FeedbackType.warn, l10n.collectionEditFailureFeedback(count)); + } else { + final count = editedOps.length; + showFeedback(context, FeedbackType.info, l10n.collectionEditSuccessFeedback(count)); + } + } + }, + ); + _browse(context); + } + + Future<Set<AvesEntry>?> _getEditableTargetItems( + BuildContext context, { + required bool Function(AvesEntry entry) canEdit, + }) => + _getEditableItems(context, _getTargetItems(context), canEdit: canEdit); + + Future<Set<AvesEntry>?> _getEditableItems( + BuildContext context, + Set<AvesEntry> entries, { + required bool Function(AvesEntry entry) canEdit, + }) async { + final bySupported = groupBy<AvesEntry, bool>(entries, canEdit); + final supported = (bySupported[true] ?? []).toSet(); + final unsupported = (bySupported[false] ?? []).toSet(); + + if (unsupported.isEmpty) return supported; + + final unsupportedTypes = unsupported.map((entry) => entry.mimeType).toSet().map(MimeUtils.displayType).toList()..sort(); + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.unsupportedTypeDialogMessage(unsupportedTypes.length, unsupportedTypes.join(', '))), + actions: [ + const CancelButton(), + if (supported.isNotEmpty) + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.continueButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return null; + + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + return supported; + } + + Future<void> _rotate(BuildContext context, {required bool clockwise}) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canRotate); + if (entries == null || entries.isEmpty) return; + + await _edit(context, entries, (entry) => entry.rotate(clockwise: clockwise)); + } + + Future<void> _flip(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canFlip); + if (entries == null || entries.isEmpty) return; + + await _edit(context, entries, (entry) => entry.flip()); + } + + Future<void> editDate(BuildContext context, {Set<AvesEntry>? entries, DateModifier? modifier, bool showResult = true}) async { + entries ??= await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditDate); + if (entries == null || entries.isEmpty) return; + + if (modifier == null) { + final collection = context.read<CollectionLens>(); + modifier = await selectDateModifier(context, entries, collection); + } + if (modifier == null) return; + + await _edit(context, entries, (entry) => entry.editDate(modifier!), showResult: showResult); + } + + Future<void> _editLocation(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditLocation); + if (entries == null || entries.isEmpty) return; + + final collection = context.read<CollectionLens>(); + final locationByEntry = await selectLocation(context, entries, collection); + if (locationByEntry == null) return; + + await _edit(context, locationByEntry.keys.toSet(), (entry) => entry.editLocation(locationByEntry[entry])); + } + + Future<LatLng?> editLocationByMap(BuildContext context, Set<AvesEntry> entries, LatLng clusterLocation, CollectionLens mapCollection) async { + final editableEntries = await _getEditableItems(context, entries, canEdit: (entry) => entry.canEditLocation); + if (editableEntries == null || editableEntries.isEmpty) return null; + + final location = await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: LocationPickPage.routeName), + builder: (context) => LocationPickPage( + collection: mapCollection, + initialLocation: clusterLocation, + ), + fullscreenDialog: true, + ), + ); + if (location == null) return null; + + await _edit(context, editableEntries, (entry) => entry.editLocation(location)); + return location; + } + + Future<void> removeLocation(BuildContext context, Set<AvesEntry> entries) async { + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.genericDangerWarningDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.applyButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return; + + final editableEntries = await _getEditableItems(context, entries, canEdit: (entry) => entry.canEditLocation); + if (editableEntries == null || editableEntries.isEmpty) return; + + await _edit(context, editableEntries, (entry) => entry.editLocation(ExtraAvesEntryMetadataEdition.removalLocation)); + } + + Future<void> _editTitleDescription(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditTitleDescription); + if (entries == null || entries.isEmpty) return; + + final modifier = await selectTitleDescriptionModifier(context, entries); + if (modifier == null) return; + + await _edit(context, entries, (entry) => entry.editTitleDescription(modifier)); + } + + Future<void> quickRate(BuildContext context, int rating) => _editRating(context, rating: rating); + + Future<void> _editRating(BuildContext context, {int? rating}) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditRating); + if (entries == null || entries.isEmpty) return; + + rating ??= await selectRating(context, entries); + if (rating == null) return; + + await _edit(context, entries, (entry) => entry.editRating(rating)); + } + + Future<void> quickTag(BuildContext context, CollectionFilter filter) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditTags); + if (entries == null || entries.isEmpty) return; + + final newTagsByEntry = <AvesEntry, Set<String>>{}; + await Future.forEach(entries, (entry) async { + newTagsByEntry[entry] = { + ...entry.tags, + ...await getTagsFromFilters({filter}, entry), + }; + }); + + await _doEditTags(context, newTagsByEntry); + } + + Future<void> _editTags(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditTags); + if (entries == null || entries.isEmpty) return; + + final newTagsByEntry = await selectTags(context, entries); + if (newTagsByEntry == null) return; + + await _doEditTags(context, newTagsByEntry); + } + + Future<void> _doEditTags(BuildContext context, Map<AvesEntry, Set<String>> newTagsByEntry) async { + final entries = newTagsByEntry.keys.toSet(); + + // only process modified items + entries.removeWhere((entry) { + final newTags = newTagsByEntry[entry] ?? entry.tags; + final currentTags = entry.tags; + return newTags.length == currentTags.length && newTags.every(currentTags.contains); + }); + if (entries.isEmpty) return; + + await _edit(context, entries, (entry) => entry.editTags(newTagsByEntry[entry]!)); + } + + Future<void> removeTags(BuildContext context, {required Set<AvesEntry> entries, required Set<String> tags}) async { + final newTagsByEntry = Map.fromEntries(entries.map((v) { + return MapEntry(v, v.tags.whereNot(tags.contains).toSet()); + })); + + await _edit(context, entries, (entry) => entry.editTags(newTagsByEntry[entry]!)); + } + + Future<void> _removeMetadata(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.isMetadataRemovalSupported); + if (entries == null || entries.isEmpty) return; + + final types = await selectMetadataToRemove(context, entries); + if (types == null || types.isEmpty) return; + + await _edit(context, entries, (entry) => entry.removeMetadata(types)); + } + + Future<void> _goToMap(BuildContext context) async { + final collection = context.read<CollectionLens>(); + final entries = _getTargetItems(context); + + // need collection with fresh ID to prevent hero from scroller on Map page to Collection page + final mapCollection = CollectionLens( + source: collection.source, + filters: collection.filters, + fixedSelection: entries.where((entry) => entry.hasGps).toList(), + ); + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: MapPage.routeName), + builder: (context) => MapPage(collection: mapCollection), + ), + ); + } + + void _goToSlideshow(BuildContext context) { + final collection = context.read<CollectionLens>(); + final entries = _getTargetItems(context); + + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: SlideshowPage.routeName), + builder: (context) { + return SlideshowPage( + collection: CollectionLens( + source: collection.source, + filters: collection.filters, + fixedSelection: entries.toList(), + ), + ); + }, + ), + ); + } + + void _goToStats(BuildContext context) { + final collection = context.read<CollectionLens>(); + final entries = _getTargetItems(context); + + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: StatsPage.routeName), + builder: (context) => StatsPage( + entries: entries, + source: collection.source, + parentCollection: collection, + ), + ), + ); + } + + void _goToSearch(BuildContext context) { + final collection = context.read<CollectionLens>(); + + Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: collection.source, + parentCollection: collection, + ), + ), + ); + } + + static String? _getDefaultNameForFilters(BuildContext context, Set<CollectionFilter> filters) { + String? defaultName; + if (filters.isNotEmpty) { + // we compute the default name beforehand + // because some filter labels need localization + final sortedFilters = List<CollectionFilter>.from(filters)..sort(); + defaultName = sortedFilters.first.getLabel(context).replaceAll('\n', ' '); + } + return defaultName; + } + + Future<void> _addDynamicAlbum(BuildContext context) async { + final l10n = context.l10n; + final collection = context.read<CollectionLens>(); + final filters = collection.filters; + if (filters.isEmpty) return; + + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + + final name = await showDialog<String>( + context: context, + builder: (context) => const CreateDynamicAlbumDialog(), + routeSettings: const RouteSettings(name: CreateDynamicAlbumDialog.routeName), + ); + if (name == null) return; + + final existingAlbum = dynamicAlbums.get(name); + if (existingAlbum != null) { + // album already exists, so we just need to highlight it + await _showDynamicAlbum(navigator, existingAlbum); + } else { + final album = DynamicAlbumFilter(name, filters.length == 1 ? filters.first : SetAndFilter(filters)); + await dynamicAlbums.add(album); + + final showAction = SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () => _showDynamicAlbum(navigator, album), + ); + showFeedback(context, FeedbackType.info, l10n.genericSuccessFeedback, showAction); + } + } + + Future<void> _showDynamicAlbum(NavigatorState? navigator, DynamicAlbumFilter albumFilter) async { + // local context may be deactivated when action is triggered after navigation + if (navigator != null) { + final context = navigator.context; + final highlightInfo = context.read<HighlightInfo>(); + if (context.currentRouteName == AlbumListPage.routeName) { + highlightInfo.trackItem(FilterGridItem(albumFilter, null), highlightItem: albumFilter); + } else { + highlightInfo.set(albumFilter); + final initialGroup = albumGrouping.getFilterParent(albumFilter); + await navigator.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: AlbumListPage.routeName), + builder: (_) => AlbumListPage(initialGroup: initialGroup), + ), + (route) => false, + ); + } + } + } + + Future<void> _addShortcut(BuildContext context) async { + final collection = context.read<CollectionLens>(); + final filters = collection.filters; + + String? defaultName = _getDefaultNameForFilters(context, filters); + final result = await showDialog<(AvesEntry?, String)>( + context: context, + builder: (context) => AddShortcutDialog( + defaultName: defaultName ?? '', + collection: collection, + ), + routeSettings: const RouteSettings(name: AddShortcutDialog.routeName), + ); + if (result == null) return; + + final (coverEntry, name) = result; + if (name.isEmpty) return; + + await appService.pinToHomeScreen(name, coverEntry, route: CollectionPage.routeName, filters: filters); + if (!device.showPinShortcutFeedback) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } + } + + void _setHome(BuildContext context) async { + settings.setHome(HomePageSetting.collection, customCollection: context.read<CollectionLens>().filters); + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } +} diff --git a/lib/widgets/collection/filter_bar.dart b/lib/widgets/collection/filter_bar.dart new file mode 100644 index 0000000..b565d7b --- /dev/null +++ b/lib/widgets/collection/filter_bar.dart @@ -0,0 +1,163 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class FilterBar extends StatefulWidget { + static const EdgeInsets chipPadding = EdgeInsets.symmetric(horizontal: 4); + static const EdgeInsets rowPadding = EdgeInsets.symmetric(horizontal: 4); + static const EdgeInsets padding = EdgeInsets.only(top: 4, bottom: 8); + static final double preferredHeight = AvesFilterChip.minChipHeight + padding.vertical; + + final List<CollectionFilter> filters; + final bool interactive; + final AFilterCallback? onTap, onRemove; + + FilterBar({ + super.key, + required Set<CollectionFilter> filters, + this.interactive = true, + this.onTap, + this.onRemove, + }) : filters = List<CollectionFilter>.from(filters)..sort(); + + @override + State<FilterBar> createState() => _FilterBarState(); +} + +class _FilterBarState extends State<FilterBar> { + final GlobalKey<AnimatedListState> _animatedListKey = GlobalKey(debugLabel: 'filter-bar-animated-list'); + CollectionFilter? _userTappedFilter; + + List<CollectionFilter> get filters => widget.filters; + + @override + void didUpdateWidget(covariant FilterBar oldWidget) { + super.didUpdateWidget(oldWidget); + final current = widget.filters; + final existing = oldWidget.filters; + final removed = existing.where((filter) => !current.contains(filter)).toList(); + final added = current.where((filter) => !existing.contains(filter)).toList(); + final listState = _animatedListKey.currentState; + removed.forEach((filter) { + final index = existing.indexOf(filter); + existing.removeAt(index); + // only animate item removal when triggered by a user interaction with the chip, + // not from automatic chip replacement following chip selection + final animate = context.read<Settings>().animate && _userTappedFilter == filter; + listState!.removeItem( + index, + animate + ? (context, animation) { + animation = animation.drive(CurveTween(curve: Curves.easeInOutBack)); + return FadeTransition( + opacity: animation, + child: SizeTransition( + axis: Axis.horizontal, + sizeFactor: animation, + child: ScaleTransition( + scale: animation, + child: _buildChip(filter), + ), + ), + ); + } + : (context, animation) => const SizedBox(), + duration: animate ? ADurations.filterBarRemovalAnimation : Duration.zero, + ); + }); + added.forEach((filter) { + final index = current.indexOf(filter); + listState!.insertItem( + index, + duration: Duration.zero, + ); + }); + _userTappedFilter = null; + } + + @override + Widget build(BuildContext context) { + return Container( + // specify transparent as a workaround to prevent + // chip border clipping when the floating app bar is fading + padding: FilterBar.padding, + color: Colors.transparent, + height: FilterBar.preferredHeight, + child: AnimatedList( + key: _animatedListKey, + initialItemCount: filters.length, + scrollDirection: Axis.horizontal, + padding: FilterBar.rowPadding, + itemBuilder: (context, index, animation) { + if (index >= filters.length) return const SizedBox(); + return _buildChip(filters.toList()[index]); + }, + ), + ); + } + + Widget _buildChip(CollectionFilter filter) { + final onTap = widget.onTap != null + ? (filter) { + _userTappedFilter = filter; + widget.onTap?.call(filter); + } + : null; + final onRemove = widget.onRemove != null + ? (filter) { + _userTappedFilter = filter; + widget.onRemove?.call(filter); + } + : null; + return _Chip( + filter: filter, + single: filters.length == 1, + interactive: widget.interactive, + onTap: onTap, + onRemove: onRemove, + ); + } +} + +class _Chip extends StatelessWidget { + final CollectionFilter filter; + final bool single, interactive; + final AFilterCallback? onTap, onRemove; + + const _Chip({ + required this.filter, + required this.single, + required this.interactive, + required this.onTap, + required this.onRemove, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: FilterBar.chipPadding, + child: Center( + child: AvesFilterChip( + key: ValueKey(filter), + filter: filter, + maxWidth: single + ? AvesFilterChip.computeMaxWidthForRow( + context, + minChipPerRow: 1, + chipPadding: FilterBar.chipPadding.horizontal, + rowPadding: FilterBar.rowPadding.horizontal + AvesFloatingBar.margin.horizontal, + ) + : null, + heroType: HeroType.always, + onTap: onTap, + onRemove: onRemove, + onLongPress: interactive ? AvesFilterChip.showDefaultLongPressMenu : null, + ), + ), + ); + } +} diff --git a/lib/widgets/collection/grid/headers/album.dart b/lib/widgets/collection/grid/headers/album.dart new file mode 100644 index 0000000..8adb22f --- /dev/null +++ b/lib/widgets/collection/grid/headers/album.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/covers.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:aves/widgets/common/identity/aves_icons.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class AlbumSectionHeader extends StatelessWidget { + final String? directory, albumName; + final bool selectable; + + const AlbumSectionHeader({ + super.key, + required this.directory, + required this.albumName, + required this.selectable, + }); + + @override + Widget build(BuildContext context) { + Widget? albumIcon; + final _directory = directory; + if (_directory != null) { + albumIcon = IconUtils.getAlbumIcon(context: context, albumPath: _directory); + if (albumIcon != null) { + albumIcon = RepaintBoundary( + child: albumIcon, + ); + } + } + return SectionHeader<AvesEntry>( + sectionKey: EntryAlbumSectionKey(_directory), + leading: albumIcon, + title: albumName ?? context.l10n.sectionUnknown, + trailing: _directory != null && androidFileUtils.isOnRemovableStorage(_directory) + ? const Icon( + AIcons.storageCard, + size: 16, + color: Color(0xFF757575), + ) + : null, + selectable: selectable, + ); + } + + static double getPreferredHeight(BuildContext context, double maxWidth, CollectionSource source, EntryAlbumSectionKey sectionKey) { + final directory = sectionKey.directory ?? context.l10n.sectionUnknown; + return SectionHeader.getPreferredHeight( + context: context, + maxWidth: maxWidth, + title: source.getStoredAlbumDisplayName(context, directory), + hasLeading: covers.effectiveAlbumType(directory) != AlbumType.regular, + hasTrailing: androidFileUtils.isOnRemovableStorage(directory), + ); + } +} diff --git a/lib/widgets/collection/grid/headers/any.dart b/lib/widgets/collection/grid/headers/any.dart new file mode 100644 index 0000000..0360041 --- /dev/null +++ b/lib/widgets/collection/grid/headers/any.dart @@ -0,0 +1,98 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/collection/grid/headers/album.dart'; +import 'package:aves/widgets/collection/grid/headers/date.dart'; +import 'package:aves/widgets/collection/grid/headers/rating.dart'; +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class CollectionSectionHeader extends StatelessWidget { + final CollectionLens collection; + final SectionKey sectionKey; + final double height; + final bool selectable; + + const CollectionSectionHeader({ + super.key, + required this.collection, + required this.sectionKey, + required this.height, + required this.selectable, + }); + + @override + Widget build(BuildContext context) { + final header = _buildHeader(context); + return header != null + ? SizedBox( + height: height, + child: header, + ) + : const SizedBox(); + } + + Widget? _buildHeader(BuildContext context) { + switch (collection.sortFactor) { + case EntrySortFactor.date: + switch (collection.sectionFactor) { + case EntrySectionFactor.album: + return _buildAlbumHeader(context); + case EntrySectionFactor.month: + return MonthSectionHeader<AvesEntry>( + key: ValueKey(sectionKey), + date: (sectionKey as EntryDateSectionKey).date, + selectable: selectable, + ); + case EntrySectionFactor.day: + return DaySectionHeader<AvesEntry>( + key: ValueKey(sectionKey), + date: (sectionKey as EntryDateSectionKey).date, + selectable: selectable, + ); + case EntrySectionFactor.none: + break; + } + case EntrySortFactor.name: + case EntrySortFactor.path: + return _buildAlbumHeader(context); + case EntrySortFactor.rating: + return RatingSectionHeader<AvesEntry>( + key: ValueKey(sectionKey), + rating: (sectionKey as EntryRatingSectionKey).rating, + selectable: selectable, + ); + case EntrySortFactor.size: + case EntrySortFactor.duration: + break; + } + return null; + } + + Widget _buildAlbumHeader(BuildContext context) { + final source = collection.source; + final directory = (sectionKey as EntryAlbumSectionKey).directory; + return AlbumSectionHeader( + key: ValueKey(sectionKey), + directory: directory, + albumName: directory != null ? source.getStoredAlbumDisplayName(context, directory) : null, + selectable: selectable, + ); + } + + static double getPreferredHeight(BuildContext context, double maxWidth, CollectionSource source, SectionKey sectionKey) { + var headerExtent = 0.0; + if (sectionKey is EntryAlbumSectionKey) { + // only compute height for album headers, as they're the only likely ones to split on multiple lines + headerExtent = AlbumSectionHeader.getPreferredHeight(context, maxWidth, source, sectionKey); + } + + final textScaler = MediaQuery.textScalerOf(context); + headerExtent = max(headerExtent, textScaler.scale(SectionHeader.leadingSize.height)) + SectionHeader.padding.vertical + SectionHeader.margin.vertical; + return headerExtent; + } +} diff --git a/lib/widgets/collection/grid/headers/date.dart b/lib/widgets/collection/grid/headers/date.dart new file mode 100644 index 0000000..2dd5138 --- /dev/null +++ b/lib/widgets/collection/grid/headers/date.dart @@ -0,0 +1,87 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class DaySectionHeader<T> extends StatelessWidget { + final DateTime? date; + final bool selectable; + + const DaySectionHeader({ + super.key, + required this.date, + required this.selectable, + }); + + // Examples (en_US): + // `MMMMd`: `April 15` + // `yMMMMd`: `April 15, 2020` + // `MMMEd`: `Wed, Apr 15` + // `yMMMEd`: `Wed, Apr 15, 2020` + // `MMMMEEEEd`: `Wednesday, April 15` + // `yMMMMEEEEd`: `Wednesday, April 15, 2020` + // `MEd`: `Wed, 4/15` + // `yMEd`: `Wed, 4/15/2020` + + // Examples (ko): + // `MMMMd`: `1월 26일` + // `yMMMMd`: `2021년 1월 26일` + // `MMMEd`: `1월 26일 (화)` + // `yMMMEd`: `2021년 1월 26일 (화)` + // `MMMMEEEEd`: `1월 26일 화요일` + // `yMMMMEEEEd`: `2021년 1월 26일 화요일` + // `MEd`: `1. 26. (화)` + // `yMEd`: `2021. 1. 26. (화)` + + static String _formatDate(BuildContext context, DateTime? date) { + final l10n = context.l10n; + if (date == null) return l10n.sectionUnknown; + if (date.isToday) return l10n.dateToday; + if (date.isYesterday) return l10n.dateYesterday; + + final locale = context.locale; + if (date.isThisYear) return '${DateFormat.MMMMd(locale).format(date)} (${DateFormat.E(locale).format(date)})'; + return '${DateFormat.yMMMMd(locale).format(date)} (${DateFormat.E(locale).format(date)})'; + } + + @override + Widget build(BuildContext context) { + return SectionHeader<T>( + sectionKey: EntryDateSectionKey(date), + title: _formatDate(context, date), + selectable: selectable, + ); + } +} + +class MonthSectionHeader<T> extends StatelessWidget { + final DateTime? date; + final bool selectable; + + const MonthSectionHeader({ + super.key, + required this.date, + required this.selectable, + }); + + static String _formatDate(BuildContext context, DateTime? date) { + final l10n = context.l10n; + if (date == null) return l10n.sectionUnknown; + if (date.isThisMonth) return l10n.dateThisMonth; + + final locale = context.locale; + final localized = date.isThisYear ? DateFormat.MMMM(locale).format(date) : DateFormat.yMMMM(locale).format(date); + return '${localized.substring(0, 1).toUpperCase()}${localized.substring(1)}'; + } + + @override + Widget build(BuildContext context) { + return SectionHeader<T>( + sectionKey: EntryDateSectionKey(date), + title: _formatDate(context, date), + selectable: selectable, + ); + } +} diff --git a/lib/widgets/collection/grid/headers/rating.dart b/lib/widgets/collection/grid/headers/rating.dart new file mode 100644 index 0000000..4cdfc3e --- /dev/null +++ b/lib/widgets/collection/grid/headers/rating.dart @@ -0,0 +1,24 @@ +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:flutter/material.dart'; + +class RatingSectionHeader<T> extends StatelessWidget { + final int rating; + final bool selectable; + + const RatingSectionHeader({ + super.key, + required this.rating, + required this.selectable, + }); + + @override + Widget build(BuildContext context) { + return SectionHeader<T>( + sectionKey: EntryRatingSectionKey(rating), + title: RatingFilter.formatRating(context, rating), + selectable: selectable, + ); + } +} diff --git a/lib/widgets/collection/grid/list_details.dart b/lib/widgets/collection/grid/list_details.dart new file mode 100644 index 0000000..0c30a73 --- /dev/null +++ b/lib/widgets/collection/grid/list_details.dart @@ -0,0 +1,109 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/collection/grid/list_details_theme.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EntryListDetails extends StatelessWidget { + final AvesEntry entry; + + const EntryListDetails({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + final detailsTheme = context.watch<EntryListDetailsThemeData>(); + + return Container( + padding: EntryListDetailsTheme.contentPadding, + foregroundDecoration: BoxDecoration( + border: Border(top: AvesBorder.straightSide(context)), + ), + margin: EntryListDetailsTheme.contentMargin, + child: IconTheme.merge( + data: detailsTheme.iconTheme, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + entry.bestTitle ?? context.l10n.viewerInfoUnknown, + style: detailsTheme.titleStyle, + softWrap: false, + overflow: detailsTheme.titleMaxLines == 1 ? TextOverflow.fade : TextOverflow.ellipsis, + maxLines: detailsTheme.titleMaxLines, + ), + const SizedBox(height: EntryListDetailsTheme.titleDetailPadding), + if (detailsTheme.showDate) _buildDateRow(context, detailsTheme.captionStyle), + if (detailsTheme.showLocation && entry.hasGps) _buildLocationRow(context, detailsTheme.captionStyle), + ], + ), + ), + ); + } + + Widget _buildRow(List<InlineSpan> spans, TextStyle style) { + return Text.rich( + TextSpan( + children: spans, + ), + style: style, + softWrap: false, + overflow: TextOverflow.fade, + ); + } + + WidgetSpan _buildIconSpan(IconData icon, {EdgeInsetsDirectional padding = EdgeInsetsDirectional.zero}) { + return WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: 8, bottom: 1) + padding, + child: Icon(icon), + ), + ); + } + + Widget _buildDateRow(BuildContext context, TextStyle style) { + final locale = context.locale; + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + final date = entry.bestDate; + final dateText = date != null ? formatDateTime(date, locale, use24hour) : AText.valueNotAvailable; + + final size = entry.stackedEntries?.map((v) => v.sizeBytes).sum ?? entry.sizeBytes; + final sizeText = size != null ? formatFileSize(locale, size) : AText.valueNotAvailable; + + return Wrap( + spacing: 8, + children: [ + _buildRow( + [_buildIconSpan(AIcons.date), TextSpan(text: dateText)], + style, + ), + _buildRow( + [_buildIconSpan(AIcons.size), TextSpan(text: sizeText)], + style, + ), + ], + ); + } + + Widget _buildLocationRow(BuildContext context, TextStyle style) { + final location = entry.hasAddress ? entry.shortAddress : settings.coordinateFormat.format(context, entry.latLng!); + + return _buildRow( + [_buildIconSpan(AIcons.location), TextSpan(text: location)], + style, + ); + } +} diff --git a/lib/widgets/collection/grid/list_details_theme.dart b/lib/widgets/collection/grid/list_details_theme.dart new file mode 100644 index 0000000..bc93023 --- /dev/null +++ b/lib/widgets/collection/grid/list_details_theme.dart @@ -0,0 +1,113 @@ +import 'package:aves/theme/format.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:provider/provider.dart'; + +class EntryListDetailsTheme extends StatelessWidget { + final double extent; + final Widget child; + + static const EdgeInsets contentMargin = EdgeInsets.symmetric(horizontal: 8); + static const EdgeInsets contentPadding = EdgeInsets.symmetric(vertical: 4); + static const double titleDetailPadding = 6; + + const EntryListDetailsTheme({ + super.key, + required this.extent, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ProxyProvider<MediaQueryData, EntryListDetailsThemeData>( + update: (context, mq, previous) { + final use24hour = mq.alwaysUse24HourFormat; + final textScaler = mq.textScaler; + + final textTheme = Theme.of(context).textTheme; + var titleStyle = textTheme.bodyMedium!; + var captionStyle = textTheme.bodySmall!; + // specify `height` for accurate paragraph height measurement + final defaultTextHeight = DefaultTextStyle.of(context).style.height; + titleStyle = titleStyle.copyWith(height: titleStyle.height ?? defaultTextHeight); + captionStyle = captionStyle.copyWith(height: captionStyle.height ?? defaultTextHeight); + + final titleLineHeightParagraph = RenderParagraph( + TextSpan( + text: 'Fake Title', + style: titleStyle, + ), + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final titleLineHeight = titleLineHeightParagraph.getMaxIntrinsicHeight(double.infinity); + titleLineHeightParagraph.dispose(); + + final captionLineHeightParagraph = RenderParagraph( + TextSpan( + text: formatDateTime(DateTime.now(), context.locale, use24hour), + style: captionStyle, + ), + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final captionLineHeight = captionLineHeightParagraph.getMaxIntrinsicHeight(double.infinity); + + var titleMaxLines = 1; + var showDate = false; + var showLocation = false; + + final gridExtentMin = context.read<TileExtentController>().effectiveExtentMin; + final isMinExtent = (extent - gridExtentMin).abs() < precisionErrorTolerance; + + var availableHeight = extent - contentMargin.vertical - contentPadding.vertical; + if (availableHeight >= titleLineHeight + titleDetailPadding + captionLineHeight) { + showDate = true; + availableHeight -= titleLineHeight + titleDetailPadding + captionLineHeight; + if (availableHeight >= captionLineHeight) { + showLocation = true; + availableHeight -= captionLineHeight; + titleMaxLines += availableHeight ~/ titleLineHeight; + } + } + + return EntryListDetailsThemeData( + extent: extent, + titleMaxLines: titleMaxLines, + isMinExtent: isMinExtent, + showDate: showDate, + showLocation: showLocation, + titleStyle: titleStyle, + captionStyle: captionStyle, + iconTheme: IconThemeData( + color: captionStyle.color, + size: textScaler.scale(captionStyle.fontSize!), + ), + ); + }, + child: child, + ); + } +} + +class EntryListDetailsThemeData { + final double extent; + final int titleMaxLines; + final bool isMinExtent, showDate, showLocation; + final TextStyle titleStyle, captionStyle; + final IconThemeData iconTheme; + + const EntryListDetailsThemeData({ + required this.extent, + required this.titleMaxLines, + required this.isMinExtent, + required this.showDate, + required this.showLocation, + required this.titleStyle, + required this.captionStyle, + required this.iconTheme, + }); +} diff --git a/lib/widgets/collection/grid/section_layout.dart b/lib/widgets/collection/grid/section_layout.dart new file mode 100644 index 0000000..1156b61 --- /dev/null +++ b/lib/widgets/collection/grid/section_layout.dart @@ -0,0 +1,51 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/collection/grid/headers/any.dart'; +import 'package:aves/widgets/common/grid/sections/provider.dart'; +import 'package:flutter/material.dart'; + +class SectionedEntryListLayoutProvider extends SectionedListLayoutProvider<AvesEntry> { + final CollectionLens collection; + final bool selectable; + + SectionedEntryListLayoutProvider({ + super.key, + required this.collection, + required this.selectable, + required super.scrollableWidth, + required super.tileLayout, + required super.columnCount, + required super.spacing, + required super.horizontalPadding, + required double tileExtent, + required super.tileBuilder, + required super.tileAnimationDelay, + required super.child, + }) : super( + tileWidth: tileExtent, + tileHeight: tileExtent, + coverRatioResolver: (item) => item.displayAspectRatio, + ); + + @override + bool get showHeaders => collection.showHeaders; + + @override + Map<SectionKey, List<AvesEntry>> get sections => collection.sections; + + @override + double getHeaderExtent(BuildContext context, SectionKey sectionKey) { + return CollectionSectionHeader.getPreferredHeight(context, scrollableWidth, collection.source, sectionKey); + } + + @override + Widget buildHeader(BuildContext context, SectionKey sectionKey, double headerExtent) { + return CollectionSectionHeader( + collection: collection, + sectionKey: sectionKey, + height: headerExtent, + selectable: selectable, + ); + } +} diff --git a/lib/widgets/collection/grid/tile.dart b/lib/widgets/collection/grid/tile.dart new file mode 100644 index 0000000..c9400c7 --- /dev/null +++ b/lib/widgets/collection/grid/tile.dart @@ -0,0 +1,144 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/intent_service.dart'; +import 'package:aves/widgets/collection/grid/list_details.dart'; +import 'package:aves/widgets/collection/grid/list_details_theme.dart'; +import 'package:aves/widgets/common/grid/scaling.dart'; +import 'package:aves/widgets/common/providers/viewer_entry_provider.dart'; +import 'package:aves/widgets/common/thumbnail/decorated.dart'; +import 'package:aves/widgets/common/thumbnail/notifications.dart'; +import 'package:aves/widgets/viewer/hero.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class InteractiveTile extends StatelessWidget { + final CollectionLens collection; + final AvesEntry entry; + final double thumbnailExtent; + final TileLayout tileLayout; + final ValueNotifier<bool>? isScrollingNotifier; + + const InteractiveTile({ + super.key, + required this.collection, + required this.entry, + required this.thumbnailExtent, + required this.tileLayout, + this.isScrollingNotifier, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: () { + final appMode = context.read<ValueNotifier<AppMode>>().value; + switch (appMode) { + case AppMode.main: + final selection = context.read<Selection<AvesEntry>>(); + if (selection.isSelecting) { + selection.toggleSelection(entry); + } else { + OpenViewerNotification(entry).dispatch(context); + } + case AppMode.pickSingleMediaExternal: + IntentService.submitPickedItems([entry.uri]); + case AppMode.pickMultipleMediaExternal: + final selection = context.read<Selection<AvesEntry>>(); + selection.toggleSelection(entry); + case AppMode.pickFilteredMediaInternal: + case AppMode.pickUnfilteredMediaInternal: + Navigator.maybeOf(context)?.pop(entry); + default: + break; + } + }, + child: MetaData( + metaData: ScalerMetadata(entry), + child: Tile( + entry: entry, + thumbnailExtent: thumbnailExtent, + tileLayout: tileLayout, + selectable: true, + highlightable: true, + isScrollingNotifier: isScrollingNotifier, + heroTagger: () => EntryHeroInfo(collection, entry).tag, + ), + ), + ); + } +} + +class Tile extends StatelessWidget { + final AvesEntry entry; + final double thumbnailExtent; + final TileLayout tileLayout; + final bool selectable, highlightable; + final ValueNotifier<bool>? isScrollingNotifier; + final Object? Function()? heroTagger; + + const Tile({ + super.key, + required this.entry, + required this.thumbnailExtent, + required this.tileLayout, + this.selectable = false, + this.highlightable = false, + this.isScrollingNotifier, + this.heroTagger, + }); + + @override + Widget build(BuildContext context) { + switch (tileLayout) { + case TileLayout.mosaic: + case TileLayout.grid: + return _buildThumbnail(); + case TileLayout.list: + return Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox.square( + dimension: context.select<EntryListDetailsThemeData, double>((v) => v.extent), + child: _buildThumbnail(), + ), + Expanded( + child: EntryListDetails( + entry: entry, + ), + ), + ], + ); + } + } + + Widget _buildThumbnail() => DecoratedThumbnail( + entry: entry, + tileExtent: thumbnailExtent, + isMosaic: tileLayout == TileLayout.mosaic, + // when the user is scrolling faster than we can retrieve the thumbnails, + // the retrieval task queue can pile up for thumbnails that got disposed + // in this case we pause the image retrieval task to get it out of the queue + cancellableNotifier: isScrollingNotifier, + selectable: selectable, + highlightable: highlightable, + heroTagger: heroTagger, + // do not use a hero placeholder but hide the thumbnail matching the viewer entry, + // so that it can hero out on an entry and come back with a hero to a different entry + heroPlaceholderBuilder: (context, heroSize, child) => child, + imageDecorator: (context, child) { + return Selector<ViewerEntryNotifier, bool>( + selector: (context, v) => v.value == entry, + builder: (context, isViewerEntry, child) { + return Visibility.maintain( + visible: !isViewerEntry, + child: child!, + ); + }, + child: child, + ); + }, + ); +} diff --git a/lib/widgets/collection/loading.dart b/lib/widgets/collection/loading.dart new file mode 100644 index 0000000..390752e --- /dev/null +++ b/lib/widgets/collection/loading.dart @@ -0,0 +1,50 @@ +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/events.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class LoadingEmptyContent extends StatelessWidget { + final CollectionSource source; + + const LoadingEmptyContent({ + super.key, + required this.source, + }); + + @override + Widget build(BuildContext context) { + final countFormatter = NumberFormat.decimalPattern(context.locale); + final progressTextStyle = TextStyle( + color: Theme.of(context).colorScheme.primary.withValues(alpha: .5), + fontSize: 18, + ); + + return EmptyContent( + text: context.l10n.sourceStateLoading, + bottom: Padding( + padding: const EdgeInsets.only(top: 16), + child: Stack( + alignment: Alignment.center, + children: [ + const ReportProgressIndicator(), + ValueListenableBuilder<ProgressEvent>( + valueListenable: source.progressNotifier, + builder: (context, progress, snapshot) { + final done = progress.done; + return done > 0 + ? Text( + countFormatter.format(done), + style: progressTextStyle, + ) + : const SizedBox(); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/collection/query_bar.dart b/lib/widgets/collection/query_bar.dart new file mode 100644 index 0000000..cc50804 --- /dev/null +++ b/lib/widgets/collection/query_bar.dart @@ -0,0 +1,75 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/common/basic/query_bar.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EntryQueryBar extends StatefulWidget { + final ValueNotifier<String> queryNotifier; + final FocusNode focusNode; + + const EntryQueryBar({ + super.key, + required this.queryNotifier, + required this.focusNode, + }); + + @override + State<EntryQueryBar> createState() => _EntryQueryBarState(); + + static double getPreferredHeight(TextScaler textScaler) => QueryBar.getPreferredHeight(textScaler); +} + +class _EntryQueryBarState extends State<EntryQueryBar> { + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant EntryQueryBar oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(EntryQueryBar widget) { + widget.queryNotifier.addListener(_onQueryChanged); + } + + void _unregisterWidget(EntryQueryBar widget) { + widget.queryNotifier.removeListener(_onQueryChanged); + } + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return Container( + height: EntryQueryBar.getPreferredHeight(textScaler), + alignment: Alignment.topCenter, + child: Selector<Selection<AvesEntry>, bool>( + selector: (context, selection) => !selection.isSelecting, + builder: (context, editable, child) => QueryBar( + queryNotifier: widget.queryNotifier, + focusNode: widget.focusNode, + hintText: context.l10n.collectionSearchTitlesHintText, + editable: editable, + ), + ), + ); + } + + void _onQueryChanged() { + final query = widget.queryNotifier.value; + context.read<CollectionLens>().setLiveQuery(query); + } +} |
