aboutsummaryrefslogtreecommitdiff
path: root/lib/widgets/common/grid
diff options
context:
space:
mode:
Diffstat (limited to 'lib/widgets/common/grid')
-rw-r--r--lib/widgets/common/grid/draggable_thumb_label.dart88
-rw-r--r--lib/widgets/common/grid/header.dart289
-rw-r--r--lib/widgets/common/grid/item_tracker.dart170
-rw-r--r--lib/widgets/common/grid/overlay.dart58
-rw-r--r--lib/widgets/common/grid/scaling.dart248
-rw-r--r--lib/widgets/common/grid/sections/fixed/list_layout.dart62
-rw-r--r--lib/widgets/common/grid/sections/fixed/row.dart162
-rw-r--r--lib/widgets/common/grid/sections/fixed/scale_grid.dart111
-rw-r--r--lib/widgets/common/grid/sections/fixed/scale_overlay.dart136
-rw-r--r--lib/widgets/common/grid/sections/fixed/section_layout.dart41
-rw-r--r--lib/widgets/common/grid/sections/fixed/section_layout_builder.dart109
-rw-r--r--lib/widgets/common/grid/sections/list_layout.dart28
-rw-r--r--lib/widgets/common/grid/sections/mosaic/list_layout.dart78
-rw-r--r--lib/widgets/common/grid/sections/mosaic/row.dart159
-rw-r--r--lib/widgets/common/grid/sections/mosaic/scale_grid.dart74
-rw-r--r--lib/widgets/common/grid/sections/mosaic/scale_overlay.dart117
-rw-r--r--lib/widgets/common/grid/sections/mosaic/section_layout.dart61
-rw-r--r--lib/widgets/common/grid/sections/mosaic/section_layout_builder.dart198
-rw-r--r--lib/widgets/common/grid/sections/provider.dart105
-rw-r--r--lib/widgets/common/grid/sections/section_layout.dart37
-rw-r--r--lib/widgets/common/grid/sections/section_layout_builder.dart105
-rw-r--r--lib/widgets/common/grid/selector.dart244
-rw-r--r--lib/widgets/common/grid/sliver.dart264
-rw-r--r--lib/widgets/common/grid/theme.dart111
24 files changed, 3055 insertions, 0 deletions
diff --git a/lib/widgets/common/grid/draggable_thumb_label.dart b/lib/widgets/common/grid/draggable_thumb_label.dart
new file mode 100644
index 0000000..0645597
--- /dev/null
+++ b/lib/widgets/common/grid/draggable_thumb_label.dart
@@ -0,0 +1,88 @@
+import 'package:aves/theme/format.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:flutter/material.dart';
+import 'package:intl/intl.dart';
+import 'package:provider/provider.dart';
+
+class DraggableCrumbLabel extends StatelessWidget {
+ final String label;
+
+ const DraggableCrumbLabel({
+ super.key,
+ required this.label,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: _crumbLabelMaxWidth),
+ child: Padding(
+ padding: _padding,
+ child: _buildText(label, isCrumb: true),
+ ),
+ );
+ }
+}
+
+class DraggableThumbLabel<T> extends StatelessWidget {
+ final double offsetY;
+ final List<String> Function(BuildContext context, T item) lineBuilder;
+
+ const DraggableThumbLabel({
+ super.key,
+ required this.offsetY,
+ required this.lineBuilder,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final sll = context.read<SectionedListLayout<T>>();
+ final sectionLayout = sll.getSectionAt(offsetY);
+ if (sectionLayout == null) return const SizedBox();
+
+ final item = sll.getItemAt(Offset(0, offsetY)) ?? sll.sections[sectionLayout.sectionKey]!.first;
+
+ final lines = lineBuilder(context, item);
+ if (lines.isEmpty) return const SizedBox();
+
+ return ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: _thumbLabelMaxWidth),
+ child: Padding(
+ padding: _padding,
+ child: lines.length > 1
+ ? Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: lines.map((v) => _buildText(v, isCrumb: false)).toList(),
+ )
+ : _buildText(lines.first, isCrumb: false),
+ ),
+ );
+ }
+
+ static String formatMonthThumbLabel(BuildContext context, DateTime? date) {
+ if (date == null) return context.l10n.sectionUnknown;
+ return DateFormat.yMMM(context.locale).format(date);
+ }
+
+ static String formatDayThumbLabel(BuildContext context, DateTime? date) {
+ if (date == null) return context.l10n.sectionUnknown;
+ return formatDay(date, context.locale);
+ }
+}
+
+const double _crumbLabelMaxWidth = 96;
+const double _thumbLabelMaxWidth = 144;
+const EdgeInsets _padding = EdgeInsets.symmetric(vertical: 4, horizontal: 8);
+
+Widget _buildText(String text, {required bool isCrumb}) => Text(
+ text,
+ style: TextStyle(
+ color: Colors.black,
+ fontSize: isCrumb ? 10 : 14,
+ ),
+ softWrap: false,
+ overflow: TextOverflow.fade,
+ maxLines: 1,
+ );
diff --git a/lib/widgets/common/grid/header.dart b/lib/widgets/common/grid/header.dart
new file mode 100644
index 0000000..ed70d0e
--- /dev/null
+++ b/lib/widgets/common/grid/header.dart
@@ -0,0 +1,289 @@
+import 'package:aves/model/selection.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/model/source/section_keys.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/theme/icons.dart';
+import 'package:aves/theme/styles.dart';
+import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:provider/provider.dart';
+
+class SectionHeader<T> extends StatelessWidget {
+ final SectionKey sectionKey;
+ final Widget? leading, trailing;
+ final String title;
+ final bool selectable;
+
+ const SectionHeader({
+ super.key,
+ required this.sectionKey,
+ this.leading,
+ required this.title,
+ this.trailing,
+ this.selectable = true,
+ });
+
+ static const leadingSize = Size.square(32);
+ static const widgetSpanAlignmentMargin = EdgeInsetsDirectional.only(bottom: 4);
+ static final leadingMargin = const EdgeInsetsDirectional.only(end: 8) + widgetSpanAlignmentMargin;
+ static final trailingMargin = const EdgeInsetsDirectional.only(start: 8) + widgetSpanAlignmentMargin;
+ static const margin = EdgeInsets.symmetric(vertical: 0, horizontal: 8);
+ static const padding = EdgeInsets.symmetric(vertical: 16, horizontal: 8);
+ static const widgetSpanAlignment = PlaceholderAlignment.middle;
+
+ @override
+ Widget build(BuildContext context) {
+ final onTap = selectable ? () => _toggleSectionSelection(context) : null;
+
+ final theme = Theme.of(context);
+
+ Widget child = Container(
+ padding: padding,
+ constraints: BoxConstraints(minHeight: leadingSize.height),
+ child: AGestureDetector(
+ onTap: onTap,
+ onLongPress: selectable
+ ? Feedback.wrapForLongPress(() {
+ final selection = context.read<Selection<T>>();
+ if (selection.isSelecting) {
+ _toggleSectionSelection(context);
+ } else {
+ selection.select();
+ selection.addToSelection(_getSectionEntries(context));
+ }
+ }, context)
+ : null,
+ longPressTimeout: settings.longPressTimeout,
+ child: Text.rich(
+ TextSpan(
+ children: [
+ WidgetSpan(
+ alignment: widgetSpanAlignment,
+ child: Theme(
+ data: theme.copyWith(
+ iconTheme: theme.iconTheme.copyWith(
+ color: theme.colorScheme.onSurface,
+ ),
+ ),
+ child: _SectionSelectableLeading<T>(
+ selectable: selectable,
+ sectionKey: sectionKey,
+ browsingBuilder: leading != null
+ ? (context) => Container(
+ width: leadingSize.width,
+ height: leadingSize.height,
+ margin: leadingMargin,
+ child: leading,
+ )
+ : null,
+ onPressed: onTap,
+ ),
+ ),
+ ),
+ TextSpan(
+ text: title,
+ style: _headerTextStyle(context),
+ ),
+ if (trailing != null)
+ WidgetSpan(
+ alignment: widgetSpanAlignment,
+ child: Container(
+ margin: trailingMargin,
+ child: trailing,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ if (settings.useTvLayout) {
+ // prevent ink response when tapping the header does nothing,
+ // because otherwise Play Store reviewers think it is broken navigation
+ child = context.select<Selection<T>, bool>((v) => v.isSelecting)
+ ? InkWell(
+ onTap: onTap,
+ borderRadius: const BorderRadius.all(Radius.circular(123)),
+ child: child,
+ )
+ : Focus(child: child);
+ }
+ return Container(
+ alignment: AlignmentDirectional.centerStart,
+ margin: margin,
+ child: child,
+ );
+ }
+
+ List<T> _getSectionEntries(BuildContext context) => context.read<SectionedListLayout<T>>().sections[sectionKey] ?? [];
+
+ void _toggleSectionSelection(BuildContext context) {
+ final sectionEntries = _getSectionEntries(context);
+ final selection = context.read<Selection<T>>();
+ final isSelected = selection.isSelected(sectionEntries);
+ if (isSelected) {
+ selection.removeFromSelection(sectionEntries);
+ } else {
+ selection.addToSelection(sectionEntries);
+ }
+ }
+
+ // TODO TLAD [perf] cache header extent computation?
+ static double getPreferredHeight({
+ required BuildContext context,
+ required double maxWidth,
+ required String title,
+ bool hasLeading = false,
+ bool hasTrailing = false,
+ }) {
+ final textScaler = MediaQuery.textScalerOf(context);
+ final leadingFontSize = leadingSize.height;
+ final textScaleFactor = textScaler.scale(leadingFontSize) / leadingFontSize;
+ final maxContentWidth = maxWidth - (SectionHeader.padding.horizontal + SectionHeader.margin.horizontal);
+ final paragraph = RenderParagraph(
+ TextSpan(
+ children: [
+ // as of Flutter v3.7.7, `RenderParagraph` fails to lay out `WidgetSpan` offscreen
+ // so we use a hair space times a magic number to match width
+ TextSpan(
+ // 23 hair spaces match a width of 40.0
+ text: '\u200A' * (hasLeading ? 23 : 1),
+ // force a higher first line to match leading icon/selector dimension
+ style: TextStyle(height: 2.3 * textScaleFactor),
+ ),
+ if (hasTrailing) TextSpan(text: '\u200A' * 17),
+ TextSpan(
+ text: title,
+ style: _headerTextStyle(context),
+ ),
+ ],
+ ),
+ textDirection: TextDirection.ltr,
+ textScaler: textScaler,
+ )..layout(BoxConstraints(maxWidth: maxContentWidth), parentUsesSize: true);
+ final height = paragraph.getMaxIntrinsicHeight(maxContentWidth);
+ paragraph.dispose();
+ return height;
+ }
+
+ static TextStyle _headerTextStyle(BuildContext context) {
+ // specify `height` for accurate paragraph height measurement
+ final defaultTextHeight = DefaultTextStyle.of(context).style.height;
+ return AStyles.unknownTitleText.copyWith(height: defaultTextHeight);
+ }
+}
+
+class _SectionSelectableLeading<T> extends StatelessWidget {
+ final bool selectable;
+ final SectionKey sectionKey;
+ final WidgetBuilder? browsingBuilder;
+ final VoidCallback? onPressed;
+
+ const _SectionSelectableLeading({
+ super.key,
+ this.selectable = true,
+ required this.sectionKey,
+ required this.browsingBuilder,
+ required this.onPressed,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ if (!selectable) return _buildBrowsing(context);
+
+ final duration = context.select<DurationsData, Duration>((v) => v.formTransition);
+ final isSelecting = context.select<Selection<T>, bool>((selection) => selection.isSelecting);
+ final Widget child = isSelecting
+ ? _SectionSelectingLeading<T>(
+ sectionKey: sectionKey,
+ onPressed: onPressed,
+ )
+ : _buildBrowsing(context);
+
+ return FocusTraversalGroup(
+ descendantsAreFocusable: false,
+ descendantsAreTraversable: false,
+ child: AnimatedSwitcher(
+ duration: duration,
+ switchInCurve: Curves.easeInOut,
+ switchOutCurve: Curves.easeInOut,
+ transitionBuilder: (child, animation) {
+ Widget transition = ScaleTransition(
+ scale: animation,
+ child: child,
+ );
+ if (browsingBuilder == null) {
+ // when switching with a header that has no icon,
+ // we also transition the size for a smooth push to the text
+ transition = SizeTransition(
+ axis: Axis.horizontal,
+ sizeFactor: animation,
+ child: transition,
+ );
+ }
+ return transition;
+ },
+ child: child,
+ ),
+ );
+ }
+
+ Widget _buildBrowsing(BuildContext context) => browsingBuilder?.call(context) ?? SizedBox(height: SectionHeader.leadingSize.height + SectionHeader.widgetSpanAlignmentMargin.vertical);
+}
+
+class _SectionSelectingLeading<T> extends StatelessWidget {
+ final SectionKey sectionKey;
+ final VoidCallback? onPressed;
+
+ const _SectionSelectingLeading({
+ super.key,
+ required this.sectionKey,
+ required this.onPressed,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final duration = context.select<DurationsData, Duration>((v) => v.formTransition);
+ final sectionEntries = context.watch<SectionedListLayout<T>>().sections[sectionKey] ?? [];
+ final selection = context.watch<Selection<T>>();
+ final isSelected = selection.isSelected(sectionEntries);
+ return AnimatedSwitcher(
+ duration: duration,
+ switchInCurve: Curves.easeOutBack,
+ switchOutCurve: Curves.easeOutBack,
+ transitionBuilder: (child, animation) => ScaleTransition(
+ scale: animation,
+ child: child,
+ ),
+ child: TooltipTheme(
+ key: ValueKey(isSelected),
+ data: TooltipTheme.of(context).copyWith(
+ preferBelow: false,
+ ),
+ child: Container(
+ width: SectionHeader.leadingSize.width,
+ height: SectionHeader.leadingSize.height,
+ margin: SectionHeader.leadingMargin,
+ child: Theme(
+ data: Theme.of(context).copyWith(
+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ child: IconButton(
+ iconSize: 26,
+ onPressed: onPressed,
+ tooltip: isSelected ? context.l10n.collectionDeselectSectionTooltip : context.l10n.collectionSelectSectionTooltip,
+ style: ButtonStyle(
+ padding: WidgetStateProperty.all<EdgeInsetsGeometry>(EdgeInsets.zero),
+ minimumSize: WidgetStateProperty.all<Size>(SectionHeader.leadingSize),
+ ),
+ icon: Icon(isSelected ? AIcons.selected : AIcons.unselected),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/common/grid/item_tracker.dart b/lib/widgets/common/grid/item_tracker.dart
new file mode 100644
index 0000000..ea8aadf
--- /dev/null
+++ b/lib/widgets/common/grid/item_tracker.dart
@@ -0,0 +1,170 @@
+import 'dart:async';
+import 'dart:math';
+
+import 'package:aves/model/highlight.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+class GridItemTracker<T> extends StatefulWidget {
+ final GlobalKey scrollableKey;
+ final ValueNotifier<double> appBarHeightNotifier;
+ final TileLayout tileLayout;
+ final ScrollController scrollController;
+ final Widget child;
+
+ const GridItemTracker({
+ super.key,
+ required this.scrollableKey,
+ required this.appBarHeightNotifier,
+ required this.tileLayout,
+ required this.scrollController,
+ required this.child,
+ });
+
+ @override
+ State<GridItemTracker<T>> createState() => _GridItemTrackerState<T>();
+}
+
+class _GridItemTrackerState<T> extends State<GridItemTracker<T>> with WidgetsBindingObserver {
+ ValueNotifier<double> get appBarHeightNotifier => widget.appBarHeightNotifier;
+
+ ScrollController get scrollController => widget.scrollController;
+
+ @override
+ Widget build(BuildContext context) {
+ return widget.child;
+ }
+
+ Size get scrollableSize {
+ final scrollableContext = widget.scrollableKey.currentContext!;
+ return (scrollableContext.findRenderObject() as RenderBox).size;
+ }
+
+ final Set<StreamSubscription> _subscriptions = {};
+
+ // grid section metrics before the app is laid out with the new orientation
+ late SectionedListLayout<T> _lastSectionedListLayout;
+ late Size _lastScrollableSize;
+ Orientation _lastOrientation = Orientation.portrait;
+
+ @override
+ void initState() {
+ super.initState();
+ final highlightInfo = context.read<HighlightInfo>();
+ _subscriptions.add(highlightInfo.eventBus.on<TrackEvent<T>>().listen(_trackItem));
+ WidgetsBinding.instance.addObserver(this);
+ _saveLayoutMetrics();
+ }
+
+ @override
+ void didUpdateWidget(covariant GridItemTracker<T> oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.tileLayout != widget.tileLayout) {
+ _onLayoutChanged();
+ }
+ _saveLayoutMetrics();
+ }
+
+ @override
+ void didChangeMetrics() {
+ // the order of `WidgetsBindingObserver` metrics change notification is unreliable
+ // w.r.t. the `View` update, and consequentially to this widget update:
+ // `WidgetsBindingObserver` is notified mostly before, sometimes after, the widget update
+ final size = View.of(context).physicalSize;
+ final orientation = size.width > size.height ? Orientation.landscape : Orientation.portrait;
+ if (_lastOrientation != orientation) {
+ _lastOrientation = orientation;
+ _onLayoutChanged();
+ _saveLayoutMetrics();
+ }
+ }
+
+ @override
+ void dispose() {
+ WidgetsBinding.instance.removeObserver(this);
+ _subscriptions
+ ..forEach((sub) => sub.cancel())
+ ..clear();
+ super.dispose();
+ }
+
+ // about scrolling & offset retrieval:
+ // `Scrollable.ensureVisible` only works on already rendered objects
+ // `RenderViewport.showOnScreen` can find any `RenderSliver`, but not always a `RenderMetadata`
+ // `RenderViewport.scrollOffsetOf` is a good alternative
+ Future<void> _trackItem(TrackEvent event) async {
+ final sectionedListLayout = context.read<SectionedListLayout<T>>();
+ final tileRect = sectionedListLayout.getTileRect(event.item);
+ if (tileRect == null) return;
+
+ final viewportRect = Offset(0, scrollController.offset) & scrollableSize;
+ final itemVisibility = max(0, tileRect.intersect(viewportRect).height) / tileRect.height;
+ if (!event.predicate(itemVisibility)) return;
+
+ double scrollOffset = tileRect.top + (tileRect.height - scrollableSize.height) * ((event.alignment.y + 1) / 2);
+ // most of the time the app bar will be scrolled away after scaling,
+ // so we compensate for it to center the focal point thumbnail
+ scrollOffset += appBarHeightNotifier.value;
+ scrollOffset = scrollOffset.clamp(0, scrollController.position.maxScrollExtent);
+
+ if (scrollOffset > 0) {
+ if (event.animate) {
+ await scrollController.animateTo(
+ scrollOffset,
+ duration: Duration(milliseconds: (scrollOffset / 2).round().clamp(ADurations.highlightScrollAnimationMinMillis, ADurations.highlightScrollAnimationMaxMillis)),
+ curve: Curves.easeInOutCubic,
+ );
+ } else {
+ scrollController.jumpTo(scrollOffset);
+ await Future.delayed(ADurations.highlightJumpDelay);
+ }
+ }
+
+ final highlightItem = event.highlightItem;
+ if (highlightItem != null) {
+ context.read<HighlightInfo>().set(highlightItem);
+ }
+ }
+
+ Future<void> _saveLayoutMetrics() async {
+ // use a delay to obtain current layout metrics
+ // so that we can handle window orientation change with the previous metrics,
+ // regardless of the `View`/`WidgetsBindingObserver` order uncertainty
+ await Future.delayed(const Duration(milliseconds: 500));
+ if (!mounted) return;
+ _lastSectionedListLayout = context.read<SectionedListLayout<T>>();
+ _lastScrollableSize = scrollableSize;
+ }
+
+ void _onLayoutChanged() {
+ if (scrollController.positions.length != 1) return;
+
+ // do not track when view shows top edge
+ if (scrollController.offset == 0) return;
+
+ final layout = _lastSectionedListLayout;
+ final halfSize = _lastScrollableSize / 2;
+ final center = Offset(
+ halfSize.width,
+ halfSize.height + scrollController.offset - appBarHeightNotifier.value,
+ );
+ var pivotItem = layout.getItemAt(center) ?? layout.getItemAt(Offset(0, center.dy));
+ if (pivotItem == null) {
+ final pivotSectionKey = layout.getSectionAt(center.dy)?.sectionKey;
+ if (pivotSectionKey != null) {
+ pivotItem = layout.sections[pivotSectionKey]?.firstOrNull;
+ }
+ }
+
+ if (pivotItem != null) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ context.read<HighlightInfo>().trackItem(pivotItem, animate: false);
+ });
+ }
+ }
+}
diff --git a/lib/widgets/common/grid/overlay.dart b/lib/widgets/common/grid/overlay.dart
new file mode 100644
index 0000000..8d0149d
--- /dev/null
+++ b/lib/widgets/common/grid/overlay.dart
@@ -0,0 +1,58 @@
+import 'package:aves/model/selection.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/theme/icons.dart';
+import 'package:aves/widgets/common/identity/aves_icons.dart';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+class GridItemSelectionOverlay<T> extends StatelessWidget {
+ final T item;
+ final BorderRadius? borderRadius;
+ final EdgeInsets? padding;
+
+ const GridItemSelectionOverlay({
+ super.key,
+ required this.item,
+ this.borderRadius,
+ this.padding,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final duration = context.select<DurationsData, Duration>((v) => v.formTransition);
+ final isSelecting = context.select<Selection<T>, bool>((selection) => selection.isSelecting);
+ return AnimatedSwitcher(
+ duration: duration,
+ child: isSelecting
+ ? Selector<Selection<T>, bool>(
+ selector: (context, selection) => selection.isSelected({item}),
+ builder: (context, isSelected, child) {
+ return AnimatedContainer(
+ alignment: AlignmentDirectional.topEnd,
+ padding: padding,
+ decoration: BoxDecoration(
+ color: isSelected ? Theme.of(context).colorScheme.primary.withValues(alpha: .6) : Colors.transparent,
+ borderRadius: borderRadius,
+ ),
+ duration: duration,
+ child: AnimatedSwitcher(
+ duration: duration,
+ switchInCurve: Curves.easeOutBack,
+ switchOutCurve: Curves.easeOutBack,
+ transitionBuilder: (child, animation) => ScaleTransition(
+ scale: animation,
+ child: child,
+ ),
+ child: OverlayIcon(
+ key: ValueKey(isSelected),
+ icon: isSelected ? AIcons.selected : AIcons.unselected,
+ margin: EdgeInsets.zero,
+ ),
+ ),
+ );
+ },
+ )
+ : const SizedBox(),
+ );
+ }
+}
diff --git a/lib/widgets/common/grid/scaling.dart b/lib/widgets/common/grid/scaling.dart
new file mode 100644
index 0000000..fe29b4b
--- /dev/null
+++ b/lib/widgets/common/grid/scaling.dart
@@ -0,0 +1,248 @@
+import 'package:aves/model/highlight.dart';
+import 'package:aves/widgets/common/behaviour/eager_scale_gesture_recognizer.dart';
+import 'package:aves/widgets/common/grid/sections/fixed/scale_overlay.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/scale_overlay.dart';
+import 'package:aves/widgets/common/grid/sections/section_layout_builder.dart';
+import 'package:aves/widgets/common/grid/theme.dart';
+import 'package:aves/widgets/common/providers/tile_extent_controller_provider.dart';
+import 'package:aves/widgets/common/tile_extent_controller.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:provider/provider.dart';
+
+// metadata to identify entry from RenderObject hit test during collection scaling
+class ScalerMetadata<T> {
+ final T item;
+
+ const ScalerMetadata(this.item);
+}
+
+class GridScaleGestureDetector<T> extends StatefulWidget {
+ final GlobalKey scrollableKey;
+ final TileLayout tileLayout;
+ final double Function(double width) heightForWidth;
+ final Widget Function(Offset center, Size tileSize, Widget child) gridBuilder;
+ final TileBuilder<T> scaledItemBuilder;
+ final MosaicItemBuilder mosaicItemBuilder;
+ final Object Function(T item)? highlightItem;
+ final Widget child;
+
+ const GridScaleGestureDetector({
+ super.key,
+ required this.scrollableKey,
+ required this.tileLayout,
+ required this.heightForWidth,
+ required this.gridBuilder,
+ required this.scaledItemBuilder,
+ required this.mosaicItemBuilder,
+ this.highlightItem,
+ required this.child,
+ });
+
+ @override
+ State<GridScaleGestureDetector<T>> createState() => _GridScaleGestureDetectorState<T>();
+}
+
+class _GridScaleGestureDetectorState<T> extends State<GridScaleGestureDetector<T>> {
+ Size? _startSize;
+ double? _extentMin, _extentMax;
+ bool _applyingScale = false;
+ ValueNotifier<Size>? _scaledSizeNotifier;
+ OverlayEntry? _overlayEntry;
+ ScalerMetadata<T>? _metadata;
+
+ TileLayout get tileLayout => widget.tileLayout;
+
+ @override
+ void dispose() {
+ _scaledSizeNotifier?.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final gestureSettings = MediaQuery.gestureSettingsOf(context);
+
+ final child = GestureDetector(
+ // Horizontal/vertical drag gestures are interpreted as scaling
+ // if they are not handled by `onHorizontalDragStart`/`onVerticalDragStart`
+ // at the scaling `GestureDetector` level, or handled beforehand down the widget tree.
+ // Setting `onHorizontalDragStart`, `onVerticalDragStart`, and `onScaleStart`
+ // all at once is not allowed, so we use another `GestureDetector` for that.
+ onVerticalDragStart: (details) {},
+ onHorizontalDragStart: (details) {},
+ child: widget.child,
+ );
+
+ // as of Flutter v2.5.3, `ScaleGestureRecognizer` does not work well
+ // when combined with the `VerticalDragGestureRecognizer` inside a `GridView`,
+ // so it is modified to eagerly accept the gesture
+ // when multiple pointers are involved, and take priority over drag gestures.
+ return RawGestureDetector(
+ gestures: <Type, GestureRecognizerFactory>{
+ EagerScaleGestureRecognizer: GestureRecognizerFactoryWithHandlers<EagerScaleGestureRecognizer>(
+ () => EagerScaleGestureRecognizer(debugOwner: this),
+ (instance) {
+ instance
+ ..onStart = _onScaleStart
+ ..onUpdate = _onScaleUpdate
+ ..onEnd = _onScaleEnd
+ ..dragStartBehavior = DragStartBehavior.start
+ ..gestureSettings = gestureSettings;
+ },
+ ),
+ },
+ child: child,
+ );
+ }
+
+ void _onScaleStart(ScaleStartDetails details) {
+ // the gesture detector wrongly detects a new scaling gesture
+ // when scaling ends and we apply the new extent, so we prevent this
+ // until we scaled and scrolled to the tile in the new grid
+ if (_applyingScale) return;
+
+ final tileExtentController = context.read<TileExtentController>();
+
+ final scrollableContext = widget.scrollableKey.currentContext!;
+ final scrollableBox = scrollableContext.findRenderObject() as RenderBox;
+ final renderMetaData = _getClosestRenderMetadata(
+ box: scrollableBox,
+ localFocalPoint: details.localFocalPoint,
+ spacing: tileExtentController.spacing,
+ );
+ // abort if we cannot find an image to show on overlay
+ if (renderMetaData == null) return;
+ final metadata = renderMetaData.metaData;
+ if (metadata is! ScalerMetadata<T>) return;
+ _metadata = metadata;
+
+ switch (tileLayout) {
+ case TileLayout.mosaic:
+ _startSize = Size.square(tileExtentController.extentNotifier.value);
+ case TileLayout.grid:
+ case TileLayout.list:
+ _startSize = renderMetaData.size;
+ }
+ _scaledSizeNotifier = ValueNotifier(_startSize!);
+
+ // not the same as `MediaQuery` metrics, because of screen insets/padding
+ final scrollViewRect = scrollableBox.localToGlobal(Offset.zero) & scrollableBox.size;
+ final contentRect = scrollViewRect.deflate(tileExtentController.horizontalPadding);
+
+ _extentMin = tileExtentController.effectiveExtentMin;
+ _extentMax = tileExtentController.effectiveExtentMax;
+
+ final halfSize = _startSize! / 2;
+ switch (tileLayout) {
+ case TileLayout.mosaic:
+ _overlayEntry = OverlayEntry(
+ builder: (context) => MosaicScaleOverlay(
+ contentRect: contentRect,
+ spacing: tileExtentController.spacing,
+ extentMax: _extentMax!,
+ scaledSizeNotifier: _scaledSizeNotifier!,
+ itemBuilder: widget.mosaicItemBuilder,
+ ),
+ );
+ case TileLayout.grid:
+ case TileLayout.list:
+ final tileCenter = renderMetaData.localToGlobal(Offset(halfSize.width, halfSize.height));
+ _overlayEntry = OverlayEntry(
+ builder: (context) => TileExtentControllerProvider(
+ controller: tileExtentController,
+ child: FixedExtentScaleOverlay(
+ tileLayout: tileLayout,
+ tileCenter: tileCenter,
+ contentRect: contentRect,
+ scaledSizeNotifier: _scaledSizeNotifier!,
+ gridBuilder: widget.gridBuilder,
+ builder: (scaledTileSize) => SizedBox.fromSize(
+ size: scaledTileSize,
+ child: GridTheme(
+ extent: tileLayout == TileLayout.grid ? scaledTileSize.width : scaledTileSize.height,
+ child: widget.scaledItemBuilder(_metadata!.item, scaledTileSize),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+ Overlay.of(scrollableContext).insert(_overlayEntry!);
+ }
+
+ void _onScaleUpdate(ScaleUpdateDetails details) {
+ if (_scaledSizeNotifier == null) return;
+
+ final s = details.scale;
+ switch (tileLayout) {
+ case TileLayout.mosaic:
+ case TileLayout.grid:
+ final scaledWidth = (_startSize!.width * s).clamp(_extentMin!, _extentMax!);
+ _scaledSizeNotifier!.value = Size(scaledWidth, widget.heightForWidth(scaledWidth));
+ case TileLayout.list:
+ final scaledHeight = (_startSize!.height * s).clamp(_extentMin!, _extentMax!);
+ _scaledSizeNotifier!.value = Size(_startSize!.width, scaledHeight);
+ }
+ }
+
+ void _onScaleEnd(ScaleEndDetails details) {
+ if (_scaledSizeNotifier == null) return;
+
+ final scaledSize = _scaledSizeNotifier!.value;
+ _scaledSizeNotifier!.dispose();
+ _scaledSizeNotifier = null;
+
+ _overlayEntry
+ ?..remove()
+ ..dispose();
+ _overlayEntry = null;
+
+ _applyingScale = true;
+ final tileExtentController = context.read<TileExtentController>();
+ final oldExtent = tileExtentController.extentNotifier.value;
+ // sanitize and update grid layout if necessary
+ late final double preferredExtent;
+ switch (tileLayout) {
+ case TileLayout.mosaic:
+ case TileLayout.grid:
+ preferredExtent = scaledSize.width;
+ case TileLayout.list:
+ preferredExtent = scaledSize.height;
+ }
+ final newExtent = tileExtentController.setUserPreferredExtent(preferredExtent);
+ if (newExtent == oldExtent) {
+ _applyingScale = false;
+ } else {
+ // scroll to show the focal point thumbnail at its new position
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ final trackItem = _metadata!.item;
+ final highlightItem = widget.highlightItem?.call(trackItem) ?? trackItem;
+ context.read<HighlightInfo>().trackItem(trackItem, animate: false, highlightItem: highlightItem);
+ _applyingScale = false;
+ });
+ }
+ }
+
+ RenderMetaData? _getClosestRenderMetadata({
+ required RenderBox box,
+ required Offset localFocalPoint,
+ required double spacing,
+ }) {
+ var position = localFocalPoint;
+ while (position.dx > 0 && position.dy > 0) {
+ final result = BoxHitTestResult();
+ box.hitTest(result, position: position);
+
+ // find `RenderObject`s at the gesture focal point
+ U? firstOf<U>(BoxHitTestResult result) => result.path.firstWhereOrNull((el) => el.target is U)?.target as U?;
+ final renderMetaData = firstOf<RenderMetaData>(result);
+ if (renderMetaData != null) return renderMetaData;
+ position = position.translate(-spacing, -spacing);
+ }
+ return null;
+ }
+}
diff --git a/lib/widgets/common/grid/sections/fixed/list_layout.dart b/lib/widgets/common/grid/sections/fixed/list_layout.dart
new file mode 100644
index 0000000..162fcc8
--- /dev/null
+++ b/lib/widgets/common/grid/sections/fixed/list_layout.dart
@@ -0,0 +1,62 @@
+import 'dart:math';
+
+import 'package:aves/model/source/section_keys.dart';
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+
+class FixedExtentSectionedListLayout<T> extends SectionedListLayout<T> {
+ final int columnCount;
+ final double tileWidth, tileHeight;
+
+ const FixedExtentSectionedListLayout({
+ required super.sections,
+ required super.showHeaders,
+ required this.columnCount,
+ required this.tileWidth,
+ required this.tileHeight,
+ required super.spacing,
+ required super.horizontalPadding,
+ required super.sectionLayouts,
+ });
+
+ @override
+ Rect? getTileRect(T item) {
+ final MapEntry<SectionKey?, List<T>>? section = sections.entries.firstWhereOrNull((kv) => kv.value.contains(item));
+ if (section == null) return null;
+
+ final sectionKey = section.key;
+ final sectionLayout = sectionLayouts.firstWhereOrNull((sl) => sl.sectionKey == sectionKey);
+ if (sectionLayout == null) return null;
+
+ final sectionItemIndex = section.value.indexOf(item);
+ final column = sectionItemIndex % columnCount;
+ final row = (sectionItemIndex / columnCount).floor();
+ final listIndex = sectionLayout.firstIndex + 1 + row;
+
+ final left = horizontalPadding + tileWidth * column + spacing * (column - 1);
+ final top = sectionLayout.indexToLayoutOffset(listIndex);
+ return Rect.fromLTWH(left, top, tileWidth, tileHeight);
+ }
+
+ @override
+ T? getItemAt(Offset position) {
+ var dy = position.dy;
+ final sectionLayout = getSectionAt(dy);
+ if (sectionLayout == null) return null;
+
+ final section = sections[sectionLayout.sectionKey];
+ if (section == null) return null;
+
+ dy -= sectionLayout.minOffset + sectionLayout.headerExtent;
+ if (dy < 0) return null;
+
+ final row = dy ~/ (tileHeight + spacing);
+ final column = max(0, position.dx - horizontalPadding) ~/ (tileWidth + spacing);
+ final index = row * columnCount + column;
+ if (index >= section.length) return null;
+
+ return section[index];
+ }
+}
diff --git a/lib/widgets/common/grid/sections/fixed/row.dart b/lib/widgets/common/grid/sections/fixed/row.dart
new file mode 100644
index 0000000..f0f9e1c
--- /dev/null
+++ b/lib/widgets/common/grid/sections/fixed/row.dart
@@ -0,0 +1,162 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+
+class FixedExtentGridRow extends MultiChildRenderObjectWidget {
+ final double width, height, spacing;
+ final TextDirection textDirection;
+
+ const FixedExtentGridRow({
+ super.key,
+ required this.width,
+ required this.height,
+ required this.spacing,
+ required this.textDirection,
+ required super.children,
+ });
+
+ @override
+ RenderObject createRenderObject(BuildContext context) {
+ return RenderFixedExtentGridRow(
+ width: width,
+ height: height,
+ spacing: spacing,
+ textDirection: textDirection,
+ );
+ }
+
+ @override
+ void updateRenderObject(BuildContext context, RenderFixedExtentGridRow renderObject) {
+ renderObject.width = width;
+ renderObject.height = height;
+ renderObject.spacing = spacing;
+ renderObject.textDirection = textDirection;
+ }
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(DoubleProperty('width', width));
+ properties.add(DoubleProperty('height', height));
+ properties.add(DoubleProperty('spacing', spacing));
+ properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
+ }
+}
+
+class _GridRowParentData extends ContainerBoxParentData<RenderBox> {}
+
+class RenderFixedExtentGridRow extends RenderBox with ContainerRenderObjectMixin<RenderBox, _GridRowParentData>, RenderBoxContainerDefaultsMixin<RenderBox, _GridRowParentData> {
+ RenderFixedExtentGridRow({
+ List<RenderBox>? children,
+ required double width,
+ required double height,
+ required double spacing,
+ required TextDirection textDirection,
+ }) : _width = width,
+ _height = height,
+ _spacing = spacing,
+ _textDirection = textDirection {
+ addAll(children);
+ }
+
+ double get width => _width;
+ double _width;
+
+ set width(double value) {
+ if (_width == value) return;
+ _width = value;
+ markNeedsLayout();
+ }
+
+ double get height => _height;
+ double _height;
+
+ set height(double value) {
+ if (_height == value) return;
+ _height = value;
+ markNeedsLayout();
+ }
+
+ double get spacing => _spacing;
+ double _spacing;
+
+ set spacing(double value) {
+ if (_spacing == value) return;
+ _spacing = value;
+ markNeedsLayout();
+ }
+
+ TextDirection get textDirection => _textDirection;
+ TextDirection _textDirection;
+
+ set textDirection(TextDirection value) {
+ if (_textDirection == value) return;
+ _textDirection = value;
+ markNeedsLayout();
+ }
+
+ @override
+ void setupParentData(RenderBox child) {
+ if (child.parentData is! _GridRowParentData) {
+ child.parentData = _GridRowParentData();
+ }
+ }
+
+ double get intrinsicWidth => width * childCount + spacing * (childCount - 1);
+
+ @override
+ double computeMinIntrinsicWidth(double height) => intrinsicWidth;
+
+ @override
+ double computeMaxIntrinsicWidth(double height) => intrinsicWidth;
+
+ @override
+ double computeMinIntrinsicHeight(double width) => height;
+
+ @override
+ double computeMaxIntrinsicHeight(double width) => height;
+
+ @override
+ void performLayout() {
+ var child = firstChild;
+ if (child == null) {
+ size = constraints.smallest;
+ return;
+ }
+ size = Size(constraints.maxWidth, height);
+ final childConstraints = BoxConstraints.tight(Size(width, height));
+ final flipMainAxis = textDirection == TextDirection.rtl;
+ var offset = Offset(flipMainAxis ? size.width - width : 0, 0);
+ final dx = (flipMainAxis ? -1 : 1) * (width + spacing);
+ while (child != null) {
+ child.layout(childConstraints, parentUsesSize: false);
+ final childParentData = child.parentData! as _GridRowParentData;
+ childParentData.offset = offset;
+ offset += Offset(dx, 0);
+ child = childParentData.nextSibling;
+ }
+ }
+
+ @override
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
+ return defaultComputeDistanceToHighestActualBaseline(baseline);
+ }
+
+ @override
+ bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
+ return defaultHitTestChildren(result, position: position);
+ }
+
+ @override
+ void paint(PaintingContext context, Offset offset) {
+ defaultPaint(context, offset);
+ }
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(DoubleProperty('width', width));
+ properties.add(DoubleProperty('height', height));
+ properties.add(DoubleProperty('spacing', spacing));
+ properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
+ }
+}
diff --git a/lib/widgets/common/grid/sections/fixed/scale_grid.dart b/lib/widgets/common/grid/sections/fixed/scale_grid.dart
new file mode 100644
index 0000000..c31b6ea
--- /dev/null
+++ b/lib/widgets/common/grid/sections/fixed/scale_grid.dart
@@ -0,0 +1,111 @@
+import 'dart:ui' as ui;
+
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/material.dart';
+
+class FixedExtentGridPainter extends CustomPainter {
+ final TileLayout tileLayout;
+ final Offset tileCenter;
+ final Size tileSize;
+ final double spacing, horizontalPadding, borderWidth;
+ final Radius borderRadius;
+ final Color color;
+ final TextDirection textDirection;
+
+ const FixedExtentGridPainter({
+ required this.tileLayout,
+ required this.tileCenter,
+ required this.tileSize,
+ required this.spacing,
+ required this.horizontalPadding,
+ required this.borderWidth,
+ required this.borderRadius,
+ required this.color,
+ required this.textDirection,
+ });
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ late final Offset chipCenter;
+ late final Size chipSize;
+ late final int deltaColumn;
+ late final Shader strokeShader;
+ switch (tileLayout) {
+ case TileLayout.mosaic:
+ return;
+ case TileLayout.grid:
+ chipCenter = tileCenter;
+ chipSize = tileSize;
+ deltaColumn = 2;
+ strokeShader = ui.Gradient.radial(
+ tileCenter,
+ chipSize.shortestSide * 2,
+ [
+ color,
+ Colors.transparent,
+ ],
+ [
+ .8,
+ 1,
+ ],
+ );
+ case TileLayout.list:
+ chipSize = Size.square(tileSize.shortestSide);
+ final chipCenterToEdge = chipSize.width / 2;
+ chipCenter = Offset(textDirection == TextDirection.rtl ? size.width - (chipCenterToEdge + horizontalPadding) : chipCenterToEdge + horizontalPadding, tileCenter.dy);
+ deltaColumn = 0;
+ strokeShader = ui.Gradient.linear(
+ tileCenter - Offset(0, chipSize.shortestSide * 3),
+ tileCenter + Offset(0, chipSize.shortestSide * 3),
+ [
+ Colors.transparent,
+ color,
+ color,
+ Colors.transparent,
+ ],
+ [
+ 0,
+ .2,
+ .8,
+ 1,
+ ],
+ );
+ }
+ final strokePaint = Paint()
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = borderWidth
+ ..shader = strokeShader;
+ final fillPaint = Paint()
+ ..style = PaintingStyle.fill
+ ..color = color.withValues(alpha: .25);
+
+ final chipWidth = chipSize.width;
+ final chipHeight = chipSize.height;
+
+ final deltaX = tileSize.width + spacing;
+ final deltaY = tileSize.height + spacing;
+ for (var i = -deltaColumn; i <= deltaColumn; i++) {
+ final dx = deltaX * i;
+ for (var j = -2; j <= 2; j++) {
+ if (i == 0 && j == 0) continue;
+ final dy = deltaY * j;
+ final rect = RRect.fromRectAndRadius(
+ Rect.fromCenter(
+ center: chipCenter + Offset(dx, dy),
+ width: chipWidth - borderWidth,
+ height: chipHeight - borderWidth,
+ ),
+ borderRadius,
+ );
+
+ if ((i.abs() == 1 && j == 0) || (j.abs() == 1 && i == 0)) {
+ canvas.drawRRect(rect, fillPaint);
+ }
+ canvas.drawRRect(rect, strokePaint);
+ }
+ }
+ }
+
+ @override
+ bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
+}
diff --git a/lib/widgets/common/grid/sections/fixed/scale_overlay.dart b/lib/widgets/common/grid/sections/fixed/scale_overlay.dart
new file mode 100644
index 0000000..56be3a9
--- /dev/null
+++ b/lib/widgets/common/grid/sections/fixed/scale_overlay.dart
@@ -0,0 +1,136 @@
+import 'package:aves/theme/durations.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/extensions/theme.dart';
+import 'package:aves/widgets/common/providers/media_query_data_provider.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:aves_utils/aves_utils.dart';
+import 'package:flutter/material.dart';
+
+class FixedExtentScaleOverlay extends StatelessWidget {
+ final TileLayout tileLayout;
+ final Offset tileCenter;
+ final double xMin, xMax;
+ final ValueNotifier<Size> scaledSizeNotifier;
+ final Widget Function(Offset center, Size tileSize, Widget child) gridBuilder;
+ final Widget Function(Size scaledTileSize) builder;
+
+ FixedExtentScaleOverlay({
+ super.key,
+ required this.tileLayout,
+ required this.tileCenter,
+ required Rect contentRect,
+ required this.scaledSizeNotifier,
+ required this.gridBuilder,
+ required this.builder,
+ }) : xMin = contentRect.left,
+ xMax = contentRect.right;
+
+ @override
+ Widget build(BuildContext context) {
+ return MediaQueryDataProvider(
+ child: IgnorePointer(
+ child: _OverlayBackground(
+ gradientCenter: tileLayout == TileLayout.grid ? tileCenter : Offset(context.isRtl ? xMax : xMin, tileCenter.dy),
+ child: ValueListenableBuilder<Size>(
+ valueListenable: scaledSizeNotifier,
+ builder: (context, scaledSize, child) {
+ final width = scaledSize.width;
+ final height = scaledSize.height;
+ // keep scaled thumbnail within the screen
+ var dx = .0;
+ if (tileCenter.dx - width / 2 < xMin) {
+ dx = xMin - (tileCenter.dx - width / 2);
+ } else if (tileCenter.dx + width / 2 > xMax) {
+ dx = xMax - (tileCenter.dx + width / 2);
+ }
+ final clampedCenter = tileCenter.translate(dx, 0);
+
+ var child = builder(scaledSize);
+ child = Stack(
+ children: [
+ Positioned(
+ left: clampedCenter.dx - width / 2,
+ top: clampedCenter.dy - height / 2,
+ child: DefaultTextStyle(
+ style: const TextStyle(),
+ child: child,
+ ),
+ ),
+ ],
+ );
+ child = gridBuilder(clampedCenter, scaledSize, child);
+ return child;
+ },
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _OverlayBackground extends StatefulWidget {
+ final Offset gradientCenter;
+ final Widget child;
+
+ const _OverlayBackground({
+ required this.gradientCenter,
+ required this.child,
+ });
+
+ @override
+ State<_OverlayBackground> createState() => _OverlayBackgroundState();
+}
+
+class _OverlayBackgroundState extends State<_OverlayBackground> {
+ bool _initialized = false;
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) => setState(() => _initialized = true));
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AnimatedContainer(
+ decoration: _buildBackgroundDecoration(context),
+ duration: ADurations.scalingGridBackgroundAnimation,
+ child: widget.child,
+ );
+ }
+
+ BoxDecoration _buildBackgroundDecoration(BuildContext context) {
+ final isDark = Theme.of(context).isDark;
+ final gradientCenter = widget.gradientCenter;
+ return _initialized
+ ? BoxDecoration(
+ gradient: RadialGradient(
+ center: FractionalOffset.fromOffsetAndSize(gradientCenter, MediaQuery.sizeOf(context)),
+ radius: 1,
+ colors: isDark
+ ? const [
+ Colors.black,
+ Colors.black54,
+ ]
+ : const [
+ Colors.white,
+ Colors.white38,
+ ],
+ ),
+ )
+ : BoxDecoration(
+ // provide dummy gradient to lerp to the other one during animation
+ gradient: RadialGradient(
+ colors: isDark
+ ? const [
+ ColorUtils.transparentBlack,
+ ColorUtils.transparentBlack,
+ ]
+ : const [
+ ColorUtils.transparentWhite,
+ ColorUtils.transparentWhite,
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/common/grid/sections/fixed/section_layout.dart b/lib/widgets/common/grid/sections/fixed/section_layout.dart
new file mode 100644
index 0000000..7cdfbc9
--- /dev/null
+++ b/lib/widgets/common/grid/sections/fixed/section_layout.dart
@@ -0,0 +1,41 @@
+import 'package:aves/widgets/common/grid/sections/section_layout.dart';
+
+class FixedExtentSectionLayout extends SectionLayout {
+ final double tileHeight, mainAxisStride;
+
+ @override
+ List<Object?> get props => [sectionKey, firstIndex, lastIndex, minOffset, maxOffset, headerExtent, tileHeight, spacing];
+
+ const FixedExtentSectionLayout({
+ required super.sectionKey,
+ required super.firstIndex,
+ required super.lastIndex,
+ required super.minOffset,
+ required super.maxOffset,
+ required super.headerExtent,
+ required this.tileHeight,
+ required super.spacing,
+ required super.builder,
+ }) : mainAxisStride = tileHeight + spacing;
+
+ @override
+ double indexToLayoutOffset(int index) {
+ index -= bodyFirstIndex;
+ if (index < 0) return minOffset;
+ return bodyMinOffset + index * mainAxisStride;
+ }
+
+ @override
+ int getMinChildIndexForScrollOffset(double scrollOffset) {
+ scrollOffset -= bodyMinOffset;
+ if (mainAxisStride == 0 || !scrollOffset.isFinite || scrollOffset < 0) return firstIndex;
+ return bodyFirstIndex + scrollOffset ~/ mainAxisStride;
+ }
+
+ @override
+ int getMaxChildIndexForScrollOffset(double scrollOffset) {
+ scrollOffset -= bodyMinOffset;
+ if (mainAxisStride == 0 || !scrollOffset.isFinite || scrollOffset < 0) return firstIndex;
+ return bodyFirstIndex + (scrollOffset / mainAxisStride).ceil() - 1;
+ }
+}
diff --git a/lib/widgets/common/grid/sections/fixed/section_layout_builder.dart b/lib/widgets/common/grid/sections/fixed/section_layout_builder.dart
new file mode 100644
index 0000000..e450f23
--- /dev/null
+++ b/lib/widgets/common/grid/sections/fixed/section_layout_builder.dart
@@ -0,0 +1,109 @@
+import 'package:aves/model/source/section_keys.dart';
+import 'package:aves/widgets/common/grid/sections/fixed/list_layout.dart';
+import 'package:aves/widgets/common/grid/sections/fixed/row.dart';
+import 'package:aves/widgets/common/grid/sections/fixed/section_layout.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/sections/section_layout_builder.dart';
+import 'package:flutter/material.dart';
+
+class FixedExtentSectionLayoutBuilder<T> extends SectionLayoutBuilder<T> {
+ int _currentIndex = 0;
+ double _currentOffset = 0;
+ final List<Size> _itemSizes;
+
+ FixedExtentSectionLayoutBuilder({
+ required super.sections,
+ required super.showHeaders,
+ required super.getHeaderExtent,
+ required super.buildHeader,
+ required super.scrollableWidth,
+ required super.tileLayout,
+ required super.columnCount,
+ required super.spacing,
+ required super.horizontalPadding,
+ required super.tileWidth,
+ required super.tileHeight,
+ required super.tileBuilder,
+ required super.tileAnimationDelay,
+ }) : _itemSizes = List.generate(columnCount, (index) => Size(tileWidth, tileHeight));
+
+ @override
+ SectionedListLayout<T> updateLayouts(BuildContext context) {
+ final sectionLayouts = sections.keys
+ .map((sectionKey) => buildSectionLayout(
+ headerExtent: showHeaders ? getHeaderExtent(context, sectionKey) : 0.0,
+ sectionKey: sectionKey,
+ section: sections[sectionKey]!,
+ animate: animate,
+ ))
+ .toList();
+
+ return FixedExtentSectionedListLayout<T>(
+ sections: sections,
+ showHeaders: showHeaders,
+ columnCount: columnCount,
+ tileWidth: tileWidth,
+ tileHeight: tileHeight,
+ spacing: spacing,
+ horizontalPadding: horizontalPadding,
+ sectionLayouts: sectionLayouts,
+ );
+ }
+
+ @override
+ SectionLayout buildSectionLayout({
+ required double headerExtent,
+ required SectionKey sectionKey,
+ required List<T> section,
+ required bool animate,
+ }) {
+ final sectionItemCount = section.length;
+ final rowCount = (sectionItemCount / columnCount).ceil();
+ final sectionChildCount = 1 + rowCount;
+
+ final sectionFirstIndex = _currentIndex;
+ _currentIndex += sectionChildCount;
+ final sectionLastIndex = _currentIndex - 1;
+
+ final sectionMinOffset = _currentOffset;
+ _currentOffset += headerExtent + tileHeight * rowCount + spacing * (rowCount - 1);
+ final sectionMaxOffset = _currentOffset;
+
+ return FixedExtentSectionLayout(
+ sectionKey: sectionKey,
+ firstIndex: sectionFirstIndex,
+ lastIndex: sectionLastIndex,
+ minOffset: sectionMinOffset,
+ maxOffset: sectionMaxOffset,
+ headerExtent: headerExtent,
+ tileHeight: tileHeight,
+ spacing: spacing,
+ builder: (context, listIndex) {
+ final textDirection = Directionality.of(context);
+ final sectionChildIndex = listIndex - sectionFirstIndex;
+ return buildSectionWidget(
+ context: context,
+ section: section,
+ sectionGridIndex: listIndex * columnCount,
+ sectionChildIndex: sectionChildIndex,
+ itemIndexRange: () => (
+ (sectionChildIndex - 1) * columnCount,
+ sectionChildIndex * columnCount,
+ ),
+ sectionKey: sectionKey,
+ headerExtent: headerExtent,
+ itemSizes: _itemSizes,
+ animate: animate,
+ buildGridRow: (children) => FixedExtentGridRow(
+ width: tileWidth,
+ height: tileHeight,
+ spacing: spacing,
+ textDirection: textDirection,
+ children: children,
+ ),
+ );
+ },
+ );
+ }
+}
diff --git a/lib/widgets/common/grid/sections/list_layout.dart b/lib/widgets/common/grid/sections/list_layout.dart
new file mode 100644
index 0000000..06e9f05
--- /dev/null
+++ b/lib/widgets/common/grid/sections/list_layout.dart
@@ -0,0 +1,28 @@
+import 'package:aves/model/source/section_keys.dart';
+import 'package:aves/widgets/common/grid/sections/section_layout.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+
+abstract class SectionedListLayout<T> {
+ final Map<SectionKey, List<T>> sections;
+ final bool showHeaders;
+ final double spacing, horizontalPadding;
+ final List<SectionLayout> sectionLayouts;
+
+ const SectionedListLayout({
+ required this.sections,
+ required this.showHeaders,
+ required this.spacing,
+ required this.horizontalPadding,
+ required this.sectionLayouts,
+ });
+
+ // returns tile rectangle in layout space, i.e. x=0 is start
+ Rect? getTileRect(T item);
+
+ SectionLayout? getSectionAt(double offsetY) => sectionLayouts.firstWhereOrNull((sl) => offsetY < sl.maxOffset);
+
+ // `position` in layout space, i.e. x=0 is start
+ T? getItemAt(Offset position);
+}
diff --git a/lib/widgets/common/grid/sections/mosaic/list_layout.dart b/lib/widgets/common/grid/sections/mosaic/list_layout.dart
new file mode 100644
index 0000000..4590bf9
--- /dev/null
+++ b/lib/widgets/common/grid/sections/mosaic/list_layout.dart
@@ -0,0 +1,78 @@
+import 'package:aves/model/source/section_keys.dart';
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/section_layout.dart';
+import 'package:aves/widgets/common/grid/sections/section_layout.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+
+class MosaicSectionedListLayout<T> extends SectionedListLayout<T> {
+ const MosaicSectionedListLayout({
+ required super.sections,
+ required super.showHeaders,
+ required super.spacing,
+ required super.horizontalPadding,
+ required super.sectionLayouts,
+ });
+
+ List<MosaicRowLayout> _rowsFor(SectionLayout sectionLayout) => (sectionLayout as MosaicSectionLayout).rows;
+
+ @override
+ Rect? getTileRect(T item) {
+ final MapEntry<SectionKey?, List<T>>? section = sections.entries.firstWhereOrNull((kv) => kv.value.contains(item));
+ if (section == null) return null;
+
+ final sectionKey = section.key;
+ final sectionLayout = sectionLayouts.firstWhereOrNull((sl) => sl.sectionKey == sectionKey);
+ if (sectionLayout == null) return null;
+
+ final sectionItemIndex = section.value.indexOf(item);
+ final row = _rowsFor(sectionLayout).firstWhereOrNull((row) => sectionItemIndex <= row.lastIndex);
+ if (row == null) return null;
+
+ final rowItemIndex = sectionItemIndex - row.firstIndex;
+ final tileWidth = row.itemWidths[rowItemIndex];
+ final tileHeight = row.height - spacing;
+
+ var left = horizontalPadding;
+ row.itemWidths.forEachIndexedWhile((i, width) {
+ if (i == rowItemIndex) return true;
+
+ left += width + spacing;
+ return false;
+ });
+ final listIndex = sectionLayout.firstIndex + 1 + _rowsFor(sectionLayout).indexOf(row);
+
+ final top = sectionLayout.indexToLayoutOffset(listIndex);
+ return Rect.fromLTWH(left, top, tileWidth, tileHeight);
+ }
+
+ @override
+ T? getItemAt(Offset position) {
+ var dy = position.dy;
+ final sectionLayout = getSectionAt(dy);
+ if (sectionLayout == null) return null;
+
+ final section = sections[sectionLayout.sectionKey];
+ if (section == null) return null;
+
+ dy -= sectionLayout.minOffset + sectionLayout.headerExtent;
+ if (dy < 0) return null;
+
+ final row = _rowsFor(sectionLayout).firstWhereOrNull((v) => dy < v.maxOffset);
+ if (row == null) return null;
+
+ var dx = position.dx - horizontalPadding;
+ var index = -1;
+ row.itemWidths.forEachIndexedWhile((i, width) {
+ dx -= width + spacing;
+ if (dx > 0) return true;
+
+ index = row.firstIndex + i;
+ return false;
+ });
+
+ if (index < 0 || index >= section.length) return null;
+ return section[index];
+ }
+}
diff --git a/lib/widgets/common/grid/sections/mosaic/row.dart b/lib/widgets/common/grid/sections/mosaic/row.dart
new file mode 100644
index 0000000..1198405
--- /dev/null
+++ b/lib/widgets/common/grid/sections/mosaic/row.dart
@@ -0,0 +1,159 @@
+import 'package:aves/widgets/common/grid/sections/mosaic/section_layout.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+
+class MosaicGridRow extends MultiChildRenderObjectWidget {
+ final MosaicRowLayout rowLayout;
+ final double spacing;
+ final TextDirection textDirection;
+
+ const MosaicGridRow({
+ super.key,
+ required this.rowLayout,
+ required this.spacing,
+ required this.textDirection,
+ required super.children,
+ });
+
+ @override
+ RenderObject createRenderObject(BuildContext context) {
+ return RenderMosaicGridRow(
+ rowLayout: rowLayout,
+ spacing: spacing,
+ textDirection: textDirection,
+ );
+ }
+
+ @override
+ void updateRenderObject(BuildContext context, RenderMosaicGridRow renderObject) {
+ renderObject.rowLayout = rowLayout;
+ renderObject.spacing = spacing;
+ renderObject.textDirection = textDirection;
+ }
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(DiagnosticsProperty<MosaicRowLayout>('rowLayout', rowLayout));
+ properties.add(DoubleProperty('spacing', spacing));
+ properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
+ }
+}
+
+class _GridRowParentData extends ContainerBoxParentData<RenderBox> {}
+
+class RenderMosaicGridRow extends RenderBox with ContainerRenderObjectMixin<RenderBox, _GridRowParentData>, RenderBoxContainerDefaultsMixin<RenderBox, _GridRowParentData> {
+ RenderMosaicGridRow({
+ List<RenderBox>? children,
+ required MosaicRowLayout rowLayout,
+ required double spacing,
+ required TextDirection textDirection,
+ }) : _rowLayout = rowLayout,
+ _spacing = spacing,
+ _textDirection = textDirection {
+ addAll(children);
+ }
+
+ MosaicRowLayout get rowLayout => _rowLayout;
+ MosaicRowLayout _rowLayout;
+
+ set rowLayout(MosaicRowLayout value) {
+ if (_rowLayout == value) return;
+ _rowLayout = value;
+ markNeedsLayout();
+ }
+
+ double get spacing => _spacing;
+ double _spacing;
+
+ set spacing(double value) {
+ if (_spacing == value) return;
+ _spacing = value;
+ markNeedsLayout();
+ }
+
+ TextDirection get textDirection => _textDirection;
+ TextDirection _textDirection;
+
+ set textDirection(TextDirection value) {
+ if (_textDirection == value) return;
+ _textDirection = value;
+ markNeedsLayout();
+ }
+
+ @override
+ void setupParentData(RenderBox child) {
+ if (child.parentData is! _GridRowParentData) {
+ child.parentData = _GridRowParentData();
+ }
+ }
+
+ double get intrinsicWidth => rowLayout.itemWidths.sum + spacing * (childCount - 1);
+
+ @override
+ double computeMinIntrinsicWidth(double height) => intrinsicWidth;
+
+ @override
+ double computeMaxIntrinsicWidth(double height) => intrinsicWidth;
+
+ @override
+ double computeMinIntrinsicHeight(double width) => rowLayout.height;
+
+ @override
+ double computeMaxIntrinsicHeight(double width) => rowLayout.height;
+
+ @override
+ void performLayout() {
+ var child = firstChild;
+ if (child == null) {
+ size = constraints.smallest;
+ return;
+ }
+ final thumbnailHeight = rowLayout.height - spacing;
+ size = Size(constraints.maxWidth, rowLayout.height);
+ final flipMainAxis = textDirection == TextDirection.rtl;
+ var i = 0;
+ double offsetX = flipMainAxis ? size.width : 0;
+ while (child != null) {
+ final thumbnailWidth = rowLayout.itemWidths[i];
+ final childConstraints = BoxConstraints.tight(Size(thumbnailWidth, thumbnailHeight));
+ child.layout(childConstraints, parentUsesSize: false);
+ final childParentData = child.parentData! as _GridRowParentData;
+ if (flipMainAxis) {
+ offsetX -= thumbnailWidth;
+ }
+ childParentData.offset = Offset(offsetX, 0);
+ if (flipMainAxis) {
+ offsetX -= spacing;
+ } else {
+ offsetX += thumbnailWidth + spacing;
+ }
+ child = childParentData.nextSibling;
+ i++;
+ }
+ }
+
+ @override
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
+ return defaultComputeDistanceToHighestActualBaseline(baseline);
+ }
+
+ @override
+ bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
+ return defaultHitTestChildren(result, position: position);
+ }
+
+ @override
+ void paint(PaintingContext context, Offset offset) {
+ defaultPaint(context, offset);
+ }
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(DiagnosticsProperty<MosaicRowLayout>('rowLayout', rowLayout));
+ properties.add(DoubleProperty('spacing', spacing));
+ properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
+ }
+}
diff --git a/lib/widgets/common/grid/sections/mosaic/scale_grid.dart b/lib/widgets/common/grid/sections/mosaic/scale_grid.dart
new file mode 100644
index 0000000..820d5c7
--- /dev/null
+++ b/lib/widgets/common/grid/sections/mosaic/scale_grid.dart
@@ -0,0 +1,74 @@
+import 'package:aves/theme/durations.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/scale_overlay.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/section_layout_builder.dart';
+import 'package:flutter/material.dart';
+
+class MosaicGrid extends StatelessWidget {
+ final Rect contentRect;
+ final Size tileSize;
+ final double spacing;
+ final MosaicItemBuilder builder;
+
+ static const _itemRatios = <double>[
+ 3 / 4,
+ 16 / 9,
+ 9 / 16,
+ 3 / 4,
+ 4 / 3,
+ 4 / 3,
+ 3 / 4,
+ 4 / 3,
+ 4 / 3,
+ 4 / 3,
+ ];
+
+ const MosaicGrid({
+ super.key,
+ required this.contentRect,
+ required this.tileSize,
+ required this.spacing,
+ required this.builder,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final children = <Widget>[];
+
+ final targetExtent = tileSize.width;
+ final rows = MosaicSectionLayoutBuilder.computeMosaicRows(
+ section: List.generate(5, (i) => _itemRatios).expand((v) => v).toList(),
+ availableWidthFor: (itemCount) => contentRect.width - (itemCount - 1) * spacing,
+ heightMax: targetExtent * MosaicSectionLayoutBuilder.heightMaxFactor,
+ targetExtent: targetExtent,
+ spacing: spacing,
+ bottom: tileSize.height - tileSize.width,
+ coverRatioResolver: (item) => item,
+ );
+
+ var i = 0;
+ var dy = contentRect.top;
+ rows.forEach((row) {
+ var dx = contentRect.left;
+ final itemHeight = row.height - spacing;
+ row.itemWidths.forEach((itemWidth) {
+ children.add(
+ AnimatedPositioned(
+ left: dx,
+ top: dy,
+ width: itemWidth,
+ height: itemHeight,
+ duration: ADurations.scalingGridPositionAnimation,
+ child: builder(i, targetExtent),
+ ),
+ );
+ dx += itemWidth + spacing;
+ i++;
+ });
+ dy += row.height;
+ });
+
+ return Stack(
+ children: children,
+ );
+ }
+}
diff --git a/lib/widgets/common/grid/sections/mosaic/scale_overlay.dart b/lib/widgets/common/grid/sections/mosaic/scale_overlay.dart
new file mode 100644
index 0000000..1e44634
--- /dev/null
+++ b/lib/widgets/common/grid/sections/mosaic/scale_overlay.dart
@@ -0,0 +1,117 @@
+import 'package:aves/theme/durations.dart';
+import 'package:aves/widgets/common/extensions/theme.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/scale_grid.dart';
+import 'package:aves/widgets/common/providers/media_query_data_provider.dart';
+import 'package:aves_utils/aves_utils.dart';
+import 'package:flutter/material.dart';
+
+typedef MosaicItemBuilder = Widget Function(int index, double targetExtent);
+
+class MosaicScaleOverlay extends StatelessWidget {
+ final Rect contentRect;
+ final double spacing, extentMax;
+ final ValueNotifier<Size> scaledSizeNotifier;
+ final MosaicItemBuilder itemBuilder;
+
+ const MosaicScaleOverlay({
+ super.key,
+ required this.contentRect,
+ required this.spacing,
+ required this.extentMax,
+ required this.scaledSizeNotifier,
+ required this.itemBuilder,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return MediaQueryDataProvider(
+ child: IgnorePointer(
+ child: _OverlayBackground(
+ child: ValueListenableBuilder<Size>(
+ valueListenable: scaledSizeNotifier,
+ builder: (context, scaledSize, child) {
+ final theme = Theme.of(context);
+ final colorScheme = theme.colorScheme;
+ Widget _buildBar(double width, Color color) => ClipRRect(
+ borderRadius: const BorderRadius.all(Radius.circular(4)),
+ child: Container(
+ color: color,
+ width: width,
+ height: 4,
+ ),
+ );
+ return SafeArea(
+ left: false,
+ right: false,
+ bottom: false,
+ child: Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ _buildBar(extentMax, colorScheme.onSurface.withValues(alpha: .2)),
+ _buildBar(scaledSize.width, colorScheme.primary),
+ ],
+ ),
+ ),
+ Expanded(
+ child: MosaicGrid(
+ contentRect: contentRect,
+ tileSize: scaledSize,
+ spacing: spacing,
+ builder: itemBuilder,
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _OverlayBackground extends StatefulWidget {
+ final Widget child;
+
+ const _OverlayBackground({
+ required this.child,
+ });
+
+ @override
+ State<_OverlayBackground> createState() => _OverlayBackgroundState();
+}
+
+class _OverlayBackgroundState extends State<_OverlayBackground> {
+ bool _initialized = false;
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) => setState(() => _initialized = true));
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AnimatedContainer(
+ decoration: _buildBackgroundDecoration(context),
+ duration: ADurations.scalingGridBackgroundAnimation,
+ child: widget.child,
+ );
+ }
+
+ BoxDecoration _buildBackgroundDecoration(BuildContext context) {
+ final isDark = Theme.of(context).isDark;
+ return _initialized
+ ? BoxDecoration(
+ color: isDark ? Colors.black87 : const Color(0xDDFFFFFF),
+ )
+ : BoxDecoration(
+ color: isDark ? ColorUtils.transparentBlack : ColorUtils.transparentWhite,
+ );
+ }
+}
diff --git a/lib/widgets/common/grid/sections/mosaic/section_layout.dart b/lib/widgets/common/grid/sections/mosaic/section_layout.dart
new file mode 100644
index 0000000..0cba43a
--- /dev/null
+++ b/lib/widgets/common/grid/sections/mosaic/section_layout.dart
@@ -0,0 +1,61 @@
+import 'package:aves/widgets/common/grid/sections/section_layout.dart';
+import 'package:collection/collection.dart';
+import 'package:equatable/equatable.dart';
+
+class MosaicSectionLayout extends SectionLayout {
+ final List<MosaicRowLayout> rows;
+
+ @override
+ List<Object?> get props => [sectionKey, firstIndex, lastIndex, minOffset, maxOffset, headerExtent, rows, spacing];
+
+ const MosaicSectionLayout({
+ required super.sectionKey,
+ required super.firstIndex,
+ required super.lastIndex,
+ required super.minOffset,
+ required super.maxOffset,
+ required super.headerExtent,
+ required this.rows,
+ required super.spacing,
+ required super.builder,
+ });
+
+ @override
+ double indexToLayoutOffset(int index) {
+ index -= bodyFirstIndex;
+ if (index < 0) return minOffset;
+ return bodyMinOffset + (index < rows.length ? rows[index].minOffset : rows.lastOrNull?.maxOffset ?? 0);
+ }
+
+ @override
+ int getMinChildIndexForScrollOffset(double scrollOffset) {
+ scrollOffset -= bodyMinOffset;
+ if (scrollOffset < 0) return firstIndex;
+ return bodyFirstIndex + rows.indexWhere((v) => scrollOffset < v.maxOffset);
+ }
+
+ @override
+ int getMaxChildIndexForScrollOffset(double scrollOffset) {
+ scrollOffset -= bodyMinOffset;
+ if (scrollOffset < 0) return firstIndex;
+ final rowIndex = rows.indexWhere((v) => scrollOffset < v.maxOffset);
+ return bodyFirstIndex + (rowIndex == -1 ? rows.length - 1 : rowIndex);
+ }
+}
+
+class MosaicRowLayout extends Equatable {
+ final int firstIndex, lastIndex;
+ final double minOffset, maxOffset, height;
+ final List<double> itemWidths;
+
+ @override
+ List<Object?> get props => [firstIndex, lastIndex, minOffset, maxOffset, height, itemWidths];
+
+ const MosaicRowLayout({
+ required this.firstIndex,
+ required this.lastIndex,
+ required this.minOffset,
+ required this.height,
+ required this.itemWidths,
+ }) : maxOffset = minOffset + height;
+}
diff --git a/lib/widgets/common/grid/sections/mosaic/section_layout_builder.dart b/lib/widgets/common/grid/sections/mosaic/section_layout_builder.dart
new file mode 100644
index 0000000..26701c5
--- /dev/null
+++ b/lib/widgets/common/grid/sections/mosaic/section_layout_builder.dart
@@ -0,0 +1,198 @@
+import 'dart:math';
+
+import 'package:aves/model/source/section_keys.dart';
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/list_layout.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/row.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/section_layout.dart';
+import 'package:aves/widgets/common/grid/sections/provider.dart';
+import 'package:aves/widgets/common/grid/sections/section_layout.dart';
+import 'package:aves/widgets/common/grid/sections/section_layout_builder.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+
+class MosaicSectionLayoutBuilder<T> extends SectionLayoutBuilder<T> {
+ int _currentIndex = 0;
+ double _currentOffset = 0;
+ late double Function(int itemCount) rowAvailableWidth;
+ late double rowHeightMax;
+ final CoverRatioResolver<T> coverRatioResolver;
+
+ static const double heightMaxFactor = 2.4;
+ static const double minThumbnailAspectRatio = 9 / 32;
+ static const double maxThumbnailAspectRatio = 32 / 9;
+
+ MosaicSectionLayoutBuilder({
+ required super.sections,
+ required super.showHeaders,
+ required super.getHeaderExtent,
+ required super.buildHeader,
+ required super.scrollableWidth,
+ required super.tileLayout,
+ required super.columnCount,
+ required super.spacing,
+ required super.horizontalPadding,
+ required super.tileWidth,
+ required super.tileHeight,
+ required super.tileBuilder,
+ required Duration tileAnimationDelay,
+ required this.coverRatioResolver,
+ }) : super(tileAnimationDelay: Duration(milliseconds: (tileAnimationDelay.inMilliseconds / columnCount).ceil())) {
+ final rowWidth = scrollableWidth - horizontalPadding * 2;
+ rowAvailableWidth = (itemCount) => rowWidth - (itemCount - 1) * spacing;
+ rowHeightMax = tileWidth * heightMaxFactor;
+ }
+
+ @override
+ SectionedListLayout<T> updateLayouts(BuildContext context) {
+ final sectionLayouts = sections.keys
+ .map((sectionKey) => buildSectionLayout(
+ headerExtent: showHeaders ? getHeaderExtent(context, sectionKey) : 0.0,
+ sectionKey: sectionKey,
+ section: sections[sectionKey]!,
+ animate: animate,
+ ))
+ .toList();
+
+ return MosaicSectionedListLayout<T>(
+ sections: sections,
+ showHeaders: showHeaders,
+ spacing: spacing,
+ horizontalPadding: horizontalPadding,
+ sectionLayouts: sectionLayouts,
+ );
+ }
+
+ @override
+ SectionLayout buildSectionLayout({
+ required double headerExtent,
+ required SectionKey sectionKey,
+ required List<T> section,
+ required bool animate,
+ }) {
+ final rows = computeMosaicRows(
+ section: section,
+ availableWidthFor: rowAvailableWidth,
+ heightMax: rowHeightMax,
+ targetExtent: tileWidth,
+ spacing: spacing,
+ bottom: bottom,
+ coverRatioResolver: (item) => coverRatioResolver(item).clamp(minThumbnailAspectRatio, maxThumbnailAspectRatio),
+ );
+ final rowCount = rows.length;
+ final sectionChildCount = 1 + rowCount;
+
+ final sectionFirstIndex = _currentIndex;
+ _currentIndex += sectionChildCount;
+ final sectionLastIndex = _currentIndex - 1;
+
+ final sectionMinOffset = _currentOffset;
+ _currentOffset += headerExtent + rows.map((v) => v.height).sum - spacing;
+ final sectionMaxOffset = _currentOffset;
+
+ return MosaicSectionLayout(
+ sectionKey: sectionKey,
+ firstIndex: sectionFirstIndex,
+ lastIndex: sectionLastIndex,
+ minOffset: sectionMinOffset,
+ maxOffset: sectionMaxOffset,
+ headerExtent: headerExtent,
+ rows: rows,
+ spacing: spacing,
+ builder: (context, listIndex) {
+ final textDirection = Directionality.of(context);
+ final sectionChildIndex = listIndex - sectionFirstIndex;
+ final isHeader = sectionChildIndex == 0;
+ final row = isHeader ? rows.first : rows[sectionChildIndex - 1];
+ final sectionGridIndex = isHeader ? sectionFirstIndex * columnCount : (sectionChildIndex + 1) * columnCount + row.firstIndex;
+ return buildSectionWidget(
+ context: context,
+ section: section,
+ sectionGridIndex: sectionGridIndex,
+ sectionChildIndex: sectionChildIndex,
+ itemIndexRange: () => isHeader ? const (0, 0) : (row.firstIndex, row.lastIndex + 1),
+ sectionKey: sectionKey,
+ headerExtent: headerExtent,
+ itemSizes: row.itemWidths.map((v) => Size(v, row.height)).toList(),
+ animate: animate,
+ buildGridRow: (children) {
+ return isHeader
+ ? const SizedBox()
+ : MosaicGridRow(
+ rowLayout: row,
+ spacing: spacing,
+ textDirection: textDirection,
+ children: children,
+ );
+ },
+ );
+ },
+ );
+ }
+
+ static List<MosaicRowLayout> computeMosaicRows<T>({
+ required List<T> section,
+ required double Function(int itemCount) availableWidthFor,
+ required double heightMax,
+ required double targetExtent,
+ required double spacing,
+ required double bottom,
+ required CoverRatioResolver<T> coverRatioResolver,
+ }) {
+ final rows = <MosaicRowLayout>[];
+ final items = <T>[];
+ double ratioSum = 0, ratioMin = double.infinity;
+ int firstIndex = 0;
+ double minOffset = 0;
+
+ void addRow(int i, {required bool complete}) {
+ if (items.isEmpty) return;
+
+ final availableWidth = availableWidthFor(items.length);
+ var height = availableWidth / ratioSum + spacing;
+ if (height > heightMax + precisionErrorTolerance) {
+ if (!complete) {
+ ratioSum = availableWidth / (heightMax - spacing);
+ addRow(i, complete: complete);
+ }
+ return;
+ }
+
+ height += bottom;
+ rows.add(MosaicRowLayout(
+ firstIndex: firstIndex,
+ lastIndex: i - 1,
+ minOffset: minOffset,
+ height: height,
+ itemWidths: items.map((item) => availableWidth * coverRatioResolver(item) / ratioSum).toList(),
+ ));
+ firstIndex = i;
+ minOffset += height;
+ ratioMin = double.infinity;
+ ratioSum = 0;
+ items.clear();
+ }
+
+ section.forEachIndexed((i, item) {
+ final ratio = coverRatioResolver(item);
+ final nextAvailableWidth = availableWidthFor(items.length + 1);
+ final nextRatioSum = ratio + ratioSum;
+ final nextItemMinWidth = nextAvailableWidth * min(ratio, ratioMin) / nextRatioSum;
+ final nextHeight = nextAvailableWidth / nextRatioSum + spacing;
+ if (nextItemMinWidth < targetExtent || nextHeight < targetExtent) {
+ // add row when appending the next item would make other items too small
+ addRow(i, complete: true);
+ }
+ items.add(item);
+ ratioMin = min(ratio, ratioMin);
+ ratioSum += ratio;
+ });
+ if (items.isNotEmpty) {
+ // add last row, possibly incomplete
+ addRow(section.length, complete: false);
+ }
+
+ return rows;
+ }
+}
diff --git a/lib/widgets/common/grid/sections/provider.dart b/lib/widgets/common/grid/sections/provider.dart
new file mode 100644
index 0000000..d8b2eb9
--- /dev/null
+++ b/lib/widgets/common/grid/sections/provider.dart
@@ -0,0 +1,105 @@
+import 'package:aves/model/source/section_keys.dart';
+import 'package:aves/widgets/common/grid/sections/fixed/section_layout_builder.dart';
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:aves/widgets/common/grid/sections/mosaic/section_layout_builder.dart';
+import 'package:aves/widgets/common/grid/sections/section_layout_builder.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:provider/provider.dart';
+
+typedef CoverRatioResolver<T> = double Function(T item);
+
+abstract class SectionedListLayoutProvider<T> extends StatelessWidget {
+ final double scrollableWidth;
+ final TileLayout tileLayout;
+ final int columnCount;
+ final double spacing, horizontalPadding, tileWidth, tileHeight;
+ final TileBuilder<T> tileBuilder;
+ final Duration tileAnimationDelay;
+ final CoverRatioResolver<T> coverRatioResolver;
+ final Widget child;
+
+ const SectionedListLayoutProvider({
+ super.key,
+ required this.scrollableWidth,
+ required this.tileLayout,
+ required int columnCount,
+ required this.spacing,
+ required this.horizontalPadding,
+ required double tileWidth,
+ required this.tileHeight,
+ required this.tileBuilder,
+ required this.tileAnimationDelay,
+ required this.coverRatioResolver,
+ required this.child,
+ }) : assert(scrollableWidth != 0),
+ columnCount = tileLayout == TileLayout.list ? 1 : columnCount,
+ tileWidth = tileLayout == TileLayout.list ? scrollableWidth - (horizontalPadding * 2) : tileWidth;
+
+ @override
+ Widget build(BuildContext context) {
+ return ProxyProvider0<SectionedListLayout<T>>(
+ update: (context, _) {
+ switch (tileLayout) {
+ case TileLayout.mosaic:
+ return MosaicSectionLayoutBuilder<T>(
+ sections: sections,
+ showHeaders: showHeaders,
+ getHeaderExtent: getHeaderExtent,
+ buildHeader: buildHeader,
+ scrollableWidth: scrollableWidth,
+ tileLayout: tileLayout,
+ columnCount: columnCount,
+ spacing: spacing,
+ horizontalPadding: horizontalPadding,
+ tileWidth: tileWidth,
+ tileHeight: tileHeight,
+ tileBuilder: tileBuilder,
+ tileAnimationDelay: tileAnimationDelay,
+ coverRatioResolver: coverRatioResolver,
+ ).updateLayouts(context);
+ case TileLayout.grid:
+ case TileLayout.list:
+ return FixedExtentSectionLayoutBuilder<T>(
+ sections: sections,
+ showHeaders: showHeaders,
+ buildHeader: buildHeader,
+ getHeaderExtent: getHeaderExtent,
+ scrollableWidth: scrollableWidth,
+ tileLayout: tileLayout,
+ columnCount: columnCount,
+ spacing: spacing,
+ horizontalPadding: horizontalPadding,
+ tileWidth: tileWidth,
+ tileHeight: tileHeight,
+ tileBuilder: tileBuilder,
+ tileAnimationDelay: tileAnimationDelay,
+ ).updateLayouts(context);
+ }
+ },
+ child: child,
+ );
+ }
+
+ bool get showHeaders;
+
+ Map<SectionKey, List<T>> get sections;
+
+ double getHeaderExtent(BuildContext context, SectionKey sectionKey);
+
+ Widget buildHeader(BuildContext context, SectionKey sectionKey, double headerExtent);
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(DoubleProperty('scrollableWidth', scrollableWidth));
+ properties.add(EnumProperty<TileLayout>('tileLayout', tileLayout));
+ properties.add(IntProperty('columnCount', columnCount));
+ properties.add(DoubleProperty('spacing', spacing));
+ properties.add(DoubleProperty('horizontalPadding', horizontalPadding));
+ properties.add(DoubleProperty('tileWidth', tileWidth));
+ properties.add(DoubleProperty('tileHeight', tileHeight));
+ properties.add(DiagnosticsProperty<bool>('showHeaders', showHeaders));
+ }
+}
diff --git a/lib/widgets/common/grid/sections/section_layout.dart b/lib/widgets/common/grid/sections/section_layout.dart
new file mode 100644
index 0000000..ccc7b99
--- /dev/null
+++ b/lib/widgets/common/grid/sections/section_layout.dart
@@ -0,0 +1,37 @@
+import 'package:aves/model/source/section_keys.dart';
+import 'package:equatable/equatable.dart';
+import 'package:flutter/material.dart';
+
+@immutable
+abstract class SectionLayout extends Equatable {
+ final SectionKey sectionKey;
+ final int firstIndex, lastIndex, bodyFirstIndex;
+ final double minOffset, maxOffset, bodyMinOffset;
+ final double headerExtent, spacing;
+ final IndexedWidgetBuilder builder;
+
+ @override
+ List<Object?> get props => [sectionKey, firstIndex, lastIndex, minOffset, maxOffset, headerExtent, spacing];
+
+ const SectionLayout({
+ required this.sectionKey,
+ required this.firstIndex,
+ required this.lastIndex,
+ required this.minOffset,
+ required this.maxOffset,
+ required this.headerExtent,
+ required this.spacing,
+ required this.builder,
+ }) : bodyFirstIndex = firstIndex + 1,
+ bodyMinOffset = minOffset + headerExtent;
+
+ bool hasChild(int index) => firstIndex <= index && index <= lastIndex;
+
+ bool hasChildAtOffset(double scrollOffset) => minOffset <= scrollOffset && scrollOffset <= maxOffset;
+
+ double indexToLayoutOffset(int index);
+
+ int getMinChildIndexForScrollOffset(double scrollOffset);
+
+ int getMaxChildIndexForScrollOffset(double scrollOffset);
+}
diff --git a/lib/widgets/common/grid/sections/section_layout_builder.dart b/lib/widgets/common/grid/sections/section_layout_builder.dart
new file mode 100644
index 0000000..2be7e97
--- /dev/null
+++ b/lib/widgets/common/grid/sections/section_layout_builder.dart
@@ -0,0 +1,105 @@
+import 'package:aves/model/source/section_keys.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:aves/widgets/common/grid/sections/section_layout.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
+import 'package:provider/provider.dart';
+
+typedef TileBuilder<T> = Widget Function(T item, Size tileSize);
+
+abstract class SectionLayoutBuilder<T> {
+ final Map<SectionKey, List<T>> sections;
+ final bool showHeaders;
+ final double Function(BuildContext context, SectionKey sectionKey) getHeaderExtent;
+ final Widget Function(BuildContext context, SectionKey sectionKey, double headerExtent) buildHeader;
+ final double scrollableWidth;
+ final TileLayout tileLayout;
+ final int columnCount;
+ final double spacing, horizontalPadding, tileWidth, tileHeight, bottom;
+ final TileBuilder<T> tileBuilder;
+ final Duration tileAnimationDelay;
+ final bool animate;
+
+ const SectionLayoutBuilder({
+ required this.sections,
+ required this.showHeaders,
+ required this.getHeaderExtent,
+ required this.buildHeader,
+ required this.scrollableWidth,
+ required this.tileLayout,
+ required this.columnCount,
+ required this.spacing,
+ required this.horizontalPadding,
+ required this.tileWidth,
+ required this.tileHeight,
+ required this.tileBuilder,
+ required this.tileAnimationDelay,
+ }) : animate = tileAnimationDelay > Duration.zero,
+ bottom = tileHeight - tileWidth;
+
+ SectionedListLayout<T> updateLayouts(BuildContext context);
+
+ SectionLayout buildSectionLayout({
+ required double headerExtent,
+ required SectionKey sectionKey,
+ required List<T> section,
+ required bool animate,
+ });
+
+ Widget buildSectionWidget({
+ required BuildContext context,
+ required List<T> section,
+ required int sectionGridIndex,
+ required int sectionChildIndex,
+ required (int, int) Function() itemIndexRange,
+ required SectionKey sectionKey,
+ required double headerExtent,
+ required List<Size> itemSizes,
+ required bool animate,
+ required Widget Function(List<Widget> children) buildGridRow,
+ }) {
+ if (sectionChildIndex == 0) {
+ final header = headerExtent > 0 ? buildHeader(context, sectionKey, headerExtent) : const SizedBox();
+ return animate ? _buildAnimation(context, sectionGridIndex, header) : header;
+ }
+
+ final sectionItemCount = section.length;
+ final itemMinMax = itemIndexRange();
+ final minItemIndex = itemMinMax.$1.clamp(0, sectionItemCount);
+ final maxItemIndex = itemMinMax.$2.clamp(0, sectionItemCount);
+ final childrenCount = maxItemIndex - minItemIndex;
+ final children = <Widget>[];
+ for (var i = 0; i < childrenCount; i++) {
+ final item = RepaintBoundary(
+ child: tileBuilder(section[minItemIndex + i], itemSizes[i]),
+ );
+ if (animate) {
+ children.add(_buildAnimation(context, sectionGridIndex + i, item));
+ } else {
+ children.add(item);
+ }
+ }
+ return Padding(
+ padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
+ child: buildGridRow(children),
+ );
+ }
+
+ Widget _buildAnimation(BuildContext context, int index, Widget child) {
+ final durations = context.watch<DurationsData>();
+ return AnimationConfiguration.staggeredGrid(
+ position: index,
+ columnCount: tileLayout == TileLayout.mosaic ? 1 : columnCount,
+ duration: durations.staggeredAnimation,
+ delay: tileAnimationDelay,
+ child: SlideAnimation(
+ verticalOffset: 50.0,
+ child: FadeInAnimation(
+ child: child,
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/common/grid/selector.dart b/lib/widgets/common/grid/selector.dart
new file mode 100644
index 0000000..8f92217
--- /dev/null
+++ b/lib/widgets/common/grid/selector.dart
@@ -0,0 +1,244 @@
+import 'dart:async';
+import 'dart:math';
+
+import 'package:aves/model/selection.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/utils/math_utils.dart';
+import 'package:aves/widgets/common/basic/gestures/gesture_detector.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/sections/list_layout.dart';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+class GridSelectionGestureDetector<T> extends StatefulWidget {
+ final GlobalKey scrollableKey;
+ final bool selectable;
+ final List<T> items;
+ final ScrollController scrollController;
+ final ValueNotifier<double> appBarHeightNotifier;
+ final Widget child;
+
+ const GridSelectionGestureDetector({
+ super.key,
+ required this.scrollableKey,
+ this.selectable = true,
+ required this.items,
+ required this.scrollController,
+ required this.appBarHeightNotifier,
+ required this.child,
+ });
+
+ @override
+ State<GridSelectionGestureDetector<T>> createState() => _GridSelectionGestureDetectorState<T>();
+}
+
+class _GridSelectionGestureDetectorState<T> extends State<GridSelectionGestureDetector<T>> {
+ bool _pressing = false, _selecting = false;
+ late int _fromIndex, _lastToIndex;
+ late Offset _localPosition;
+ late EdgeInsets _scrollableInsets;
+ late double _scrollSpeedFactor;
+ Timer? _selectionUpdateTimer;
+ Timer? _scrollMonitoringTimer;
+ var _isScrolling = false;
+
+ List<T> get items => widget.items;
+
+ ScrollController get scrollController => widget.scrollController;
+
+ double get appBarHeight => widget.appBarHeightNotifier.value;
+
+ double get scrollableWidth {
+ final scrollableContext = widget.scrollableKey.currentContext!;
+ final scrollableBox = scrollableContext.findRenderObject() as RenderBox;
+ // not the same as `MediaQuery.size.width`, because of screen insets/padding
+ return scrollableBox.size.width;
+ }
+
+ static const double _scrollEdgeRatio = .15;
+ static const double _scrollMaxPixelPerSecond = 600.0;
+ static const Duration _scrollUpdateInterval = Duration(milliseconds: 100);
+
+ @override
+ void initState() {
+ super.initState();
+ _registerWidget(widget);
+ }
+
+ @override
+ void didUpdateWidget(covariant GridSelectionGestureDetector<T> oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ _unregisterWidget(oldWidget);
+ _registerWidget(widget);
+ }
+
+ @override
+ void dispose() {
+ _unregisterWidget(widget);
+ _stopScrollMonitoringTimer();
+ super.dispose();
+ }
+
+ void _registerWidget(GridSelectionGestureDetector<T> widget) {
+ widget.scrollController.addListener(_onScrollChanged);
+ }
+
+ void _unregisterWidget(GridSelectionGestureDetector<T> widget) {
+ widget.scrollController.removeListener(_onScrollChanged);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final selectable = widget.selectable;
+ return AGestureDetector(
+ onLongPressStart: selectable
+ ? (details) {
+ if (_isScrolling) return;
+
+ final fromItem = _getItemAt(details.localPosition);
+ if (fromItem == null) return;
+
+ Feedback.forLongPress(context);
+ final selection = context.read<Selection<T>>();
+ selection.toggleSelection(fromItem);
+ _selecting = selection.isSelected([fromItem]);
+ _fromIndex = items.indexOf(fromItem);
+ _lastToIndex = _fromIndex;
+ _scrollableInsets = EdgeInsets.only(
+ top: appBarHeight,
+ bottom: context.read<MediaQueryData>().effectiveBottomPadding,
+ );
+ _scrollSpeedFactor = 0;
+ _pressing = true;
+ }
+ : null,
+ onLongPressMoveUpdate: selectable
+ ? (details) {
+ if (!_pressing) return;
+ _localPosition = details.localPosition;
+ _onLongPressUpdate();
+ }
+ : null,
+ onLongPressEnd: selectable
+ ? (details) {
+ if (!_pressing) return;
+ _setScrollSpeed(0);
+ _pressing = false;
+ }
+ : null,
+ onTapUp: selectable && context.select<Selection<T>, bool>((selection) => selection.isSelecting)
+ ? (details) {
+ if (_isScrolling) return;
+
+ final item = _getItemAt(details.localPosition);
+ if (item == null) return;
+
+ final selection = context.read<Selection<T>>();
+ selection.toggleSelection(item);
+ }
+ : null,
+ longPressTimeout: settings.longPressTimeout,
+ child: widget.child,
+ );
+ }
+
+ void _onScrollChanged() {
+ _isScrolling = true;
+ _stopScrollMonitoringTimer();
+ _scrollMonitoringTimer = Timer(settings.longPressTimeout + const Duration(milliseconds: 150), () {
+ _isScrolling = false;
+ });
+ }
+
+ void _stopScrollMonitoringTimer() => _scrollMonitoringTimer?.cancel();
+
+ void _onLongPressUpdate() {
+ final dy = _localPosition.dy;
+
+ final height = scrollController.position.viewportDimension;
+ final top = dy < height / 2;
+
+ final distanceToEdge = max(0, top ? dy - _scrollableInsets.top : height - dy - _scrollableInsets.bottom);
+ final threshold = height * _scrollEdgeRatio;
+ if (distanceToEdge < threshold) {
+ _setScrollSpeed((top ? -1 : 1) * roundToPrecision((threshold - distanceToEdge) / threshold, decimals: 1));
+ } else {
+ _setScrollSpeed(0);
+ }
+
+ final toItem = _getItemAt(_localPosition);
+ if (toItem != null) {
+ _toggleSelectionToIndex(items.indexOf(toItem));
+ }
+ }
+
+ void _setScrollSpeed(double speedFactor) {
+ if (speedFactor == _scrollSpeedFactor) return;
+ _scrollSpeedFactor = speedFactor;
+ _selectionUpdateTimer?.cancel();
+
+ final current = scrollController.offset;
+ if (speedFactor == 0) {
+ scrollController.jumpTo(current);
+ return;
+ }
+
+ final target = speedFactor > 0 ? scrollController.position.maxScrollExtent : .0;
+ if (target != current) {
+ final distance = target - current;
+ final millis = distance * 1000 / _scrollMaxPixelPerSecond / speedFactor;
+ scrollController.animateTo(
+ target,
+ duration: Duration(milliseconds: millis.round()),
+ curve: Curves.linear,
+ );
+ // use a timer to update the selection, because `onLongPressMoveUpdate`
+ // is not called when the pointer stays still while the view is scrolling
+ _selectionUpdateTimer = Timer.periodic(_scrollUpdateInterval, (_) => _onLongPressUpdate());
+ }
+ }
+
+ T? _getItemAt(Offset localPosition) {
+ // as of Flutter v1.22.5, `hitTest` on the `ScrollView` render object works fine when it is static,
+ // but when it is scrolling (through controller animation), result is incomplete and children are missing,
+ // so we use custom layout computation instead to find the item.
+ final offset = Offset(0, scrollController.offset - appBarHeight) + localPosition;
+ final sectionedListLayout = context.read<SectionedListLayout<T>>();
+ return sectionedListLayout.getItemAt(context.isRtl ? Offset(scrollableWidth - offset.dx, offset.dy) : offset);
+ }
+
+ void _toggleSelectionToIndex(int toIndex) {
+ if (toIndex == -1) return;
+
+ Iterable<T> getRange(int start, int end) => start < end && 0 <= start && end <= items.length ? items.getRange(start, end) : {};
+ final selection = context.read<Selection<T>>();
+ void addRange(int start, int end) => selection.addToSelection(getRange(start, end));
+ void removeRange(int start, int end) => selection.removeFromSelection(getRange(start, end));
+
+ if (_selecting) {
+ if (toIndex <= _fromIndex) {
+ if (toIndex < _lastToIndex) {
+ addRange(toIndex, min(_fromIndex, _lastToIndex));
+ if (_fromIndex < _lastToIndex) {
+ removeRange(_fromIndex + 1, _lastToIndex + 1);
+ }
+ } else if (_lastToIndex < toIndex) {
+ removeRange(_lastToIndex, toIndex);
+ }
+ } else if (_fromIndex < toIndex) {
+ if (_lastToIndex < toIndex) {
+ addRange(max(_fromIndex, _lastToIndex), toIndex + 1);
+ if (_lastToIndex < _fromIndex) {
+ removeRange(_lastToIndex, _fromIndex);
+ }
+ } else if (toIndex < _lastToIndex) {
+ removeRange(toIndex + 1, _lastToIndex + 1);
+ }
+ }
+ _lastToIndex = toIndex;
+ } else {
+ removeRange(min(_fromIndex, toIndex), max(_fromIndex, toIndex) + 1);
+ }
+ }
+}
diff --git a/lib/widgets/common/grid/sliver.dart b/lib/widgets/common/grid/sliver.dart
new file mode 100644
index 0000000..3d7ed75
--- /dev/null
+++ b/lib/widgets/common/grid/sliver.dart
@@ -0,0 +1,264 @@
+import 'dart:math' as math;
+
+import 'package:aves/widgets/common/grid/sections/list_layout.dart';
+import 'package:aves/widgets/common/grid/sections/section_layout.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/widgets.dart';
+import 'package:provider/provider.dart';
+
+// Use a `SliverList` instead of multiple `SliverGrid` because having one `SliverGrid` per section does not scale up.
+// With the multiple `SliverGrid` solution, thumbnails at the beginning of each sections are built even though they are offscreen
+// because of `RenderSliverMultiBoxAdaptor.addInitialChild` called by `RenderSliverGrid.performLayout` (line 591), as of Flutter v3.3.3.
+// cf https://github.com/flutter/flutter/issues/49027
+// adapted from Flutter `RenderSliverFixedExtentBoxAdaptor` in `/rendering/sliver_fixed_extent_list.dart`
+class SectionedListSliver<T> extends StatelessWidget {
+ const SectionedListSliver({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final sectionLayouts = context.watch<SectionedListLayout<T>>().sectionLayouts;
+ final childCount = sectionLayouts.isEmpty ? 0 : sectionLayouts.last.lastIndex + 1;
+ return _SliverKnownExtentList(
+ sectionLayouts: sectionLayouts,
+ delegate: SliverChildBuilderDelegate(
+ (context, index) {
+ if (index >= childCount) return null;
+ final sectionLayout = sectionLayouts.firstWhereOrNull((section) => section.hasChild(index));
+ return sectionLayout?.builder(context, index) ?? const SizedBox();
+ },
+ childCount: childCount,
+ addAutomaticKeepAlives: false,
+ addRepaintBoundaries: false,
+ ),
+ );
+ }
+}
+
+class _SliverKnownExtentList extends SliverMultiBoxAdaptorWidget {
+ final List<SectionLayout> sectionLayouts;
+
+ const _SliverKnownExtentList({
+ required super.delegate,
+ required this.sectionLayouts,
+ });
+
+ @override
+ _RenderSliverKnownExtentBoxAdaptor createRenderObject(BuildContext context) {
+ final element = context as SliverMultiBoxAdaptorElement;
+ return _RenderSliverKnownExtentBoxAdaptor(childManager: element, sectionLayouts: sectionLayouts);
+ }
+
+ @override
+ void updateRenderObject(BuildContext context, _RenderSliverKnownExtentBoxAdaptor renderObject) {
+ renderObject.sectionLayouts = sectionLayouts;
+ }
+}
+
+class _RenderSliverKnownExtentBoxAdaptor extends RenderSliverMultiBoxAdaptor {
+ List<SectionLayout> _sectionLayouts;
+
+ List<SectionLayout> get sectionLayouts => _sectionLayouts;
+
+ set sectionLayouts(List<SectionLayout> value) {
+ if (_sectionLayouts == value) return;
+ _sectionLayouts = value;
+ markNeedsLayout();
+ }
+
+ _RenderSliverKnownExtentBoxAdaptor({
+ required super.childManager,
+ required List<SectionLayout> sectionLayouts,
+ }) : _sectionLayouts = sectionLayouts;
+
+ SectionLayout? sectionAtIndex(int index) => sectionLayouts.firstWhereOrNull((section) => section.hasChild(index));
+
+ SectionLayout? sectionAtOffset(double scrollOffset) => sectionLayouts.firstWhereOrNull((section) => section.hasChildAtOffset(scrollOffset)) ?? sectionLayouts.lastOrNull;
+
+ double indexToLayoutOffset(int index) {
+ return (sectionAtIndex(index) ?? sectionLayouts.lastOrNull)?.indexToLayoutOffset(index) ?? 0;
+ }
+
+ int getMinChildIndexForScrollOffset(double scrollOffset) {
+ return sectionAtOffset(scrollOffset)?.getMinChildIndexForScrollOffset(scrollOffset) ?? 0;
+ }
+
+ int getMaxChildIndexForScrollOffset(double scrollOffset) {
+ return sectionAtOffset(scrollOffset)?.getMaxChildIndexForScrollOffset(scrollOffset) ?? 0;
+ }
+
+ double estimateMaxScrollOffset(
+ SliverConstraints constraints, {
+ int? firstIndex,
+ int? lastIndex,
+ double? leadingScrollOffset,
+ double? trailingScrollOffset,
+ }) {
+ // default implementation is an estimation via `childManager.estimateMaxScrollOffset()`
+ // but we have the accurate offset via pre-computed section layouts
+ return _sectionLayouts.last.maxOffset;
+ }
+
+ double computeMaxScrollOffset(SliverConstraints constraints) {
+ return sectionLayouts.last.maxOffset;
+ }
+
+ int _calculateLeadingGarbage(int firstIndex) {
+ var walker = firstChild;
+ var leadingGarbage = 0;
+ while (walker != null && indexOf(walker) < firstIndex) {
+ leadingGarbage += 1;
+ walker = childAfter(walker);
+ }
+ return leadingGarbage;
+ }
+
+ int _calculateTrailingGarbage(int targetLastIndex) {
+ var walker = lastChild;
+ var trailingGarbage = 0;
+ while (walker != null && indexOf(walker) > targetLastIndex) {
+ trailingGarbage += 1;
+ walker = childBefore(walker);
+ }
+ return trailingGarbage;
+ }
+
+ @override
+ void performLayout() {
+ final constraints = this.constraints;
+ childManager.didStartLayout();
+ childManager.setDidUnderflow(false);
+
+ final scrollOffset = constraints.scrollOffset + constraints.cacheOrigin;
+ assert(scrollOffset >= 0.0);
+ final remainingExtent = constraints.remainingCacheExtent;
+ assert(remainingExtent >= 0.0);
+ final targetEndScrollOffset = scrollOffset + remainingExtent;
+
+ final childConstraints = constraints.asBoxConstraints();
+
+ final firstIndex = getMinChildIndexForScrollOffset(scrollOffset);
+ final targetLastIndex = targetEndScrollOffset.isFinite ? getMaxChildIndexForScrollOffset(targetEndScrollOffset) : null;
+
+ if (firstChild != null) {
+ final leadingGarbage = _calculateLeadingGarbage(firstIndex);
+ final trailingGarbage = targetLastIndex != null ? _calculateTrailingGarbage(targetLastIndex) : 0;
+ collectGarbage(leadingGarbage, trailingGarbage);
+ } else {
+ collectGarbage(0, 0);
+ }
+
+ if (firstChild == null) {
+ if (!addInitialChild(index: firstIndex, layoutOffset: indexToLayoutOffset(firstIndex))) {
+ // There are either no children, or we are past the end of all our children.
+ double max;
+ if (firstIndex <= 0) {
+ max = 0.0;
+ } else {
+ max = computeMaxScrollOffset(constraints);
+ }
+ geometry = SliverGeometry(
+ scrollExtent: max,
+ maxPaintExtent: max,
+ );
+ childManager.didFinishLayout();
+ return;
+ }
+ }
+
+ RenderBox? trailingChildWithLayout;
+
+ for (var index = indexOf(firstChild!) - 1; index >= firstIndex; --index) {
+ final child = insertAndLayoutLeadingChild(childConstraints);
+ if (child == null) {
+ // Items before the previously first child are no longer present.
+ // Reset the scroll offset to offset all items prior and up to the
+ // missing item. Let parent re-layout everything.
+ final layout = sectionAtIndex(index) ?? sectionLayouts.first;
+ geometry = SliverGeometry(scrollOffsetCorrection: layout.indexToLayoutOffset(index));
+ return;
+ }
+ final childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
+ childParentData.layoutOffset = indexToLayoutOffset(index);
+ assert(childParentData.index == index);
+ trailingChildWithLayout ??= child;
+ }
+
+ if (trailingChildWithLayout == null) {
+ firstChild!.layout(childConstraints);
+ final childParentData = firstChild!.parentData as SliverMultiBoxAdaptorParentData;
+ childParentData.layoutOffset = indexToLayoutOffset(firstIndex);
+ trailingChildWithLayout = firstChild;
+ }
+
+ var estimatedMaxScrollOffset = double.infinity;
+ for (var index = indexOf(trailingChildWithLayout!) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) {
+ var child = childAfter(trailingChildWithLayout!);
+ if (child == null || indexOf(child) != index) {
+ child = insertAndLayoutChild(childConstraints, after: trailingChildWithLayout);
+ if (child == null) {
+ // We have run out of children.
+ final layout = sectionAtIndex(index) ?? sectionLayouts.last;
+ estimatedMaxScrollOffset = layout.maxOffset;
+ break;
+ }
+ } else {
+ child.layout(childConstraints);
+ }
+ trailingChildWithLayout = child;
+ final childParentData = child.parentData as SliverMultiBoxAdaptorParentData;
+ assert(childParentData.index == index);
+ childParentData.layoutOffset = indexToLayoutOffset(childParentData.index!);
+ }
+
+ final lastIndex = indexOf(lastChild!);
+ final leadingScrollOffset = indexToLayoutOffset(firstIndex);
+ final trailingScrollOffset = indexToLayoutOffset(lastIndex + 1);
+
+ assert(firstIndex == 0 || childScrollOffset(firstChild!)! - scrollOffset <= precisionErrorTolerance);
+ assert(debugAssertChildListIsNonEmptyAndContiguous());
+ assert(indexOf(firstChild!) == firstIndex);
+ assert(targetLastIndex == null || lastIndex <= targetLastIndex);
+
+ estimatedMaxScrollOffset = math.min(
+ estimatedMaxScrollOffset,
+ estimateMaxScrollOffset(
+ constraints,
+ firstIndex: firstIndex,
+ lastIndex: lastIndex,
+ leadingScrollOffset: leadingScrollOffset,
+ trailingScrollOffset: trailingScrollOffset,
+ ),
+ );
+
+ final paintExtent = calculatePaintOffset(
+ constraints,
+ from: math.min(constraints.scrollOffset, leadingScrollOffset),
+ to: trailingScrollOffset,
+ );
+
+ final cacheExtent = calculateCacheOffset(
+ constraints,
+ from: leadingScrollOffset,
+ to: trailingScrollOffset,
+ );
+
+ final targetEndScrollOffsetForPaint = constraints.scrollOffset + constraints.remainingPaintExtent;
+ final targetLastIndexForPaint = targetEndScrollOffsetForPaint.isFinite ? getMaxChildIndexForScrollOffset(targetEndScrollOffsetForPaint) : null;
+ geometry = SliverGeometry(
+ scrollExtent: estimatedMaxScrollOffset,
+ paintExtent: math.min(paintExtent, estimatedMaxScrollOffset),
+ cacheExtent: cacheExtent,
+ maxPaintExtent: estimatedMaxScrollOffset,
+ // Conservative to avoid flickering away the clip during scroll.
+ hasVisualOverflow: (targetLastIndexForPaint != null && lastIndex >= targetLastIndexForPaint) || constraints.scrollOffset > 0.0,
+ );
+
+ // We may have started the layout while scrolled to the end, which would not
+ // expose a new child.
+ if (estimatedMaxScrollOffset == trailingScrollOffset) childManager.setDidUnderflow(true);
+ childManager.didFinishLayout();
+ }
+}
diff --git a/lib/widgets/common/grid/theme.dart b/lib/widgets/common/grid/theme.dart
new file mode 100644
index 0000000..55ca836
--- /dev/null
+++ b/lib/widgets/common/grid/theme.dart
@@ -0,0 +1,111 @@
+import 'dart:math';
+
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/extensions/favourites.dart';
+import 'package:aves/model/entry/extensions/multipage.dart';
+import 'package:aves/model/entry/extensions/props.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/widgets/common/identity/aves_icons.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+class GridTheme extends StatelessWidget {
+ final double extent;
+ final bool showLocation;
+ final bool? showTrash;
+ final Widget child;
+
+ const GridTheme({
+ super.key,
+ required this.extent,
+ this.showLocation = true,
+ this.showTrash,
+ required this.child,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return ProxyProvider2<Settings, MediaQueryData, GridThemeData>(
+ update: (context, settings, mq, previous) {
+ final margin = OverlayIcon.defaultMargin.vertical;
+ var iconSize = min<double>(24.0, ((extent - margin) / 5).floorToDouble() - margin);
+ final fontSize = (iconSize * .7).floorToDouble();
+ iconSize = mq.textScaler.scale(iconSize);
+ final highlightBorderWidth = extent * .1;
+ final interactiveDimension = min(iconSize * 2, kMinInteractiveDimension);
+ return GridThemeData(
+ iconSize: iconSize,
+ fontSize: fontSize,
+ highlightBorderWidth: highlightBorderWidth,
+ interactiveDimension: interactiveDimension,
+ showFavourite: settings.showThumbnailFavourite,
+ showHdr: settings.showThumbnailHdr,
+ locationIcon: showLocation ? settings.thumbnailLocationIcon : ThumbnailOverlayLocationIcon.none,
+ tagIcon: settings.thumbnailTagIcon,
+ showMotionPhoto: settings.showThumbnailMotionPhoto,
+ showRating: settings.showThumbnailRating,
+ showRaw: settings.showThumbnailRaw,
+ showTrash: showTrash ?? true,
+ showVideoDuration: settings.showThumbnailVideoDuration,
+ );
+ },
+ child: child,
+ );
+ }
+}
+
+typedef GridThemeIconBuilder = List<Widget> Function(BuildContext context, AvesEntry entry);
+
+class GridThemeData {
+ final double iconSize, fontSize, highlightBorderWidth, interactiveDimension;
+ final bool showFavourite, showHdr, showMotionPhoto, showRating, showRaw, showTrash, showVideoDuration;
+ final bool showLocated, showUnlocated, showTagged, showUntagged;
+ late final GridThemeIconBuilder iconBuilder;
+
+ GridThemeData({
+ required this.iconSize,
+ required this.fontSize,
+ required this.highlightBorderWidth,
+ required this.interactiveDimension,
+ required this.showFavourite,
+ required this.showHdr,
+ required ThumbnailOverlayLocationIcon locationIcon,
+ required ThumbnailOverlayTagIcon tagIcon,
+ required this.showMotionPhoto,
+ required this.showRating,
+ required this.showRaw,
+ required this.showTrash,
+ required this.showVideoDuration,
+ }) : showLocated = locationIcon == ThumbnailOverlayLocationIcon.located,
+ showUnlocated = locationIcon == ThumbnailOverlayLocationIcon.unlocated,
+ showTagged = tagIcon == ThumbnailOverlayTagIcon.tagged,
+ showUntagged = tagIcon == ThumbnailOverlayTagIcon.untagged {
+ iconBuilder = (context, entry) {
+ final located = entry.hasGps;
+ final tagged = entry.tags.isNotEmpty;
+ final isMultiPage = entry.isMultiPage;
+ return [
+ if (entry.isFavourite && showFavourite) const FavouriteIcon(),
+ if (tagged && showTagged) TagIcon.tagged(),
+ if (!tagged && showUntagged) TagIcon.untagged(),
+ if (located && showLocated) LocationIcon.located(),
+ if (!located && showUnlocated) LocationIcon.unlocated(),
+ if (entry.rating != 0 && showRating) RatingIcon(entry: entry),
+ if (entry.isHdr && showHdr) const HdrIcon(),
+ if (entry.isPureVideo)
+ VideoIcon(entry: entry)
+ else if (entry.isAnimated)
+ const AnimatedImageIcon()
+ else ...[
+ if ((entry.isRaw || (isMultiPage && entry.stackedEntries?.any((v) => v.isRaw) == true)) && showRaw) const RawIcon(),
+ if (entry.is360) const PanoramaIcon(),
+ ],
+ if (entry.isMotionPhoto && showMotionPhoto) const MotionPhotoIcon(),
+ if (isMultiPage && !entry.isMotionPhoto) MultiPageIcon(entry: entry),
+ if (entry.isGeotiff) const GeoTiffIcon(),
+ if (entry.trashed && showTrash) TrashIcon(trashDaysLeft: entry.trashDaysLeft),
+ ];
+ };
+ }
+}