diff options
| author | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
|---|---|---|
| committer | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
| commit | 449d8b74bd6d9dae98a07254cdfad677b920e7b0 (patch) | |
| tree | c131c3528c4d517f56e19b854a7453fedb097d40 /lib/widgets/common | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'lib/widgets/common')
156 files changed, 20023 insertions, 0 deletions
diff --git a/lib/widgets/common/action_controls/quick_choosers/album_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/album_chooser.dart new file mode 100644 index 0000000..da5a017 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/album_chooser.dart @@ -0,0 +1,51 @@ +import 'dart:async'; + +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/menu.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AlbumQuickChooser extends StatelessWidget with FilterQuickChooserMixin<String> { + final ValueNotifier<String?> valueNotifier; + @override + final List<String> options; + final bool blurred; + final PopupMenuPosition chooserPosition; + final Stream<Offset> pointerGlobalPosition; + + const AlbumQuickChooser({ + super.key, + required this.valueNotifier, + required this.options, + required this.blurred, + required this.chooserPosition, + required this.pointerGlobalPosition, + }); + + @override + Widget build(BuildContext context) { + return MenuQuickChooser<String>( + valueNotifier: valueNotifier, + options: options, + autoReverse: true, + blurred: blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + maxTotalOptionCount: FilterQuickChooserMixin.maxTotalOptionCount, + itemHeight: computeItemHeight(context), + contentWidth: computeLargestItemWidth, + itemBuilder: itemBuilder, + emptyBuilder: (context) => Text(context.l10n.albumEmpty), + ); + } + + @override + CollectionFilter buildFilter(BuildContext context, String option) { + final source = context.read<CollectionSource>(); + return StoredAlbumFilter(option, source.getStoredAlbumDisplayName(context, option)); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/common/button.dart b/lib/widgets/common/action_controls/quick_choosers/common/button.dart new file mode 100644 index 0000000..fadcaa8 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/common/button.dart @@ -0,0 +1,150 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/route_layout.dart'; +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +abstract class ChooserQuickButton<T> extends StatefulWidget { + final bool blurred; + final ValueSetter<T>? onChooserValue; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const ChooserQuickButton({ + super.key, + required this.blurred, + this.onChooserValue, + this.focusNode, + required this.onPressed, + }); +} + +abstract class ChooserQuickButtonState<T extends ChooserQuickButton<U>, U> extends State<T> with SingleTickerProviderStateMixin { + AnimationController? _animationController; + CurvedAnimation? _animation; + OverlayEntry? _chooserOverlayEntry; + final ValueNotifier<U?> _chooserValueNotifier = ValueNotifier(null); + final StreamController<LongPressMoveUpdateDetails> _moveUpdateStreamController = StreamController.broadcast(); + + Widget get icon; + + String get tooltip; + + U? get defaultValue => null; + + Duration get animationDuration => context.read<DurationsData>().quickChooserAnimation; + + Curve get animationCurve => Curves.easeOutQuad; + + bool get hasChooser => widget.onChooserValue != null; + + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition); + + ValueNotifier<U?> get chooserValueNotifier => _chooserValueNotifier; + + Stream<Offset> get pointerGlobalPosition => _moveUpdateStreamController.stream.map((event) => event.globalPosition); + + @override + void dispose() { + _animation?.dispose(); + _animationController?.dispose(); + _clearChooserOverlayEntry(); + _chooserValueNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final _hasChooser = hasChooser; + + Widget child = IconButton( + icon: icon, + onPressed: widget.onPressed, + focusNode: widget.focusNode, + tooltip: _hasChooser ? null : tooltip, + ); + if (_hasChooser) { + child = Semantics( + tooltip: tooltip, + child: child, + ); + } + + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + return Theme( + data: theme.copyWith( + colorScheme: colorScheme.copyWith( + onSurfaceVariant: colorScheme.onSurface, + ), + ), + child: AGestureDetector( + behavior: HitTestBehavior.opaque, + onLongPressStart: _hasChooser ? _showChooser : null, + onLongPressMoveUpdate: _hasChooser ? _moveUpdateStreamController.add : null, + onLongPressEnd: _hasChooser + ? (details) { + _clearChooserOverlayEntry(); + final selectedValue = _chooserValueNotifier.value; + if (selectedValue != null) { + widget.onChooserValue?.call(selectedValue); + } + } + : null, + onLongPressCancel: _clearChooserOverlayEntry, + longPressTimeout: settings.longPressTimeout, + child: child, + ), + ); + } + + void _clearChooserOverlayEntry() { + _chooserOverlayEntry + ?..remove() + ..dispose(); + _chooserOverlayEntry = null; + } + + void _showChooser(LongPressStartDetails details) { + final overlay = Overlay.of(context); + final triggerBox = context.findRenderObject() as RenderBox; + final overlayBox = overlay.context.findRenderObject() as RenderBox; + final triggerRect = RelativeRect.fromRect( + triggerBox.localToGlobal(Offset.zero, ancestor: overlayBox) & triggerBox.size, + Offset.zero & overlayBox.size, + ); + + _chooserValueNotifier.value = defaultValue; + _chooserOverlayEntry = OverlayEntry( + builder: (context) { + final mq = MediaQuery.of(context); + final chooserPosition = (details.globalPosition.dy > mq.size.height / 2) ? PopupMenuPosition.over : PopupMenuPosition.under; + return CustomSingleChildLayout( + delegate: QuickChooserRouteLayout( + triggerRect, + chooserPosition, + mq.padding, + DisplayFeatureSubScreen.avoidBounds(mq).toSet(), + ), + child: buildChooser(_animation!, chooserPosition), + ); + }, + ); + if (_animationController == null) { + _animationController = AnimationController( + duration: animationDuration, + vsync: this, + ); + _animation = CurvedAnimation( + parent: _animationController!, + curve: animationCurve, + ); + } + _animationController!.reset(); + overlay.insert(_chooserOverlayEntry!); + _animationController!.forward(); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/common/menu.dart b/lib/widgets/common/action_controls/quick_choosers/common/menu.dart new file mode 100644 index 0000000..6866085 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/common/menu.dart @@ -0,0 +1,318 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart'; +import 'package:aves_ui/aves_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +class MenuQuickChooser<T> extends StatefulWidget { + final ValueNotifier<T?> valueNotifier; + final List<T> options; + final bool autoReverse; + final bool blurred; + final PopupMenuPosition chooserPosition; + final Stream<Offset> pointerGlobalPosition; + final int maxTotalOptionCount; + final double itemHeight; + final double? Function(BuildContext context)? contentWidth; + final Widget Function(BuildContext context, T menuItem) itemBuilder; + final WidgetBuilder? emptyBuilder; + + static const int maxVisibleOptionCount = 5; + + MenuQuickChooser({ + super.key, + required this.valueNotifier, + required List<T> options, + required this.autoReverse, + required this.blurred, + required this.chooserPosition, + required this.pointerGlobalPosition, + this.maxTotalOptionCount = maxVisibleOptionCount, + this.itemHeight = kMinInteractiveDimension, + this.contentWidth, + required this.itemBuilder, + this.emptyBuilder, + }) : options = options.take(maxTotalOptionCount).toList(); + + @override + State<MenuQuickChooser<T>> createState() => _MenuQuickChooserState<T>(); +} + +class _MenuQuickChooserState<T> extends State<MenuQuickChooser<T>> { + final Set<StreamSubscription> _subscriptions = {}; + final ValueNotifier<Rect> _selectedRowRect = ValueNotifier(Rect.zero); + final ScrollController _scrollController = ScrollController(); + int _scrollDirection = 0; + Timer? _scrollUpdateTimer; + Offset _globalPosition = Offset.zero; + + ValueNotifier<T?> get valueNotifier => widget.valueNotifier; + + List<T> get options => widget.options; + + bool get reversed => widget.autoReverse && widget.chooserPosition == PopupMenuPosition.over; + + bool get scrollable => options.length > MenuQuickChooser.maxVisibleOptionCount; + + int get visibleOptionCount => min(MenuQuickChooser.maxVisibleOptionCount, options.length); + + double get itemHeight => widget.itemHeight; + + double get contentHeight => max(0, itemHeight * visibleOptionCount + _intraPadding * (visibleOptionCount - 1)); + + static const double _selectorMargin = 24; + static const double _intraPadding = 8; + static const double _nonScrollablePaddingHeight = _intraPadding; + static const double _scrollerAreaHeight = kMinInteractiveDimension; + static const double scrollMaxPixelPerSecond = 600.0; + static const Duration scrollUpdateInterval = Duration(milliseconds: 100); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {})); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _selectedRowRect.value = Rect.fromLTWH(0, MediaQuery.sizeOf(context).height * (reversed ? 1 : -1), 0, 0); + } + + @override + void didUpdateWidget(covariant MenuQuickChooser<T> oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _selectedRowRect.dispose(); + _scrollController.dispose(); + _scrollUpdateTimer?.cancel(); + super.dispose(); + } + + void _registerWidget(MenuQuickChooser<T> widget) { + _subscriptions.add(widget.pointerGlobalPosition.listen(_onPointerMove)); + } + + void _unregisterWidget(MenuQuickChooser<T> widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return QuickChooser( + blurred: widget.blurred, + child: ValueListenableBuilder<T?>( + valueListenable: valueNotifier, + builder: (context, selectedValue, child) { + final durations = context.watch<DurationsData>(); + + if (options.isEmpty) { + return Padding( + padding: const EdgeInsets.all(16), + child: widget.emptyBuilder?.call(context) ?? const SizedBox(), + ); + } + + return Stack( + children: [ + ValueListenableBuilder<Rect>( + valueListenable: _selectedRowRect, + builder: (context, selectedRowRect, child) { + Widget child = const Center(child: AvesDot()); + child = AnimatedOpacity( + opacity: selectedValue != null ? 1 : 0, + curve: Curves.easeInOutCubic, + duration: const Duration(milliseconds: 200), + child: child, + ); + child = AnimatedPositioned( + top: selectedRowRect.top, + height: selectedRowRect.height, + curve: Curves.easeInOutCubic, + duration: const Duration(milliseconds: 200), + child: child, + ); + return child; + }, + ), + Container( + width: widget.contentWidth?.call(context), + margin: const EdgeInsetsDirectional.only(start: _selectorMargin), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + scrollable + ? ListenableBuilder( + listenable: _scrollController, + builder: (context, child) => Opacity( + opacity: canGoUp ? 1 : .5, + child: child, + ), + child: _buildScrollerArea(AIcons.up), + ) + : const SizedBox(height: _nonScrollablePaddingHeight), + ConstrainedBox( + constraints: BoxConstraints.tightFor(height: contentHeight), + child: ListView.separated( + reverse: reversed, + controller: _scrollController, + shrinkWrap: true, + padding: EdgeInsets.zero, + itemBuilder: (context, index) { + final child = Container( + alignment: AlignmentDirectional.centerStart, + constraints: BoxConstraints.tightFor(height: itemHeight), + child: widget.itemBuilder(context, options[index]), + ); + if (index < MenuQuickChooser.maxVisibleOptionCount) { + // only animate items visible on first render + return AnimationConfiguration.staggeredList( + position: index, + duration: durations.staggeredAnimation * .5, + delay: durations.staggeredAnimationDelay * .5 * timeDilation, + child: SlideAnimation( + verticalOffset: 50.0 * (widget.chooserPosition == PopupMenuPosition.over ? 1 : -1), + child: FadeInAnimation( + child: child, + ), + ), + ); + } else { + return child; + } + }, + separatorBuilder: (context, index) => const SizedBox(height: _intraPadding), + itemCount: options.length, + ), + ), + scrollable + ? ListenableBuilder( + listenable: _scrollController, + builder: (context, child) => Opacity( + opacity: canGoDown ? 1 : .5, + child: child, + ), + child: _buildScrollerArea(AIcons.down), + ) + : const SizedBox(height: _nonScrollablePaddingHeight), + ], + ), + ), + ], + ); + }, + ), + ); + } + + bool get canGoUp { + if (!_scrollController.hasClients) return false; + final position = _scrollController.position; + if (!position.hasContentDimensions) return false; + return reversed ? position.pixels < position.maxScrollExtent : 0 < position.pixels; + } + + bool get canGoDown { + if (!_scrollController.hasClients) return false; + final position = _scrollController.position; + if (!position.hasContentDimensions) return false; + return reversed ? 0 < position.pixels : position.pixels < position.maxScrollExtent; + } + + Widget _buildScrollerArea(IconData icon) { + return Container( + alignment: Alignment.center, + height: _scrollerAreaHeight, + margin: const EdgeInsetsDirectional.only(end: _selectorMargin), + child: Icon(icon), + ); + } + + void _onPointerMove(Offset globalPosition) { + _globalPosition = globalPosition; + final chooserBox = context.findRenderObject() as RenderBox?; + if (chooserBox == null) return; + + final chooserSize = chooserBox.size; + final contentWidth = chooserSize.width; + final chooserBoxEdgeHeight = (QuickChooser.margin.vertical + QuickChooser.padding.vertical) / 2; + + final localPosition = chooserBox.globalToLocal(globalPosition); + final dx = localPosition.dx; + if (!(0 < dx && dx < contentWidth)) { + valueNotifier.value = null; + return; + } + + double dy = localPosition.dy - chooserBoxEdgeHeight; + int scrollDirection = 0; + if (scrollable) { + dy -= _scrollerAreaHeight; + if (-_scrollerAreaHeight < dy && dy < 0) { + scrollDirection = reversed ? 1 : -1; + } else if (contentHeight < dy && dy < contentHeight + _scrollerAreaHeight) { + scrollDirection = reversed ? -1 : 1; + } + _scroll(scrollDirection); + } else { + dy -= _nonScrollablePaddingHeight; + } + + T? selectedValue; + if (scrollDirection == 0 && 0 < dy && dy < contentHeight) { + final visibleOffset = reversed ? contentHeight - dy : dy; + final fullItemHeight = itemHeight + _intraPadding; + final scrollOffset = _scrollController.offset; + final index = (visibleOffset + _intraPadding + scrollOffset) ~/ (fullItemHeight); + if (0 <= index && index < options.length) { + selectedValue = options[index]; + double fromEdge = fullItemHeight * index; + fromEdge += (scrollable ? _scrollerAreaHeight - scrollOffset : _nonScrollablePaddingHeight); + final top = reversed ? chooserSize.height - chooserBoxEdgeHeight - fromEdge - fullItemHeight : fromEdge; + _selectedRowRect.value = Rect.fromLTWH(0, top, contentWidth, itemHeight); + } + } + valueNotifier.value = selectedValue; + } + + void _scroll(int scrollDirection) { + if (scrollDirection == _scrollDirection) return; + _scrollDirection = scrollDirection; + _scrollUpdateTimer?.cancel(); + + final current = _scrollController.offset; + if (scrollDirection == 0) { + _scrollController.jumpTo(current); + return; + } + + final target = scrollDirection > 0 ? _scrollController.position.maxScrollExtent : .0; + if (target != current) { + final distance = target - current; + final millis = distance * 1000 / scrollMaxPixelPerSecond / scrollDirection; + _scrollController.animateTo( + target, + duration: Duration(milliseconds: millis.round()), + curve: Curves.linear, + ); + // use a timer to update the selection, because `_onPointerMove` + // is not called when the pointer stays still while the view is scrolling + _scrollUpdateTimer = Timer.periodic(scrollUpdateInterval, (_) => _onPointerMove(_globalPosition)); + } + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart new file mode 100644 index 0000000..b1430d8 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart @@ -0,0 +1,47 @@ +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class QuickChooser extends StatelessWidget { + final bool blurred; + final Widget child; + + static const margin = EdgeInsets.all(8); + static const padding = EdgeInsets.symmetric(horizontal: 8); + + const QuickChooser({ + super.key, + required this.blurred, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final brightness = Theme.of(context).brightness; + final backgroundColor = blurred ? Themes.overlayBackgroundColor(brightness: brightness, blurred: blurred) : null; + const borderRadius = BorderRadius.all(AvesDialog.cornerRadius); + return Padding( + padding: margin, + child: BlurredRRect( + enabled: blurred, + borderRadius: borderRadius, + child: Material( + borderRadius: borderRadius, + color: backgroundColor, + child: Ink( + decoration: BoxDecoration( + border: AvesBorder.border(context), + borderRadius: borderRadius, + ), + child: Padding( + padding: padding, + child: child, + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/common/route_layout.dart b/lib/widgets/common/action_controls/quick_choosers/common/route_layout.dart new file mode 100644 index 0000000..835f691 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/common/route_layout.dart @@ -0,0 +1,80 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +// adapted from Flutter `_PopupMenuRouteLayout` in `/material/popup_menu.dart` +class QuickChooserRouteLayout extends SingleChildLayoutDelegate { + final RelativeRect triggerRect; + final PopupMenuPosition menuPosition; + final EdgeInsets padding; + final Set<Rect> avoidBounds; + + static const double _kMenuScreenPadding = 8.0; + + QuickChooserRouteLayout( + this.triggerRect, + this.menuPosition, + this.padding, + this.avoidBounds, + ); + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + return BoxConstraints.loose(constraints.biggest).deflate( + const EdgeInsets.all(_kMenuScreenPadding) + padding, + ); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + // size: The size of the overlay. + // childSize: The size of the menu, when fully open, as determined by getConstraintsForChild. + + double y; + switch (menuPosition) { + case PopupMenuPosition.over: + y = triggerRect.top - childSize.height; + case PopupMenuPosition.under: + y = size.height - triggerRect.bottom; + } + double x = (triggerRect.left + (size.width - triggerRect.right) - childSize.width) / 2; + final wantedPosition = Offset(x, y); + final originCenter = triggerRect.toRect(Offset.zero & size).center; + final subScreens = DisplayFeatureSubScreen.subScreensInBounds(Offset.zero & size, avoidBounds); + final subScreen = _closestScreen(subScreens, originCenter); + return _fitInsideScreen(subScreen, childSize, wantedPosition); + } + + Rect _closestScreen(Iterable<Rect> screens, Offset point) { + Rect closest = screens.first; + for (final Rect screen in screens) { + if ((screen.center - point).distance < (closest.center - point).distance) { + closest = screen; + } + } + return closest; + } + + Offset _fitInsideScreen(Rect screen, Size childSize, Offset wantedPosition) { + double x = wantedPosition.dx; + double y = wantedPosition.dy; + // Avoid going outside an area defined as the rectangle 8.0 pixels from the + // edge of the screen in every direction. + if (x < screen.left + _kMenuScreenPadding + padding.left) { + x = screen.left + _kMenuScreenPadding + padding.left; + } else if (x + childSize.width > screen.right - _kMenuScreenPadding - padding.right) { + x = screen.right - childSize.width - _kMenuScreenPadding - padding.right; + } + if (y < screen.top + _kMenuScreenPadding + padding.top) { + y = _kMenuScreenPadding + padding.top; + } else if (y + childSize.height > screen.bottom - _kMenuScreenPadding - padding.bottom) { + y = screen.bottom - childSize.height - _kMenuScreenPadding - padding.bottom; + } + + return Offset(x, y); + } + + @override + bool shouldRelayout(QuickChooserRouteLayout oldDelegate) { + return triggerRect != oldDelegate.triggerRect || padding != oldDelegate.padding || !setEquals(avoidBounds, oldDelegate.avoidBounds); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart b/lib/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart new file mode 100644 index 0000000..93c9eeb --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart @@ -0,0 +1,56 @@ +import 'dart:math'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/modules/app.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +mixin FilterQuickChooserMixin<T> { + List<T> get options; + + static const int maxTotalOptionCount = AppSettings.recentFilterHistoryMax; + static const double _chipPadding = AvesFilterChip.defaultPadding; + static const bool _chipAllowGenericIcon = false; + + CollectionFilter buildFilter(BuildContext context, T option); + + Widget itemBuilder(BuildContext context, T option) { + return AvesFilterChip( + filter: buildFilter(context, option), + allowGenericIcon: _chipAllowGenericIcon, + padding: _chipPadding, + maxWidth: double.infinity, + ); + } + + double computeItemHeight(BuildContext context) => AvesFilterChip.minChipHeight; + + double? computeLargestItemWidth(BuildContext context) { + if (options.isEmpty) return null; + + final textStyle = DefaultTextStyle.of(context).style.copyWith( + fontSize: AvesFilterChip.fontSize, + ); + final textDirection = Directionality.of(context); + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = textScaler.scale(AvesFilterChip.iconSize); + + return options.map((option) { + final filter = buildFilter(context, option); + final icon = filter.iconBuilder(context, iconSize, allowGenericIcon: _chipAllowGenericIcon); + final label = filter.getLabel(context); + final paragraph = RenderParagraph( + TextSpan(text: label, style: textStyle), + textDirection: textDirection, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final labelWidth = paragraph.getMaxIntrinsicWidth(double.infinity); + double chipWidth = labelWidth + _chipPadding * 4; + if (icon != null) { + chipWidth += iconSize + _chipPadding; + } + return max(AvesFilterChip.minChipWidth, chipWidth); + }).reduce(max); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/move_button.dart b/lib/widgets/common/action_controls/quick_choosers/move_button.dart new file mode 100644 index 0000000..a3cc61b --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/move_button.dart @@ -0,0 +1,70 @@ +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/album_chooser.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MoveButton extends ChooserQuickButton<String> { + final bool copy; + + const MoveButton({ + super.key, + required this.copy, + required super.blurred, + super.onChooserValue, + required super.onPressed, + }); + + @override + State<MoveButton> createState() => _MoveButtonState(); +} + +class _MoveButtonState extends ChooserQuickButtonState<MoveButton, String> { + EntryAction get action => widget.copy ? EntryAction.copy : EntryAction.move; + + @override + Widget get icon => action.getIcon(); + + @override + String get tooltip => action.getText(context); + + @override + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition) { + final source = context.read<CollectionSource>(); + final rawAlbums = source.rawAlbums; + final options = settings.recentDestinationAlbums.where(rawAlbums.contains).toList(); + final takeCount = FilterQuickChooserMixin.maxTotalOptionCount - options.length; + if (takeCount > 0) { + final filters = rawAlbums.whereNot(options.contains).map((album) => StoredAlbumFilter(album, null)).toSet(); + final allMapEntries = filters.map((filter) => FilterGridItem(filter, source.recentEntry(filter))).toList(); + allMapEntries.sort(FilterNavigationPage.compareFiltersByDate); + options.addAll(allMapEntries.take(takeCount).map((v) => v.filter.album)); + } + + return MediaQueryDataProvider( + child: FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + alignment: chooserPosition == PopupMenuPosition.over ? Alignment.bottomCenter : Alignment.topCenter, + child: AlbumQuickChooser( + valueNotifier: chooserValueNotifier, + options: options, + blurred: widget.blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/rate_button.dart b/lib/widgets/common/action_controls/quick_choosers/rate_button.dart new file mode 100644 index 0000000..874e2bf --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/rate_button.dart @@ -0,0 +1,47 @@ +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/rate_chooser.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class RateButton extends ChooserQuickButton<int> { + const RateButton({ + super.key, + required super.blurred, + super.onChooserValue, + super.focusNode, + required super.onPressed, + }); + + @override + State<RateButton> createState() => _RateButtonState(); +} + +class _RateButtonState extends ChooserQuickButtonState<RateButton, int> { + static const _action = EntryAction.editRating; + + @override + Widget get icon => _action.getIcon(); + + @override + String get tooltip => _action.getText(context); + + @override + int? get defaultValue => 3; + + @override + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition) { + return FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + alignment: chooserPosition == PopupMenuPosition.over ? Alignment.bottomCenter : Alignment.topCenter, + child: RateQuickChooser( + blurred: widget.blurred, + valueNotifier: chooserValueNotifier, + pointerGlobalPosition: pointerGlobalPosition, + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/rate_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/rate_chooser.dart new file mode 100644 index 0000000..687d4ea --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/rate_chooser.dart @@ -0,0 +1,100 @@ +import 'dart:async'; + +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class RateQuickChooser extends StatefulWidget { + final bool blurred; + final ValueNotifier<int?> valueNotifier; + final Stream<Offset> pointerGlobalPosition; + + const RateQuickChooser({ + super.key, + required this.blurred, + required this.valueNotifier, + required this.pointerGlobalPosition, + }); + + @override + State<RateQuickChooser> createState() => _RateQuickChooserState(); +} + +class _RateQuickChooserState extends State<RateQuickChooser> { + final Set<StreamSubscription> _subscriptions = {}; + + ValueNotifier<int?> get valueNotifier => widget.valueNotifier; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant RateQuickChooser oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(RateQuickChooser widget) { + _subscriptions.add(widget.pointerGlobalPosition.listen(_onPointerMove)); + } + + void _unregisterWidget(RateQuickChooser widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return QuickChooser( + blurred: widget.blurred, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: ValueListenableBuilder<int?>( + valueListenable: valueNotifier, + builder: (context, selectedValue, child) { + final _rating = selectedValue ?? 0; + return Row( + mainAxisSize: MainAxisSize.min, + children: List.generate(5, (i) { + final disabled = _rating < i + 1; + return Padding( + padding: const EdgeInsets.all(4), + child: Icon( + AIcons.rating, + fill: disabled ? 0 : 1, + color: disabled ? AColors.starDisabled : AColors.starEnabled, + ), + ); + }).toList(), + ); + }, + ), + ), + ); + } + + void _onPointerMove(Offset globalPosition) { + final padding = QuickChooser.margin.horizontal + QuickChooser.padding.horizontal; + + final chooserBox = context.findRenderObject() as RenderBox; + final chooserSize = chooserBox.size; + final contentWidth = chooserSize.width - padding; + + final local = chooserBox.globalToLocal(globalPosition); + final t = (local.dx - padding / 2) / contentWidth; + valueNotifier.value = (5 * (context.isRtl ? 1 - t : t)).ceil().clamp(0, 5); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/share_button.dart b/lib/widgets/common/action_controls/quick_choosers/share_button.dart new file mode 100644 index 0000000..df22d7b --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/share_button.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/share_chooser.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class ShareButton extends ChooserQuickButton<ShareAction> { + final Set<AvesEntry> entries; + + const ShareButton({ + super.key, + required super.blurred, + required this.entries, + super.onChooserValue, + super.focusNode, + required super.onPressed, + }); + + @override + State<ShareButton> createState() => _ShareButtonState(); +} + +class _ShareButtonState extends ChooserQuickButtonState<ShareButton, ShareAction> { + EntryAction get action => EntryAction.share; + + @override + Widget get icon => action.getIcon(); + + @override + String get tooltip => action.getText(context); + + @override + bool get hasChooser => super.hasChooser && options.isNotEmpty; + + List<ShareAction> get options => [ + if (widget.entries.any((entry) => entry.isMotionPhoto)) ...[ + ShareAction.imageOnly, + ShareAction.videoOnly, + ], + ]; + + @override + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition) { + return FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + alignment: chooserPosition == PopupMenuPosition.over ? Alignment.bottomCenter : Alignment.topCenter, + child: ShareQuickChooser( + valueNotifier: chooserValueNotifier, + options: options, + blurred: widget.blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/share_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/share_chooser.dart new file mode 100644 index 0000000..43ffbea --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/share_chooser.dart @@ -0,0 +1,69 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/menu.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +class ShareQuickChooser extends StatelessWidget { + final ValueNotifier<ShareAction?> valueNotifier; + final List<ShareAction> options; + final bool blurred; + final PopupMenuPosition chooserPosition; + final Stream<Offset> pointerGlobalPosition; + + static const _itemPadding = EdgeInsetsDirectional.only(end: 8); + + const ShareQuickChooser({ + super.key, + required this.valueNotifier, + required this.options, + required this.blurred, + required this.chooserPosition, + required this.pointerGlobalPosition, + }); + + @override + Widget build(BuildContext context) { + return MenuQuickChooser<ShareAction>( + valueNotifier: valueNotifier, + options: options, + autoReverse: false, + blurred: blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + itemHeight: kMinInteractiveDimension, + contentWidth: _computeLargestItemWidth, + itemBuilder: (context, action) => Padding( + padding: _itemPadding, + child: MenuRow( + text: action.getText(context), + icon: action.getIcon(), + ), + ), + ); + } + + double? _computeLargestItemWidth(BuildContext context) { + if (options.isEmpty) return null; + + final textStyle = DefaultTextStyle.of(context).style; + final textDirection = Directionality.of(context); + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = IconTheme.of(context).size ?? 24; + + return options.map((action) { + final text = action.getText(context); + final paragraph = RenderParagraph( + TextSpan(text: text, style: textStyle), + textDirection: textDirection, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final labelWidth = paragraph.getMaxIntrinsicWidth(double.infinity); + return iconSize + MenuRow.leadingPadding.horizontal + labelWidth + _itemPadding.horizontal; + }).reduce(max); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/tag_button.dart b/lib/widgets/common/action_controls/quick_choosers/tag_button.dart new file mode 100644 index 0000000..8de2068 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/tag_button.dart @@ -0,0 +1,76 @@ +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/tag_chooser.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class TagButton extends ChooserQuickButton<CollectionFilter> { + const TagButton({ + super.key, + required super.blurred, + super.onChooserValue, + super.focusNode, + required super.onPressed, + }); + + @override + State<TagButton> createState() => _TagButtonState(); +} + +class _TagButtonState extends ChooserQuickButtonState<TagButton, CollectionFilter> { + EntryAction get action => EntryAction.editTags; + + @override + Widget get icon => action.getIcon(); + + @override + String get tooltip => action.getText(context); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + final source = context.read<CollectionSource?>(); + settings.removeObsoleteRecentTags(source); + }); + } + + @override + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition) { + final options = settings.recentTags; + final takeCount = FilterQuickChooserMixin.maxTotalOptionCount - options.length; + if (takeCount > 0) { + final source = context.read<CollectionSource>(); + final filters = source.sortedTags.map(TagFilter.new).whereNot(options.contains).toSet(); + final allMapEntries = filters.map((filter) => FilterGridItem(filter, source.recentEntry(filter))).toList(); + allMapEntries.sort(FilterNavigationPage.compareFiltersByDate); + options.addAll(allMapEntries.take(takeCount).map((v) => v.filter)); + } + + return MediaQueryDataProvider( + child: FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + alignment: chooserPosition == PopupMenuPosition.over ? Alignment.bottomCenter : Alignment.topCenter, + child: TagQuickChooser( + valueNotifier: chooserValueNotifier, + options: options, + blurred: widget.blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/tag_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/tag_chooser.dart new file mode 100644 index 0000000..1b139e5 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/tag_chooser.dart @@ -0,0 +1,45 @@ +import 'dart:async'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/menu.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class TagQuickChooser extends StatelessWidget with FilterQuickChooserMixin<CollectionFilter> { + final ValueNotifier<CollectionFilter?> valueNotifier; + @override + final List<CollectionFilter> options; + final bool blurred; + final PopupMenuPosition chooserPosition; + final Stream<Offset> pointerGlobalPosition; + + const TagQuickChooser({ + super.key, + required this.valueNotifier, + required this.options, + required this.blurred, + required this.chooserPosition, + required this.pointerGlobalPosition, + }); + + @override + Widget build(BuildContext context) { + return MenuQuickChooser<CollectionFilter>( + valueNotifier: valueNotifier, + options: options, + autoReverse: true, + blurred: blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + maxTotalOptionCount: FilterQuickChooserMixin.maxTotalOptionCount, + itemHeight: computeItemHeight(context), + contentWidth: computeLargestItemWidth, + itemBuilder: itemBuilder, + emptyBuilder: (context) => Text(context.l10n.tagEmpty), + ); + } + + @override + CollectionFilter buildFilter(BuildContext context, CollectionFilter option) => option; +} diff --git a/lib/widgets/common/action_controls/togglers/favourite.dart b/lib/widgets/common/action_controls/togglers/favourite.dart new file mode 100644 index 0000000..cfc28d7 --- /dev/null +++ b/lib/widgets/common/action_controls/togglers/favourite.dart @@ -0,0 +1,162 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/sweeper.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class FavouriteToggler extends StatefulWidget { + final Set<AvesEntry> entries; + final bool isMenuItem; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const FavouriteToggler({ + super.key, + required this.entries, + this.isMenuItem = false, + this.focusNode, + this.onPressed, + }); + + @override + State<FavouriteToggler> createState() => _FavouriteTogglerState(); +} + +class _FavouriteTogglerState extends State<FavouriteToggler> { + final ValueNotifier<bool> _isFavouriteNotifier = ValueNotifier(false); + + Set<AvesEntry> get entries => widget.entries; + + static const isFavouriteIcon = Icon(AIcons.favourite, fill: 1); + static const isNotFavouriteIcon = Icon(AIcons.favourite, fill: 0); + + @override + void initState() { + super.initState(); + favourites.addListener(_onChanged); + _onChanged(); + } + + @override + void didUpdateWidget(covariant FavouriteToggler oldWidget) { + super.didUpdateWidget(oldWidget); + _onChanged(); + } + + @override + void dispose() { + favourites.removeListener(_onChanged); + _isFavouriteNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<bool>( + valueListenable: _isFavouriteNotifier, + builder: (context, isFavourite, child) { + if (widget.isMenuItem) { + return isFavourite + ? MenuRow( + text: context.l10n.entryActionRemoveFavourite, + icon: isFavouriteIcon, + ) + : MenuRow( + text: context.l10n.entryActionAddFavourite, + icon: isNotFavouriteIcon, + ); + } + final animate = context.select<Settings, bool>((v) => v.animate); + return Stack( + alignment: Alignment.center, + children: [ + IconButton( + icon: isFavourite ? isFavouriteIcon : isNotFavouriteIcon, + onPressed: widget.onPressed, + focusNode: widget.focusNode, + tooltip: isFavourite ? context.l10n.entryActionRemoveFavourite : context.l10n.entryActionAddFavourite, + ), + if (animate) + Sweeper( + key: ValueKey(entries.length == 1 ? entries.first : entries.length), + builder: (context) => Icon( + AIcons.favourite, + fill: 0, + color: context.select<AvesColorsData, Color>((v) => v.favourite), + ), + toggledNotifier: _isFavouriteNotifier, + ), + ], + ); + }, + ); + } + + void _onChanged() { + _isFavouriteNotifier.value = entries.isNotEmpty && entries.every((entry) => entry.isFavourite); + } +} + +class FavouriteTogglerCaption extends StatefulWidget { + final Set<AvesEntry> entries; + final bool enabled; + + const FavouriteTogglerCaption({ + super.key, + required this.entries, + required this.enabled, + }); + + @override + State<FavouriteTogglerCaption> createState() => _FavouriteTogglerCaptionState(); +} + +class _FavouriteTogglerCaptionState extends State<FavouriteTogglerCaption> { + final ValueNotifier<bool> _isFavouriteNotifier = ValueNotifier(false); + + Set<AvesEntry> get entries => widget.entries; + + @override + void initState() { + super.initState(); + favourites.addListener(_onChanged); + _onChanged(); + } + + @override + void didUpdateWidget(covariant FavouriteTogglerCaption oldWidget) { + super.didUpdateWidget(oldWidget); + _onChanged(); + } + + @override + void dispose() { + favourites.removeListener(_onChanged); + _isFavouriteNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<bool>( + valueListenable: _isFavouriteNotifier, + builder: (context, isFavourite, child) { + return CaptionedButtonText( + text: isFavourite ? context.l10n.entryActionRemoveFavourite : context.l10n.entryActionAddFavourite, + enabled: widget.enabled, + ); + }, + ); + } + + void _onChanged() { + _isFavouriteNotifier.value = entries.isNotEmpty && entries.every((entry) => entry.isFavourite); + } +} diff --git a/lib/widgets/common/action_controls/togglers/mute.dart b/lib/widgets/common/action_controls/togglers/mute.dart new file mode 100644 index 0000000..caff772 --- /dev/null +++ b/lib/widgets/common/action_controls/togglers/mute.dart @@ -0,0 +1,87 @@ +import 'dart:async'; + +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; + +class MuteToggler extends StatelessWidget { + final AvesVideoController? controller; + final bool isMenuItem; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const MuteToggler({ + super.key, + required this.controller, + this.isMenuItem = false, + this.focusNode, + this.onPressed, + }); + + bool get isMuted => controller?.isMuted ?? false; + + @override + Widget build(BuildContext context) { + return NullableValueListenableBuilder<bool>( + valueListenable: controller?.canMuteNotifier, + builder: (context, value, child) { + final canDo = value ?? false; + return StreamBuilder<double>( + stream: controller?.volumeStream ?? Stream.value(1.0), + builder: (context, snapshot) { + final icon = Icon(isMuted ? AIcons.unmute : AIcons.mute); + final text = isMuted ? context.l10n.videoActionUnmute : context.l10n.videoActionMute; + + return isMenuItem + ? MenuRow( + text: text, + icon: icon, + ) + : IconButton( + icon: icon, + onPressed: canDo ? onPressed : null, + focusNode: focusNode, + tooltip: text, + ); + }, + ); + }, + ); + } +} + +class MuteTogglerCaption extends StatelessWidget { + final AvesVideoController? controller; + final bool enabled; + + const MuteTogglerCaption({ + super.key, + required this.controller, + required this.enabled, + }); + + bool get isMuted => controller?.isMuted ?? false; + + @override + Widget build(BuildContext context) { + return NullableValueListenableBuilder<bool>( + valueListenable: controller?.canMuteNotifier, + builder: (context, value, child) { + final canDo = value ?? false; + return StreamBuilder<double>( + stream: controller?.volumeStream ?? Stream.value(1.0), + builder: (context, snapshot) { + return CaptionedButtonText( + text: isMuted ? context.l10n.videoActionUnmute : context.l10n.videoActionMute, + enabled: canDo && enabled, + ); + }, + ); + }, + ); + } +} diff --git a/lib/widgets/common/action_controls/togglers/play.dart b/lib/widgets/common/action_controls/togglers/play.dart new file mode 100644 index 0000000..67c5a5b --- /dev/null +++ b/lib/widgets/common/action_controls/togglers/play.dart @@ -0,0 +1,130 @@ +import 'dart:async'; + +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class PlayToggler extends StatefulWidget { + final AvesVideoController? controller; + final bool isMenuItem; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const PlayToggler({ + super.key, + required this.controller, + this.isMenuItem = false, + this.focusNode, + this.onPressed, + }); + + @override + State<PlayToggler> createState() => _PlayTogglerState(); +} + +class _PlayTogglerState extends State<PlayToggler> with SingleTickerProviderStateMixin { + final Set<StreamSubscription> _subscriptions = {}; + late AnimationController _playPauseAnimation; + + AvesVideoController? get controller => widget.controller; + + bool get isPlaying => controller?.isPlaying ?? false; + + @override + void initState() { + super.initState(); + _playPauseAnimation = AnimationController( + duration: context.read<DurationsData>().iconAnimation, + vsync: this, + ); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant PlayToggler oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _playPauseAnimation.dispose(); + super.dispose(); + } + + void _registerWidget(PlayToggler widget) { + final controller = widget.controller; + if (controller != null) { + _subscriptions.add(controller.statusStream.listen(_onStatusChanged)); + _onStatusChanged(controller.status); + } + } + + void _unregisterWidget(PlayToggler widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + final text = isPlaying ? context.l10n.videoActionPause : context.l10n.videoActionPlay; + + return widget.isMenuItem + ? MenuRow( + text: text, + icon: Icon(isPlaying ? AIcons.pause : AIcons.play), + ) + : IconButton( + icon: AnimatedIcon( + icon: AnimatedIcons.play_pause, + progress: _playPauseAnimation, + ), + onPressed: widget.onPressed, + focusNode: widget.focusNode, + tooltip: text, + ); + } + + void _onStatusChanged(VideoStatus status) { + final status = _playPauseAnimation.status; + if (isPlaying && !status.isForwardOrCompleted) { + _playPauseAnimation.forward(); + } else if (!isPlaying && status.isForwardOrCompleted) { + _playPauseAnimation.reverse(); + } + } +} + +class PlayTogglerCaption extends StatelessWidget { + final AvesVideoController? controller; + final bool enabled; + + const PlayTogglerCaption({ + super.key, + required this.controller, + required this.enabled, + }); + + bool get isPlaying => controller?.isPlaying ?? false; + + @override + Widget build(BuildContext context) { + return StreamBuilder<VideoStatus>( + stream: controller?.statusStream ?? Stream.value(VideoStatus.idle), + builder: (context, snapshot) { + return CaptionedButtonText( + text: isPlaying ? context.l10n.videoActionPause : context.l10n.videoActionPlay, + enabled: enabled, + ); + }, + ); + } +} diff --git a/lib/widgets/common/action_controls/togglers/title_search.dart b/lib/widgets/common/action_controls/togglers/title_search.dart new file mode 100644 index 0000000..b7badcd --- /dev/null +++ b/lib/widgets/common/action_controls/togglers/title_search.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/query.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class TitleSearchToggler extends StatelessWidget { + final bool queryEnabled, isMenuItem; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const TitleSearchToggler({ + super.key, + required this.queryEnabled, + this.isMenuItem = false, + this.focusNode, + this.onPressed, + }); + + @override + Widget build(BuildContext context) { + final icon = Icon(queryEnabled ? AIcons.filterOff : AIcons.filter); + final text = queryEnabled ? context.l10n.collectionActionHideTitleSearch : context.l10n.collectionActionShowTitleSearch; + return isMenuItem + ? MenuRow( + text: text, + icon: icon, + ) + : IconButton( + icon: icon, + onPressed: onPressed, + focusNode: focusNode, + tooltip: text, + ); + } +} + +class TitleSearchTogglerCaption extends StatelessWidget { + final bool enabled; + + const TitleSearchTogglerCaption({ + super.key, + required this.enabled, + }); + + @override + Widget build(BuildContext context) { + // `Query` may not be available during hero + return Selector<Query?, bool>( + selector: (context, query) => query?.enabled ?? false, + builder: (context, queryEnabled, child) { + return CaptionedButtonText( + text: queryEnabled ? context.l10n.collectionActionHideTitleSearch : context.l10n.collectionActionShowTitleSearch, + enabled: enabled, + ); + }, + ); + } +} diff --git a/lib/widgets/common/action_mixins/entry_editor.dart b/lib/widgets/common/action_mixins/entry_editor.dart new file mode 100644 index 0000000..4e3c937 --- /dev/null +++ b/lib/widgets/common/action_mixins/entry_editor.dart @@ -0,0 +1,144 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/metadata_edition.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/placeholder.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_date_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_description_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_location_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_rating_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/remove_metadata_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/tag_editor_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +mixin EntryEditorMixin { + Future<DateModifier?> selectDateModifier(BuildContext context, Set<AvesEntry> entries, CollectionLens? collection) async { + if (entries.isEmpty) return null; + + return showDialog<DateModifier>( + context: context, + builder: (context) => EditEntryDateDialog( + entry: entries.first, + collection: collection, + ), + routeSettings: const RouteSettings(name: EditEntryDateDialog.routeName), + ); + } + + Future<LocationEditActionResult?> selectLocation(BuildContext context, Set<AvesEntry> entries, CollectionLens? collection) async { + if (entries.isEmpty) return null; + + return showDialog<LocationEditActionResult>( + context: context, + builder: (context) => EditEntryLocationDialog( + entries: entries, + collection: collection, + ), + routeSettings: const RouteSettings(name: EditEntryLocationDialog.routeName), + ); + } + + Future<Map<DescriptionField, String?>?> selectTitleDescriptionModifier(BuildContext context, Set<AvesEntry> entries) async { + if (entries.isEmpty) return null; + + final entry = entries.first; + final initialTitle = entry.catalogMetadata?.xmpTitle ?? ''; + final fields = await metadataFetchService.getOverlayMetadata(entry, {MetadataSyntheticField.description}); + final initialDescription = fields.description ?? ''; + + return showDialog<Map<DescriptionField, String?>>( + context: context, + builder: (context) => EditEntryTitleDescriptionDialog( + initialTitle: initialTitle, + initialDescription: initialDescription, + ), + routeSettings: const RouteSettings(name: EditEntryTitleDescriptionDialog.routeName), + ); + } + + Future<int?> selectRating(BuildContext context, Set<AvesEntry> entries) async { + if (entries.isEmpty) return null; + + return showDialog<int>( + context: context, + builder: (context) => EditEntryRatingDialog( + entry: entries.first, + ), + routeSettings: const RouteSettings(name: EditEntryRatingDialog.routeName), + ); + } + + Future<Map<AvesEntry, Set<String>>?> selectTags(BuildContext context, Set<AvesEntry> entries) async { + if (entries.isEmpty) return null; + + final oldTagsByEntry = Map.fromEntries(entries.map((v) { + return MapEntry(v, v.tags.map(TagFilter.new).toSet()); + })); + final filtersByEntry = await Navigator.maybeOf(context)?.push<Map<AvesEntry, Set<CollectionFilter>>>( + MaterialPageRoute( + settings: const RouteSettings(name: TagEditorPage.routeName), + builder: (context) => TagEditorPage( + tagsByEntry: oldTagsByEntry, + ), + ), + ) ?? + oldTagsByEntry; + + final newTagsByEntry = <AvesEntry, Set<String>>{}; + await Future.forEach(filtersByEntry.entries, (kv) async { + final entry = kv.key; + final filters = kv.value; + newTagsByEntry[entry] = await getTagsFromFilters(filters, entry); + }); + + return newTagsByEntry; + } + + Future<Set<String>> getTagsFromFilters(Set<CollectionFilter> filters, AvesEntry entry) async { + final tags = filters.whereType<TagFilter>().map((v) => v.tag).toSet(); + final placeholderTags = await Future.wait(filters.whereType<PlaceholderFilter>().map((v) => v.toTag(entry))); + tags.addAll(placeholderTags.nonNulls.where((v) => v.isNotEmpty)); + return tags; + } + + Future<Set<MetadataType>?> selectMetadataToRemove(BuildContext context, Set<AvesEntry> entries) async { + if (entries.isEmpty) return null; + + final types = await showDialog<Set<MetadataType>>( + context: context, + builder: (context) => RemoveEntryMetadataDialog( + showJpegTypes: entries.any((entry) => entry.mimeType == MimeTypes.jpeg), + ), + routeSettings: const RouteSettings(name: RemoveEntryMetadataDialog.routeName), + ); + if (types == null || types.isEmpty) return null; + + if (entries.any((entry) => entry.isMotionPhoto) && types.contains(MetadataType.xmp)) { + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.removeEntryMetadataMotionPhotoXmpWarningDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return null; + } + + return types; + } +} diff --git a/lib/widgets/common/action_mixins/entry_storage.dart b/lib/widgets/common/action_mixins/entry_storage.dart new file mode 100644 index 0000000..a3505e1 --- /dev/null +++ b/lib/widgets/common/action_mixins/entry_storage.dart @@ -0,0 +1,563 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/image_op_events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/enums.dart'; +import 'package:aves/services/media/media_edit_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/collection/entry_set_action_delegate.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/action_mixins/size_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/album_pick_page.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/single_selection.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +mixin EntryStorageMixin on FeedbackMixin, PermissionAwareMixin, SizeAwareMixin { + // returns whether it completed the action (with or without failures) + Future<bool> doExport(BuildContext context, Set<AvesEntry> targetEntries, EntryConvertOptions options) async { + final destinationAlbumFilter = await pickAlbum( + context: context, + moveType: MoveType.export, + chipTypes: {AlbumChipType.stored}, + initialGroup: null, + ); + if (destinationAlbumFilter == null || destinationAlbumFilter is! StoredAlbumFilter) return false; + + final destinationAlbum = destinationAlbumFilter.album; + if (!await checkStoragePermissionForAlbums(context, {destinationAlbum})) return false; + + if (!await checkFreeSpaceForMove(context, targetEntries, destinationAlbum, MoveType.export)) return false; + + final transientMultiPageInfo = <MultiPageInfo>{}; + final selection = <AvesEntry>{}; + await Future.forEach(targetEntries, (targetEntry) async { + if (targetEntry.isMultiPage) { + final multiPageInfo = await targetEntry.getMultiPageInfo(); + if (multiPageInfo != null) { + transientMultiPageInfo.add(multiPageInfo); + if (targetEntry.isMotionPhoto) { + await multiPageInfo.extractMotionPhotoVideo(); + } + if (multiPageInfo.pageCount > 1) { + selection.addAll(multiPageInfo.exportEntries); + } + } + } else { + selection.add(targetEntry); + } + }); + + final l10n = context.l10n; + + var nameConflictStrategy = NameConflictStrategy.rename; + final destinationDirectory = Directory(destinationAlbum); + final destinationExtension = MimeTypes.extensionFor(options.mimeType); + final names = [ + ...selection.map((v) => '${v.filenameWithoutExtension}$destinationExtension'), + // do not guard up front based on directory existence, + // as conflicts could be within moved entries scattered across multiple albums + if (await destinationDirectory.exists()) ...destinationDirectory.listSync().map((v) => pContext.basename(v.path)), + ].map((v) => v.toLowerCase()).toList(); + // case insensitive comparison + final uniqueNames = names.toSet(); + if (uniqueNames.length < names.length) { + final value = await showDialog<NameConflictStrategy>( + context: context, + builder: (context) => AvesSingleSelectionDialog<NameConflictStrategy>( + initialValue: nameConflictStrategy, + options: Map.fromEntries(NameConflictStrategy.values.map((v) => MapEntry(v, v.getName(context)))), + message: l10n.nameConflictDialogSingleSourceMessage, + confirmationButtonLabel: l10n.continueButtonLabel, + ), + routeSettings: const RouteSettings(name: AvesSingleSelectionDialog.routeName), + ); + if (value == null) return false; + nameConflictStrategy = value; + } + + final selectionCount = selection.length; + final source = context.read<CollectionSource>(); + source.pauseMonitoring(); + await showOpReport<ExportOpEvent>( + context: context, + opStream: mediaEditService.export( + selection, + options: options, + destinationAlbum: destinationAlbum, + nameConflictStrategy: nameConflictStrategy, + ), + itemCount: selectionCount, + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final exportedOps = successOps.where((op) => !op.skipped && op.newFields[EntryFields.uri] != null).toSet(); + final newUris = exportedOps.map((op) => op.newFields[EntryFields.uri] as String).toSet(); + final isMainMode = context.read<ValueNotifier<AppMode>>().value == AppMode.main; + + // check source favourite status + final favouriteSourceUris = selection.where((entry) => entry.isFavourite).map((entry) => entry.uri).toSet(); + final favouriteNewUris = <String>{}; + exportedOps.forEach((op) { + final sourceUri = op.uri; + if (favouriteSourceUris.contains(sourceUri)) { + final newUri = op.newFields[EntryFields.uri] as String; + favouriteNewUris.add(newUri); + } + }); + + source.resumeMonitoring(); + unawaited(source.refreshUris(newUris).then((_) { + // transfer favourite status on exports + final newFavouriteEntries = source.allEntries.where((entry) => favouriteNewUris.contains(entry.uri)).toSet(); + favourites.add(newFavouriteEntries); + })); + + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + final showAction = isMainMode && newUris.isNotEmpty + ? SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () { + if (navigator != null) { + navigator.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: source, + filters: {StoredAlbumFilter(destinationAlbum, source.getStoredAlbumDisplayName(context, destinationAlbum))}, + highlightTest: (entry) => newUris.contains(entry.uri), + ), + ), + (route) => false, + ); + } + }, + ) + : null; + final successCount = successOps.length; + if (successCount < selectionCount) { + final count = selectionCount - successCount; + showFeedback( + context, + FeedbackType.warn, + l10n.collectionExportFailureFeedback(count), + showAction, + ); + } else { + showFeedback( + context, + FeedbackType.info, + l10n.genericSuccessFeedback, + showAction, + ); + } + }, + ); + transientMultiPageInfo.forEach((v) => v.dispose()); + return true; + } + + // returns whether it completed the action (with or without failures) + Future<bool> doQuickMove( + BuildContext context, { + required MoveType moveType, + required Map<String, Set<AvesEntry>> entriesByDestination, + bool hideShowAction = false, + VoidCallback? onSuccess, + }) async { + if (moveType == MoveType.move) { + // skip moving entries to their directory + entriesByDestination.forEach((destinationAlbum, entries) { + entries.removeWhere((entry) => entry.directory == destinationAlbum); + }); + entriesByDestination.removeWhere((_, entries) => entries.isEmpty); + } + + final entries = entriesByDestination.values.expand((v) => v).toSet(); + final todoCount = entries.length; + if (todoCount == 0) return true; + + final toBin = moveType == MoveType.toBin; + final copy = moveType == MoveType.copy; + + // permission for modification at destinations + final destinationAlbums = entriesByDestination.keys.toSet(); + if (!await checkStoragePermissionForAlbums(context, destinationAlbums)) return false; + + // permission for modification at origins + final originAlbums = entries.map((e) => e.directory).nonNulls.toSet(); + if ({MoveType.move, MoveType.toBin}.contains(moveType) && !await checkStoragePermissionForAlbums(context, originAlbums, entries: entries)) return false; + + final hasEnoughSpaceByDestination = await Future.wait(destinationAlbums.map((destinationAlbum) { + return checkFreeSpaceForMove(context, entries, destinationAlbum, moveType); + })); + if (hasEnoughSpaceByDestination.any((v) => !v)) return false; + + final l10n = context.l10n; + var nameConflictStrategy = NameConflictStrategy.rename; + if (!toBin && destinationAlbums.length == 1) { + final destinationDirectory = Directory(destinationAlbums.single); + final names = [ + ...entries.map((v) => '${v.filenameWithoutExtension}${v.extension}'), + // do not guard up front based on directory existence, + // as conflicts could be within moved entries scattered across multiple albums + if (await destinationDirectory.exists()) ...destinationDirectory.listSync().map((v) => pContext.basename(v.path)), + ].map((v) => v.toLowerCase()).toList(); + // case insensitive comparison + final uniqueNames = names.toSet(); + if (uniqueNames.length < names.length) { + final value = await showDialog<NameConflictStrategy>( + context: context, + builder: (context) => AvesSingleSelectionDialog<NameConflictStrategy>( + initialValue: nameConflictStrategy, + options: Map.fromEntries(NameConflictStrategy.values.map((v) => MapEntry(v, v.getName(context)))), + message: originAlbums.length == 1 ? l10n.nameConflictDialogSingleSourceMessage : l10n.nameConflictDialogMultipleSourceMessage, + confirmationButtonLabel: l10n.continueButtonLabel, + ), + routeSettings: const RouteSettings(name: AvesSingleSelectionDialog.routeName), + ); + if (value == null) return false; + nameConflictStrategy = value; + } + } + + if ({MoveType.move, MoveType.copy, MoveType.toBin}.contains(moveType) && !await _checkUndatedItems(context, entries)) return false; + + final source = context.read<CollectionSource>(); + source.pauseMonitoring(); + final opId = mediaEditService.newOpId; + await showOpReport<MoveOpEvent>( + context: context, + opStream: mediaEditService.move( + opId: opId, + entriesByDestination: entriesByDestination, + copy: copy, + nameConflictStrategy: nameConflictStrategy, + ), + itemCount: todoCount, + onCancel: () => mediaEditService.cancelFileOp(opId), + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + + // move + final movedOps = successOps.where((op) => !op.skipped && !op.deleted).toSet(); + final movedEntries = movedOps.map((op) => op.uri).map((uri) => entries.firstWhereOrNull((entry) => entry.uri == uri)).nonNulls.toSet(); + await source.updateAfterMove( + todoEntries: entries, + moveType: moveType, + destinationAlbums: destinationAlbums, + movedOps: movedOps, + ); + + // delete (when trying to move to bin obsolete entries) + final deletedOps = successOps.where((op) => op.deleted).toSet(); + final deletedUris = deletedOps.map((op) => op.uri).toSet(); + await source.removeEntries(deletedUris, includeTrash: true); + + source.resumeMonitoring(); + + // cleanup + if ({MoveType.move, MoveType.toBin}.contains(moveType)) { + await storageService.deleteEmptyRegularDirectories(originAlbums); + } + + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedback( + context, + FeedbackType.warn, + copy ? l10n.collectionCopyFailureFeedback(count) : l10n.collectionMoveFailureFeedback(count), + ); + } else { + final count = movedOps.length; + final appMode = context.read<ValueNotifier<AppMode>?>()?.value; + + SnackBarAction? action; + if (count > 0 && appMode == AppMode.main) { + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + if (toBin) { + if (movedEntries.isNotEmpty) { + action = SnackBarAction( + label: Themes.asButtonLabel(l10n.entryActionRestore), + onPressed: () { + if (navigator != null) { + doMove( + navigator.context, + moveType: MoveType.fromBin, + entries: movedEntries, + hideShowAction: true, + ); + } + }, + ); + } + } else if (!hideShowAction) { + action = SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () { + if (navigator != null) { + _showMovedItems(navigator.context, destinationAlbums, movedOps); + } + }, + ); + } + } + + if (!toBin || (toBin && settings.confirmAfterMoveToBin)) { + showFeedback( + context, + FeedbackType.info, + copy ? l10n.collectionCopySuccessFeedback(count) : l10n.collectionMoveSuccessFeedback(count), + action, + ); + } + + EntryMovedNotification(moveType, movedEntries).dispatch(context); + onSuccess?.call(); + } + }, + ); + return true; + } + + // returns whether it completed the action (with or without failures) + Future<bool> doMove( + BuildContext context, { + required MoveType moveType, + required Set<AvesEntry> entries, + bool hideShowAction = false, + VoidCallback? onSuccess, + }) async { + if (moveType == MoveType.toBin) { + final l10n = context.l10n; + if (!await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.moveToBin, + message: l10n.binEntriesConfirmationDialogMessage(entries.length), + confirmationButtonLabel: l10n.deleteButtonLabel, + )) { + return false; + } + } + + final entriesByDestination = <String, Set<AvesEntry>>{}; + switch (moveType) { + case MoveType.copy: + case MoveType.move: + case MoveType.export: + final destinationAlbumFilter = await pickAlbum( + context: context, + moveType: moveType, + chipTypes: {AlbumChipType.stored}, + initialGroup: null, + ); + if (destinationAlbumFilter == null || destinationAlbumFilter is! StoredAlbumFilter) return false; + + final destinationAlbum = destinationAlbumFilter.album; + settings.recentDestinationAlbums = settings.recentDestinationAlbums + ..remove(destinationAlbum) + ..insert(0, destinationAlbum); + entriesByDestination[destinationAlbum] = entries; + case MoveType.toBin: + entriesByDestination[AndroidFileUtils.trashDirPath] = entries; + case MoveType.fromBin: + groupBy<AvesEntry, String?>(entries, (e) => e.directory).forEach((originAlbum, dirEntries) { + if (originAlbum != null) { + entriesByDestination[originAlbum] = dirEntries.toSet(); + } + }); + } + + return await doQuickMove( + context, + moveType: moveType, + entriesByDestination: entriesByDestination, + onSuccess: onSuccess, + ); + } + + // returns whether it completed the action (with or without failures) + Future<bool> rename( + BuildContext context, { + required Map<AvesEntry, String> entriesToNewName, + required bool persist, + VoidCallback? onSuccess, + }) async { + final entries = entriesToNewName.keys.toSet(); + final todoCount = entries.length; + assert(todoCount > 0); + + if (!await checkStoragePermission(context, entries)) return false; + + if (!await _checkUndatedItems(context, entries)) return false; + + final source = context.read<CollectionSource>(); + source.pauseMonitoring(); + final opId = mediaEditService.newOpId; + await showOpReport<MoveOpEvent>( + context: context, + opStream: mediaEditService.rename( + opId: opId, + entriesToNewName: entriesToNewName, + ), + itemCount: todoCount, + onCancel: () => mediaEditService.cancelFileOp(opId), + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final movedOps = successOps.where((op) => !op.skipped).toSet(); + await source.updateAfterRename( + todoEntries: entries, + movedOps: movedOps, + persist: persist, + ); + source.resumeMonitoring(); + + final l10n = context.l10n; + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedback(context, FeedbackType.warn, l10n.collectionRenameFailureFeedback(count)); + } else { + final count = movedOps.length; + showFeedback(context, FeedbackType.info, l10n.collectionRenameSuccessFeedback(count)); + onSuccess?.call(); + } + }, + ); + return true; + } + + Future<bool> _checkUndatedItems(BuildContext context, Set<AvesEntry> entries) async { + final undatedItems = entries.where((entry) { + if (!entry.isCatalogued) return false; + final dateMillis = entry.catalogMetadata?.dateMillis; + return dateMillis == null || dateMillis == 0; + }).toSet(); + if (undatedItems.isNotEmpty) { + final confirmationDialogDelegate = MoveUndatedConfirmationDialogDelegate(); + final confirmed = await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.moveUndatedItems, + delegate: confirmationDialogDelegate, + confirmationButtonLabel: context.l10n.continueButtonLabel, + ); + confirmationDialogDelegate.dispose(); + if (!confirmed) return false; + + if (settings.setMetadataDateBeforeFileOp) { + final entriesToDate = undatedItems.where((entry) => entry.canEditDate).toSet(); + if (entriesToDate.isNotEmpty) { + await EntrySetActionDelegate().editDate( + context, + entries: entriesToDate, + modifier: DateModifier.copyField(DateFieldSource.fileModifiedDate), + showResult: false, + ); + } + } + } + return true; + } + + Future<void> _showMovedItems( + BuildContext context, + Set<String> destinationAlbums, + Set<MoveOpEvent> movedOps, + ) async { + final newUris = movedOps.map((op) => op.newFields[EntryFields.uri] as String?).toSet(); + bool highlightTest(AvesEntry entry) => newUris.contains(entry.uri); + + final collection = context.read<CollectionLens?>(); + if (collection == null || collection.filters.any((f) => f is StoredAlbumFilter || f is TrashFilter)) { + final source = context.read<CollectionSource>(); + final targetFilters = collection?.filters.where((f) => f != TrashFilter.instance).toSet() ?? {}; + // we could simply add the filter to the current collection + // but navigating makes the change less jarring + if (destinationAlbums.length == 1) { + final destinationAlbum = destinationAlbums.single; + targetFilters.removeWhere((f) => f is StoredAlbumFilter); + targetFilters.add(StoredAlbumFilter(destinationAlbum, source.getStoredAlbumDisplayName(context, destinationAlbum))); + } + unawaited(Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: source, + filters: targetFilters, + highlightTest: highlightTest, + ), + ), + (route) => false, + )); + } else { + // track in current page, without navigation + await Future.delayed(ADurations.highlightScrollInitDelay); + final targetEntry = collection.sortedEntries.firstWhereOrNull(highlightTest); + if (targetEntry != null) { + context.read<HighlightInfo>().trackItem(targetEntry, highlightItem: targetEntry); + } + } + } +} + +class MoveUndatedConfirmationDialogDelegate extends ConfirmationDialogDelegate { + final ValueNotifier<bool> _setMetadataDate = ValueNotifier(false); + + MoveUndatedConfirmationDialogDelegate() { + _setMetadataDate.value = settings.setMetadataDateBeforeFileOp; + } + + void dispose() { + _setMetadataDate.dispose(); + } + + @override + List<Widget> build(BuildContext context) => [ + Padding( + padding: const EdgeInsets.all(16) + const EdgeInsets.only(top: 8), + child: Text(context.l10n.moveUndatedConfirmationDialogMessage), + ), + ValueListenableBuilder<bool>( + valueListenable: _setMetadataDate, + builder: (context, flag, child) => SwitchListTile( + value: flag, + onChanged: (v) => _setMetadataDate.value = v, + title: Text(context.l10n.moveUndatedConfirmationDialogSetDate), + ), + ), + ]; + + @override + void apply() => settings.setMetadataDateBeforeFileOp = _setMetadataDate.value; +} diff --git a/lib/widgets/common/action_mixins/feedback.dart b/lib/widgets/common/action_mixins/feedback.dart new file mode 100644 index 0000000..6666ed6 --- /dev/null +++ b/lib/widgets/common/action_mixins/feedback.dart @@ -0,0 +1,533 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/settings/enums/accessibility_timeout.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/action_mixins/overlay_snack_bar.dart'; +import 'package:aves/widgets/common/basic/circle.dart'; +import 'package:aves/widgets/common/basic/text/change_highlight.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:overlay_support/overlay_support.dart'; +import 'package:percent_indicator/circular_percent_indicator.dart'; +import 'package:provider/provider.dart'; + +enum FeedbackType { info, warn } + +typedef MarginComputer = EdgeInsets Function(BuildContext context); + +mixin FeedbackMixin { + static final ValueNotifier<MarginComputer?> snackBarMarginOverrideNotifier = ValueNotifier(null); + static OverlaySupportEntry? _overlayNotificationEntry; + + static EdgeInsets snackBarMarginDefault(BuildContext context) { + return EdgeInsets.only( + bottom: context.select<MediaQueryData, double>((mq) => max(mq.effectiveBottomPadding, mq.systemGestureInsets.bottom)), + ); + } + + void dismissFeedback(BuildContext context) { + ScaffoldMessenger.of(context).hideCurrentSnackBar(); + _overlayNotificationEntry?.dismiss(); + _overlayNotificationEntry = null; + } + + void showFeedback(BuildContext context, FeedbackType type, String message, [SnackBarAction? action]) { + ScaffoldMessengerState? scaffoldMessenger; + try { + scaffoldMessenger = ScaffoldMessenger.of(context); + } catch (error) { + // minor issue: the page triggering this feedback likely + // allows the user to navigate away and they did so + debugPrint('failed to find ScaffoldMessenger in context'); + } + if (scaffoldMessenger != null) { + showFeedbackWithMessenger(context, scaffoldMessenger, type, message, action); + } + } + + // provide the messenger if feedback happens as the widget is disposed + void showFeedbackWithMessenger(BuildContext context, ScaffoldMessengerState messenger, FeedbackType type, String message, [SnackBarAction? action]) { + settings.timeToTakeAction.getSnackBarDuration(action != null).then((duration) { + final start = DateTime.now(); + final theme = Theme.of(context); + final snackBarTheme = theme.snackBarTheme; + + final snackBarContent = _FeedbackMessage( + type: type, + message: message, + progressColor: theme.colorScheme.primary, + start: start, + stop: action != null ? start.add(duration) : null, + ); + + if (snackBarMarginOverrideNotifier.value != null) { + // as of Flutter v2.10.4, `SnackBar` can only be positioned at the bottom, + // and space under the snack bar `margin` does not receive gestures + // (because it is used by the `Dismissible` wrapping the snack bar) + // so we use `showOverlayNotification` instead + _overlayNotificationEntry = showOverlayNotification( + (context) => SafeArea( + bottom: false, + child: ValueListenableBuilder<MarginComputer?>( + valueListenable: snackBarMarginOverrideNotifier, + builder: (context, marginComputer, child) { + final margin = (marginComputer ?? snackBarMarginDefault).call(context); + return AnimatedPadding( + padding: margin, + duration: ADurations.pageTransitionLoose, + child: child, + ); + }, + child: OverlaySnackBar( + content: snackBarContent, + action: action != null + ? TextButton( + style: ButtonStyle( + foregroundColor: WidgetStateProperty.all(snackBarTheme.actionTextColor), + ), + onPressed: () { + dismissFeedback(context); + action.onPressed(); + }, + child: Text(action.label), + ) + : null, + animation: kAlwaysCompleteAnimation, + dismissDirection: DismissDirection.horizontal, + onDismiss: () => dismissFeedback(context), + ), + ), + ), + duration: duration, + // reuse the same key to dismiss previous snack bar when a new one is shown + key: const Key('snack'), + position: NotificationPosition.bottom, + context: context, + ); + } else { + messenger.showSnackBar(SnackBar( + content: snackBarContent, + padding: action != null ? EdgeInsetsDirectional.only(start: snackBarHorizontalPadding(snackBarTheme)) : null, + action: action, + duration: duration, + dismissDirection: DismissDirection.horizontal, + )); + } + }); + } + + static double snackBarHorizontalPadding(SnackBarThemeData snackBarTheme) { + final isFloatingSnackBar = (snackBarTheme.behavior ?? SnackBarBehavior.fixed) == SnackBarBehavior.floating; + final double horizontalPadding = isFloatingSnackBar ? 16.0 : 24.0; + return horizontalPadding; + } + + // report overlay for multiple operations + + Future<void> showOpReport<T>({ + required BuildContext context, + required Stream<T> opStream, + int? itemCount, + VoidCallback? onCancel, + Future<void> Function(Set<T> processed)? onDone, + }) async { + final opCompleter = Completer(); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => ReportOverlay<T>( + opStream: opStream, + itemCount: itemCount, + onCancel: onCancel, + onDone: (processed) async { + Navigator.maybeOf(context)?.pop(); + await onDone?.call(processed); + opCompleter.complete(); + }, + ), + routeSettings: const RouteSettings(name: ReportOverlay.routeName), + ); + return opCompleter.future; + } +} + +class ReportOverlay<T> extends StatefulWidget { + static const routeName = '/dialog/report_overlay'; + + final Stream<T> opStream; + final int? itemCount; + final VoidCallback? onCancel; + final void Function(Set<T> processed) onDone; + + static const double diameter = 160.0; + static const double strokeWidth = 8.0; + + const ReportOverlay({ + super.key, + required this.opStream, + required this.itemCount, + required this.onCancel, + required this.onDone, + }); + + @override + State<ReportOverlay<T>> createState() => _ReportOverlayState<T>(); +} + +class _ReportOverlayState<T> extends State<ReportOverlay<T>> with SingleTickerProviderStateMixin { + final processed = <T>{}; + late AnimationController _animationController; + late CurvedAnimation _animation; + + Stream<T> get opStream => widget.opStream; + + static const double fontSize = 18.0; + + @override + void initState() { + super.initState(); + + _animationController = AnimationController( + duration: ADurations.collectionOpOverlayAnimation, + vsync: this, + ); + _animation = CurvedAnimation( + parent: _animationController, + curve: Curves.easeOutQuad, + ); + _animationController.forward(); + + // do not handle completion inside `StreamBuilder` + // as it could be called multiple times + Future<void> onComplete() => _animationController.reverse().then((_) => widget.onDone(processed)); + opStream.listen( + processed.add, + onError: (error) => debugPrint('_showOpReport error=$error'), + onDone: onComplete, + ); + } + + @override + void dispose() { + _animation.dispose(); + _animationController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + const diameter = ReportOverlay.diameter; + const strokeWidth = ReportOverlay.strokeWidth; + final percentFormatter = NumberFormat.percentPattern(context.locale); + + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final progressColor = colorScheme.primary; + final animate = context.select<Settings, bool>((v) => v.animate); + return PopScope( + canPop: false, + child: StreamBuilder<T>( + stream: opStream, + builder: (context, snapshot) { + final processedCount = processed.length.toDouble(); + final total = widget.itemCount; + final percent = total == null || total == 0 ? 0.0 : min(1.0, processedCount / total); + return FadeTransition( + opacity: _animation, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: diameter + 2, + height: diameter + 2, + decoration: BoxDecoration( + color: theme.isDark ? const Color(0xBB000000) : const Color(0xEEFFFFFF), + shape: BoxShape.circle, + ), + ), + if (animate) const ReportProgressIndicator(opacity: .1), + CircularPercentIndicator( + percent: percent, + lineWidth: strokeWidth, + radius: diameter / 2, + backgroundColor: colorScheme.onSurface.withValues(alpha: .2), + progressColor: progressColor, + animation: animate, + center: total != null + ? Text( + percentFormatter.format(percent), + style: const TextStyle(fontSize: fontSize), + ) + : null, + animateFromLastPercent: true, + ), + if (widget.onCancel != null) + Material( + color: Colors.transparent, + child: Container( + width: diameter, + height: diameter, + margin: const EdgeInsets.only(top: fontSize), + alignment: const FractionalOffset(0.5, 0.75), + child: Tooltip( + message: context.l10n.cancelTooltip, + preferBelow: false, + child: IconButton( + icon: const Icon(AIcons.cancel), + onPressed: widget.onCancel, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ); + } +} + +class ReportProgressIndicator extends StatelessWidget { + final double opacity; + + const ReportProgressIndicator({ + super.key, + this.opacity = 1, + }); + + @override + Widget build(BuildContext context) { + const diameter = ReportOverlay.diameter; + const strokeWidth = ReportOverlay.strokeWidth; + final progressColor = Theme.of(context).colorScheme.primary; + + return Container( + width: diameter, + height: diameter, + padding: const EdgeInsets.all(strokeWidth / 2), + child: CircularProgressIndicator( + color: progressColor.withValues(alpha: opacity), + strokeWidth: strokeWidth, + ), + ); + } +} + +class _FeedbackMessage extends StatefulWidget { + final FeedbackType type; + final String message; + final DateTime? start, stop; + final Color progressColor; + + const _FeedbackMessage({ + required this.type, + required this.message, + required this.progressColor, + this.start, + this.stop, + }); + + @override + State<_FeedbackMessage> createState() => _FeedbackMessageState(); +} + +class _FeedbackMessageState extends State<_FeedbackMessage> with SingleTickerProviderStateMixin { + AnimationController? _animationController; + CurvedAnimation? _animation; + Animation<int>? _remainingDurationMillis; + int? _totalDurationMillis; + + @override + void initState() { + super.initState(); + final start = widget.start; + final stop = widget.stop; + if (start != null && stop != null) { + _totalDurationMillis = stop.difference(start).inMilliseconds; + final remainingDuration = stop.difference(DateTime.now()); + final effectiveDuration = remainingDuration > Duration.zero ? remainingDuration : const Duration(milliseconds: 1); + _animationController = AnimationController( + duration: effectiveDuration, + vsync: this, + ); + _animation = CurvedAnimation( + parent: _animationController!, + curve: Curves.linear, + ); + _remainingDurationMillis = IntTween( + begin: effectiveDuration.inMilliseconds, + end: 0, + ).animate(_animation!); + _animationController!.forward(); + } + } + + @override + void dispose() { + _animation?.dispose(); + _animationController?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final durationFormatter = NumberFormat('0', context.locale); + + final textScaler = MediaQuery.textScalerOf(context); + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final contentTextStyle = theme.snackBarTheme.contentTextStyle ?? + theme.textTheme.bodyMedium!.copyWith( + color: colorScheme.onInverseSurface, + ); + final contentTextFontSize = contentTextStyle.fontSize ?? theme.textTheme.bodyMedium!.fontSize!; + final timerChangeShadowColor = colorScheme.primary; + + final remainingDurationAnimation = _remainingDurationMillis; + return Row( + children: [ + if (widget.type == FeedbackType.warn) ...[ + CustomPaint( + painter: const _WarnIndicator(AColors.warning), + size: Size(4, textScaler.scale(contentTextFontSize)), + ), + const SizedBox(width: 8), + ], + Expanded(child: Text(widget.message)), + if (remainingDurationAnimation != null) ...[ + const SizedBox(width: 16), + AnimatedBuilder( + animation: remainingDurationAnimation, + builder: (context, child) { + final remainingDurationMillis = remainingDurationAnimation.value; + final totalDurationMillis = _totalDurationMillis; + return CircularIndicator( + radius: 16, + lineWidth: 2, + percent: totalDurationMillis != null && totalDurationMillis > 0 ? remainingDurationMillis / totalDurationMillis : 0, + background: Colors.grey, + // progress color is provided by the caller, + // because we cannot use the app context theme here + foreground: widget.progressColor, + center: ChangeHighlightText( + durationFormatter.format((remainingDurationMillis / 1000).ceil()), + style: contentTextStyle.copyWith( + shadows: [ + Shadow( + color: timerChangeShadowColor.withAlpha(0), + blurRadius: 0, + ) + ], + ), + changedStyle: contentTextStyle.copyWith( + shadows: [ + Shadow( + color: timerChangeShadowColor, + blurRadius: 5, + ) + ], + ), + duration: context.read<DurationsData>().formTextStyleTransition, + ), + ); + }, + ), + ] + ], + ); + } +} + +class _WarnIndicator extends CustomPainter { + final Color color; + + const _WarnIndicator(this.color); + + @override + void paint(Canvas canvas, Size size) { + canvas.drawRRect( + RRect.fromLTRBR(0, 0, size.width, size.height, Radius.circular(size.shortestSide / 2)), + Paint() + ..style = PaintingStyle.fill + ..color = color, + ); + } + + @override + bool shouldRepaint(_WarnIndicator oldDelegate) => false; +} + +class ActionFeedback extends StatefulWidget { + final Widget? child; + + const ActionFeedback({ + super.key, + required this.child, + }); + + @override + State<ActionFeedback> createState() => _ActionFeedbackState(); +} + +class _ActionFeedbackState extends State<ActionFeedback> with SingleTickerProviderStateMixin { + late final AnimationController _animationController; + + @override + void initState() { + super.initState(); + _animationController = AnimationController( + duration: ADurations.viewerActionFeedbackAnimation, + vsync: this, + ); + } + + @override + void didUpdateWidget(covariant ActionFeedback oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.child != widget.child) { + _animationController.reset(); + if (widget.child != null) { + _animationController.forward(); + } + } + } + + @override + void dispose() { + _animationController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: Center( + child: AnimatedBuilder( + animation: _animationController, + builder: (context, child) { + final t = _animationController.value; + final opacity = Curves.easeOutQuad.transform(t > .5 ? (1 - t) * 2 : t * 2); + final scale = Curves.slowMiddle.transform(t) * 2; + return Opacity( + opacity: opacity, + child: Transform.scale( + scale: scale, + child: child, + ), + ); + }, + child: widget.child, + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_mixins/overlay_snack_bar.dart b/lib/widgets/common/action_mixins/overlay_snack_bar.dart new file mode 100644 index 0000000..a32206a --- /dev/null +++ b/lib/widgets/common/action_mixins/overlay_snack_bar.dart @@ -0,0 +1,431 @@ +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:flutter/material.dart'; + +// adapted from Flutter `SnackBar` in `/material/snack_bar.dart` + +// As of Flutter v3.23.0, `SnackBar` is not customizable enough to add margin +// and ignore pointers in that area, so we use an overlay entry instead. +// This overlay entry is not under a `Scaffold` (which is expected by `SnackBar` +// and `SnackBarAction`), and is not dismissed the same way. + +const double _singleLineVerticalPadding = 14.0; +const Duration _snackBarDisplayDuration = Duration(milliseconds: 4000); +const Curve _snackBarHeightCurve = Curves.fastOutSlowIn; +const Curve _snackBarM3HeightCurve = Curves.easeInOutQuart; + +const Curve _snackBarFadeInCurve = Interval(0.4, 1.0); +const Curve _snackBarM3FadeInCurve = Interval(0.4, 0.6, curve: Curves.easeInCirc); +const Curve _snackBarFadeOutCurve = Interval(0.72, 1.0, curve: Curves.fastOutSlowIn); + +class OverlaySnackBar extends StatefulWidget { + final Widget content; + final Color? backgroundColor; + final double? elevation; + final EdgeInsetsGeometry? margin; + final EdgeInsetsGeometry? padding; + final double? width; + final ShapeBorder? shape; + final HitTestBehavior? hitTestBehavior; + final SnackBarBehavior? behavior; + final Widget? action; + final double? actionOverflowThreshold; + final bool? showCloseIcon; + final Color? closeIconColor; + final Duration duration; + final Animation<double>? animation; + final VoidCallback? onVisible; + final DismissDirection dismissDirection; + final Clip clipBehavior; + final VoidCallback onDismiss; + + const OverlaySnackBar({ + super.key, + required this.content, + this.backgroundColor, + this.elevation, + this.margin, + this.padding, + this.width, + this.shape, + this.hitTestBehavior, + this.behavior, + this.action, + this.actionOverflowThreshold, + this.showCloseIcon, + this.closeIconColor, + this.duration = _snackBarDisplayDuration, + this.animation, + this.onVisible, + this.dismissDirection = DismissDirection.down, + this.clipBehavior = Clip.hardEdge, + required this.onDismiss, + }) : assert(elevation == null || elevation >= 0.0), + assert( + width == null || margin == null, + 'Width and margin can not be used together', + ), + assert(actionOverflowThreshold == null || (actionOverflowThreshold >= 0 && actionOverflowThreshold <= 1), 'Action overflow threshold must be between 0 and 1 inclusive'); + + @override + State<OverlaySnackBar> createState() => _OverlaySnackBarState(); +} + +class _OverlaySnackBarState extends State<OverlaySnackBar> { + bool _wasVisible = false; + + CurvedAnimation? _heightAnimation; + CurvedAnimation? _fadeInAnimation; + CurvedAnimation? _fadeInM3Animation; + CurvedAnimation? _fadeOutAnimation; + CurvedAnimation? _heightM3Animation; + + @override + void initState() { + super.initState(); + widget.animation!.addStatusListener(_onAnimationStatusChanged); + _setAnimations(); + } + + @override + void didUpdateWidget(OverlaySnackBar oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.animation != oldWidget.animation) { + oldWidget.animation!.removeStatusListener(_onAnimationStatusChanged); + widget.animation!.addStatusListener(_onAnimationStatusChanged); + _disposeAnimations(); + _setAnimations(); + } + } + + void _setAnimations() { + assert(widget.animation != null); + _heightAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarHeightCurve); + _fadeInAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarFadeInCurve); + _fadeInM3Animation = CurvedAnimation(parent: widget.animation!, curve: _snackBarM3FadeInCurve); + _fadeOutAnimation = CurvedAnimation( + parent: widget.animation!, + curve: _snackBarFadeOutCurve, + reverseCurve: const Threshold(0.0), + ); + // Material 3 Animation has a height animation on entry, but a direct fade out on exit. + _heightM3Animation = CurvedAnimation( + parent: widget.animation!, + curve: _snackBarM3HeightCurve, + reverseCurve: const Threshold(0.0), + ); + } + + void _disposeAnimations() { + _heightAnimation?.dispose(); + _fadeInAnimation?.dispose(); + _fadeInM3Animation?.dispose(); + _fadeOutAnimation?.dispose(); + _heightM3Animation?.dispose(); + _heightAnimation = null; + _fadeInAnimation = null; + _fadeInM3Animation = null; + _fadeOutAnimation = null; + _heightM3Animation = null; + } + + @override + void dispose() { + widget.animation!.removeStatusListener(_onAnimationStatusChanged); + _disposeAnimations(); + super.dispose(); + } + + void _onAnimationStatusChanged(AnimationStatus status) { + if (status.isCompleted) { + if (widget.onVisible != null && !_wasVisible) { + widget.onVisible!(); + } + _wasVisible = true; + } + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context); + assert(widget.animation != null); + final ThemeData theme = Theme.of(context); + final ColorScheme colorScheme = theme.colorScheme; + final SnackBarThemeData snackBarTheme = theme.snackBarTheme; + final bool isThemeDark = theme.isDark; + final Color buttonColor = isThemeDark ? colorScheme.primary : colorScheme.secondary; + final SnackBarThemeData defaults = _SnackbarDefaultsM3(context); + + // SnackBar uses a theme that is the opposite brightness from + // the surrounding theme. + final Brightness brightness = isThemeDark ? Brightness.light : Brightness.dark; + + // Invert the theme values for Material 2. Material 3 values are tokenized to pre-inverted values. + final ThemeData effectiveTheme = theme.useMaterial3 + ? theme + : theme.copyWith( + colorScheme: ColorScheme( + primary: colorScheme.onPrimary, + secondary: buttonColor, + surface: colorScheme.onSurface, + error: colorScheme.onError, + onPrimary: colorScheme.primary, + onSecondary: colorScheme.secondary, + onSurface: colorScheme.surface, + onError: colorScheme.error, + brightness: brightness, + ), + ); + + final TextStyle? contentTextStyle = snackBarTheme.contentTextStyle ?? defaults.contentTextStyle; + final SnackBarBehavior snackBarBehavior = widget.behavior ?? snackBarTheme.behavior ?? defaults.behavior!; + final double? width = widget.width ?? snackBarTheme.width; + assert(() { + // Whether the behavior is set through the constructor or the theme, + // assert that our other properties are configured properly. + if (snackBarBehavior != SnackBarBehavior.floating) { + String message(String parameter) { + final String prefix = '$parameter can only be used with floating behavior.'; + if (widget.behavior != null) { + return '$prefix SnackBarBehavior.fixed was set in the SnackBar constructor.'; + } else if (snackBarTheme.behavior != null) { + return '$prefix SnackBarBehavior.fixed was set by the inherited SnackBarThemeData.'; + } else { + return '$prefix SnackBarBehavior.fixed was set by default.'; + } + } + + assert(widget.margin == null, message('Margin')); + assert(width == null, message('Width')); + } + return true; + }()); + + final bool showCloseIcon = widget.showCloseIcon ?? snackBarTheme.showCloseIcon ?? defaults.showCloseIcon!; + + final bool isFloatingSnackBar = snackBarBehavior == SnackBarBehavior.floating; + final double horizontalPadding = isFloatingSnackBar ? 16.0 : 24.0; + final EdgeInsetsGeometry padding = widget.padding ?? EdgeInsetsDirectional.only(start: horizontalPadding, end: widget.action != null || showCloseIcon ? 0 : horizontalPadding); + + final double iconHorizontalMargin = (widget.padding?.resolve(TextDirection.ltr).right ?? horizontalPadding) / 12.0; + + final IconButton? iconButton = showCloseIcon + ? IconButton( + icon: const Icon(Icons.close), + iconSize: 24, + color: widget.closeIconColor ?? snackBarTheme.closeIconColor ?? defaults.closeIconColor, + onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(reason: SnackBarClosedReason.dismiss), + tooltip: MaterialLocalizations.of(context).closeButtonTooltip, + ) + : null; + + final EdgeInsets margin = widget.margin?.resolve(TextDirection.ltr) ?? snackBarTheme.insetPadding ?? defaults.insetPadding!; + + Widget snackBar = Padding( + padding: padding, + child: Row( + children: <Widget>[ + Expanded( + child: Container( + padding: widget.action != null ? null : const EdgeInsets.symmetric(vertical: _singleLineVerticalPadding), + child: DefaultTextStyle( + style: contentTextStyle!, + child: widget.content, + ), + ), + ), + if (widget.action != null) + TextButtonTheme( + data: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: buttonColor, + padding: EdgeInsets.symmetric(horizontal: horizontalPadding), + ), + ), + child: widget.action!, + ), + if (showCloseIcon) + Padding( + padding: EdgeInsets.symmetric(horizontal: iconHorizontalMargin), + child: iconButton, + ), + ], + ), + ); + + if (!isFloatingSnackBar) { + snackBar = SafeArea( + top: false, + child: snackBar, + ); + } + + final double elevation = widget.elevation ?? snackBarTheme.elevation ?? defaults.elevation!; + final Color backgroundColor = widget.backgroundColor ?? snackBarTheme.backgroundColor ?? defaults.backgroundColor!; + final ShapeBorder? shape = widget.shape ?? snackBarTheme.shape ?? (isFloatingSnackBar ? defaults.shape : null); + + snackBar = Material( + shape: shape, + elevation: elevation, + color: backgroundColor, + clipBehavior: widget.clipBehavior, + child: Theme( + data: effectiveTheme, + child: accessibleNavigation || theme.useMaterial3 + ? snackBar + : FadeTransition( + opacity: _fadeOutAnimation!, + child: snackBar, + ), + ), + ); + + if (isFloatingSnackBar) { + // If width is provided, do not include horizontal margins. + if (width != null) { + snackBar = Container( + margin: EdgeInsets.only(top: margin.top, bottom: margin.bottom), + width: width, + child: snackBar, + ); + } else { + snackBar = Padding( + padding: margin, + child: snackBar, + ); + } + snackBar = SafeArea( + top: false, + bottom: false, + child: snackBar, + ); + } + + snackBar = Semantics( + container: true, + liveRegion: true, + onDismiss: widget.onDismiss, + child: Dismissible( + key: const Key('dismissible'), + direction: widget.dismissDirection, + resizeDuration: null, + behavior: widget.hitTestBehavior ?? (widget.margin != null || snackBarTheme.insetPadding != null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque), + onDismissed: (direction) => widget.onDismiss(), + child: snackBar, + ), + ); + + final Widget snackBarTransition; + if (accessibleNavigation) { + snackBarTransition = snackBar; + } else if (isFloatingSnackBar && !theme.useMaterial3) { + snackBarTransition = FadeTransition( + opacity: _fadeInAnimation!, + child: snackBar, + ); + // Is Material 3 Floating Snack Bar. + } else if (isFloatingSnackBar && theme.useMaterial3) { + snackBarTransition = FadeTransition( + opacity: _fadeInM3Animation!, + child: ValueListenableBuilder<double>( + valueListenable: _heightM3Animation!, + builder: (context, value, child) { + return Align( + alignment: Alignment.bottomLeft, + heightFactor: value, + child: child, + ); + }, + child: snackBar, + ), + ); + } else { + snackBarTransition = ValueListenableBuilder<double>( + valueListenable: _heightAnimation!, + builder: (context, value, child) { + return Align( + alignment: AlignmentDirectional.topStart, + heightFactor: value, + child: child, + ); + }, + child: snackBar, + ); + } + + return Hero( + tag: '<SnackBar Hero tag - ${widget.content}>', + transitionOnUserGestures: true, + child: ClipRect( + clipBehavior: widget.clipBehavior, + child: snackBarTransition, + ), + ); + } +} + +// BEGIN GENERATED TOKEN PROPERTIES - Snackbar + +// Do not edit by hand. The code between the "BEGIN GENERATED" and +// "END GENERATED" comments are generated from data in the Material +// Design token database by the script: +// dev/tools/gen_defaults/bin/gen_defaults.dart. + +class _SnackbarDefaultsM3 extends SnackBarThemeData { + _SnackbarDefaultsM3(this.context); + + final BuildContext context; + late final ThemeData _theme = Theme.of(context); + late final ColorScheme _colors = _theme.colorScheme; + + @override + Color get backgroundColor => _colors.inverseSurface; + + @override + Color get actionTextColor => WidgetStateColor.resolveWith((states) { + if (states.contains(WidgetState.disabled)) { + return _colors.inversePrimary; + } + if (states.contains(WidgetState.pressed)) { + return _colors.inversePrimary; + } + if (states.contains(WidgetState.hovered)) { + return _colors.inversePrimary; + } + if (states.contains(WidgetState.focused)) { + return _colors.inversePrimary; + } + return _colors.inversePrimary; + }); + + @override + Color get disabledActionTextColor => _colors.inversePrimary; + + @override + TextStyle get contentTextStyle => Theme.of(context).textTheme.bodyMedium!.copyWith( + color: _colors.onInverseSurface, + ); + + @override + double get elevation => 6.0; + + @override + ShapeBorder get shape => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))); + + @override + SnackBarBehavior get behavior => SnackBarBehavior.fixed; + + @override + EdgeInsets get insetPadding => const EdgeInsets.fromLTRB(15.0, 5.0, 15.0, 10.0); + + @override + bool get showCloseIcon => false; + + @override + Color? get closeIconColor => _colors.onInverseSurface; + + @override + double get actionOverflowThreshold => 0.25; +} + +// END GENERATED TOKEN PROPERTIES - Snackbar diff --git a/lib/widgets/common/action_mixins/permission_aware.dart b/lib/widgets/common/action_mixins/permission_aware.dart new file mode 100644 index 0000000..c553fd9 --- /dev/null +++ b/lib/widgets/common/action_mixins/permission_aware.dart @@ -0,0 +1,119 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +mixin PermissionAwareMixin { + Future<bool> checkStoragePermission(BuildContext context, Set<AvesEntry> entries) { + final storageDirs = entries.map((e) => e.storageDirectory).nonNulls.toSet(); + return checkStoragePermissionForAlbums(context, storageDirs, entries: entries); + } + + Future<bool> checkStoragePermissionForAlbums(BuildContext context, Set<String> storageDirs, {Set<AvesEntry>? entries}) async { + final restrictedDirsLowerCase = await storageService.getRestrictedDirectoriesLowerCase(); + while (true) { + final inaccessibleDirs = await storageService.getInaccessibleDirectories(storageDirs); + + final restrictedInaccessibleDirsLowerCase = inaccessibleDirs + .map((dir) => dir.copyWith( + relativeDir: dir.relativeDir.toLowerCase(), + )) + .where(restrictedDirsLowerCase.contains) + .toSet(); + if (restrictedInaccessibleDirsLowerCase.isNotEmpty) { + if (entries != null && await storageService.canRequestMediaFileBulkAccess()) { + // request media file access for items in restricted directories + final uris = <String>[], mimeTypes = <String>[]; + entries.where((entry) { + final dirPath = entry.directory; + if (dirPath == null) return false; + final dir = androidFileUtils.relativeDirectoryFromPath(dirPath); + return restrictedInaccessibleDirsLowerCase.contains(dir?.copyWith(relativeDir: dir.relativeDir.toLowerCase())); + }).forEach((entry) { + uris.add(entry.uri); + mimeTypes.add(entry.mimeType); + }); + final granted = await storageService.requestMediaFileAccess(uris, mimeTypes); + if (!granted) return false; + } else if (entries == null && await storageService.canInsertMedia(restrictedInaccessibleDirsLowerCase)) { + // insertion in restricted directories + } else { + // cannot proceed further + await showRestrictedDirectoryDialog(context, restrictedInaccessibleDirsLowerCase.first); + return false; + } + // clear restricted directories + inaccessibleDirs.removeWhere((dir) => restrictedInaccessibleDirsLowerCase.contains(dir.copyWith(relativeDir: dir.relativeDir.toLowerCase()))); + } + + if (inaccessibleDirs.isEmpty) return true; + + final dir = inaccessibleDirs.first; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) { + final l10n = context.l10n; + final directory = dir.relativeDir.isEmpty ? l10n.rootDirectoryDescription : l10n.otherDirectoryDescription(dir.relativeDir); + final volume = dir.getVolumeDescription(context); + return AvesDialog( + content: Text(l10n.storageAccessDialogMessage(directory, volume)), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + // MD2 button labels were upper case but they are lower case in MD3 + child: Text(Themes.asButtonLabel(MaterialLocalizations.of(context).okButtonLabel)), + ), + ], + ); + }, + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + // abort if the user cancels in Flutter + if (confirmed == null || !confirmed) return false; + + if (!await _checkSystemFilePickerEnabled(context)) return false; + + final granted = await storageService.requestDirectoryAccess(dir.dirPath); + if (!granted) { + // abort if the user denies access from the native dialog + return false; + } + } + } + + Future<bool?> showRestrictedDirectoryDialog(BuildContext context, VolumeRelativeDirectory dir) { + return showDialog<bool>( + context: context, + builder: (context) { + final directory = dir.relativeDir.isEmpty ? context.l10n.rootDirectoryDescription : context.l10n.otherDirectoryDescription(dir.relativeDir); + final volume = dir.getVolumeDescription(context); + return AvesDialog( + content: Text(context.l10n.restrictedAccessDialogMessage(directory, volume)), + actions: const [OkButton()], + ); + }, + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + + Future<bool> _checkSystemFilePickerEnabled(BuildContext context) async { + if (await deviceService.isSystemFilePickerEnabled()) return true; + + await showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.missingSystemFilePickerDialogMessage), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + return false; + } +} diff --git a/lib/widgets/common/action_mixins/size_aware.dart b/lib/widgets/common/action_mixins/size_aware.dart new file mode 100644 index 0000000..0510ea0 --- /dev/null +++ b/lib/widgets/common/action_mixins/size_aware.dart @@ -0,0 +1,92 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +mixin SizeAwareMixin { + Future<bool> checkFreeSpaceForMove( + BuildContext context, + Set<AvesEntry> selection, + String destinationAlbum, + MoveType moveType, + ) async { + if (moveType == MoveType.toBin) return true; + + // assume we have enough space if we cannot find the volume or its remaining free space + final destinationVolume = androidFileUtils.getStorageVolume(destinationAlbum); + if (destinationVolume == null) return true; + + final free = await storageService.getFreeSpace(destinationVolume); + if (free == null) return true; + + late int needed; + int sumSize(int sum, AvesEntry entry) => sum + (entry.sizeBytes ?? 0); + switch (moveType) { + case MoveType.copy: + case MoveType.export: + needed = selection.fold(0, sumSize); + case MoveType.move: + case MoveType.toBin: + case MoveType.fromBin: + // when moving, we only need space for the entries that are not already on the destination volume + final byVolume = groupBy<AvesEntry, StorageVolume?>(selection, (entry) => androidFileUtils.getStorageVolume(entry.path)).whereNotNullKey(); + final otherVolumes = byVolume.keys.where((volume) => volume != destinationVolume); + final fromOtherVolumes = otherVolumes.fold<int>(0, (sum, volume) => sum + byVolume[volume]!.fold(0, sumSize)); + // and we need at least as much space as the largest entry because individual entries are copied then deleted + final largestSingle = selection.fold<int>(0, (largest, entry) => max(largest, entry.sizeBytes ?? 0)); + needed = max(fromOtherVolumes, largestSingle); + } + + final hasEnoughSpace = needed < free; + if (!hasEnoughSpace) { + await _showNotEnoughSpaceDialog(context, needed, free, destinationVolume); + } + return hasEnoughSpace; + } + + Future<bool> checkFreeSpace( + BuildContext context, + int needed, + String destinationAlbum, + ) async { + // assume we have enough space if we cannot find the volume or its remaining free space + final destinationVolume = androidFileUtils.getStorageVolume(destinationAlbum); + if (destinationVolume == null) return true; + + final free = await storageService.getFreeSpace(destinationVolume); + if (free == null) return true; + + final hasEnoughSpace = needed < free; + if (!hasEnoughSpace) { + await _showNotEnoughSpaceDialog(context, needed, free, destinationVolume); + } + return hasEnoughSpace; + } + + Future<void> _showNotEnoughSpaceDialog(BuildContext context, int needed, int free, StorageVolume destinationVolume) async { + await showDialog( + context: context, + builder: (context) { + final locale = context.locale; + final neededSize = formatFileSize(locale, needed); + final freeSize = formatFileSize(locale, free); + final volume = destinationVolume.getDescription(context); + return AvesDialog( + content: Text(context.l10n.notEnoughSpaceDialogMessage(neededSize, freeSize, volume)), + actions: const [OkButton()], + ); + }, + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } +} diff --git a/lib/widgets/common/action_mixins/vault_aware.dart b/lib/widgets/common/action_mixins/vault_aware.dart new file mode 100644 index 0000000..45ece04 --- /dev/null +++ b/lib/widgets/common/action_mixins/vault_aware.dart @@ -0,0 +1,149 @@ +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/password_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/pattern_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/pin_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:local_auth/error_codes.dart' as auth_error; +import 'package:local_auth/local_auth.dart'; + +mixin VaultAwareMixin on FeedbackMixin { + Future<bool> _tryUnlock(BuildContext context, String dirPath) async { + if (!vaults.isVault(dirPath) || !vaults.isLocked(dirPath)) return true; + + final details = vaults.detailsForPath(dirPath); + if (details == null) return false; + + bool? confirmed; + switch (details.lockType) { + case VaultLockType.system: + try { + confirmed = await LocalAuthentication().authenticate( + localizedReason: context.l10n.authenticateToUnlockVault, + ); + } on PlatformException catch (e, stack) { + if (!{'auth_in_progress', 'NotAvailable'}.contains(e.code)) { + // `auth_in_progress`: `Authentication in progress` + // `NotAvailable`: `Required security features not enabled` + await reportService.recordError(e, stack); + } + } + case VaultLockType.pattern: + final pattern = await showDialog<String>( + context: context, + builder: (context) => const PatternDialog(needConfirmation: false), + routeSettings: const RouteSettings(name: PatternDialog.routeName), + ); + if (pattern != null) { + confirmed = pattern == await securityService.readValue(details.passKey); + } + case VaultLockType.pin: + final pin = await showDialog<String>( + context: context, + builder: (context) => const PinDialog(needConfirmation: false), + routeSettings: const RouteSettings(name: PinDialog.routeName), + ); + if (pin != null) { + confirmed = pin == await securityService.readValue(details.passKey); + } + case VaultLockType.password: + final password = await showDialog<String>( + context: context, + builder: (context) => const PasswordDialog(needConfirmation: false), + routeSettings: const RouteSettings(name: PasswordDialog.routeName), + ); + if (password != null) { + confirmed = password == await securityService.readValue(details.passKey); + } + } + + if (confirmed == null || !confirmed) return false; + + await vaults.unlock(context, dirPath); + return true; + } + + Future<bool> unlockAlbum(BuildContext context, String dirPath) async { + final success = await _tryUnlock(context, dirPath); + if (!success) { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + return success; + } + + Future<bool> unlockFilter(BuildContext context, CollectionFilter filter) { + return filter is StoredAlbumFilter ? unlockAlbum(context, filter.album) : Future.value(true); + } + + Future<bool> unlockFilters(BuildContext context, Set<CollectionFilter> filters) async { + var unlocked = true; + await Future.forEach(filters, (filter) async { + if (unlocked) { + unlocked = await unlockFilter(context, filter); + } + }); + return unlocked; + } + + void lockFilters(Set<StoredAlbumFilter> filters) => vaults.lock(filters.map((v) => v.album).toSet()); + + Future<bool> setVaultPass(BuildContext context, VaultDetails details) async { + switch (details.lockType) { + case VaultLockType.system: + final l10n = context.l10n; + try { + return await LocalAuthentication().authenticate( + localizedReason: l10n.authenticateToConfigureVault, + ); + } on PlatformException catch (e, stack) { + await showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(e.message ?? l10n.genericFailureFeedback), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (e.code != auth_error.notAvailable) { + await reportService.recordError(e, stack); + } + } + case VaultLockType.pattern: + final pattern = await showDialog<String>( + context: context, + builder: (context) => const PatternDialog(needConfirmation: true), + routeSettings: const RouteSettings(name: PatternDialog.routeName), + ); + if (pattern != null) { + return await securityService.writeValue(details.passKey, pattern); + } + case VaultLockType.pin: + final pin = await showDialog<String>( + context: context, + builder: (context) => const PinDialog(needConfirmation: true), + routeSettings: const RouteSettings(name: PinDialog.routeName), + ); + if (pin != null) { + return await securityService.writeValue(details.passKey, pin); + } + case VaultLockType.password: + final password = await showDialog<String>( + context: context, + builder: (context) => const PasswordDialog(needConfirmation: true), + routeSettings: const RouteSettings(name: PasswordDialog.routeName), + ); + if (password != null) { + return await securityService.writeValue(details.passKey, password); + } + } + return false; + } +} diff --git a/lib/widgets/common/app_bar/app_bar_subtitle.dart b/lib/widgets/common/app_bar/app_bar_subtitle.dart new file mode 100644 index 0000000..4eb44ee --- /dev/null +++ b/lib/widgets/common/app_bar/app_bar_subtitle.dart @@ -0,0 +1,93 @@ +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/events.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class SourceStateAwareAppBarTitle extends StatelessWidget { + final Widget title; + final CollectionSource source; + + const SourceStateAwareAppBarTitle({ + super.key, + required this.title, + required this.source, + }); + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title, + ValueListenableBuilder<SourceState>( + valueListenable: source.stateNotifier, + builder: (context, sourceState, child) { + return AnimatedSwitcher( + duration: ADurations.appBarTitleAnimation, + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: SizeTransition( + sizeFactor: animation, + child: child, + ), + ), + child: sourceState == SourceState.ready + ? const SizedBox() + : SourceStateSubtitle( + source: source, + ), + ); + }, + ), + ], + ); + } +} + +class SourceStateSubtitle extends StatelessWidget { + final CollectionSource source; + + const SourceStateSubtitle({ + super.key, + required this.source, + }); + + @override + Widget build(BuildContext context) { + final sourceState = source.state; + final subtitle = sourceState.getName(context.l10n); + if (subtitle == null) return const SizedBox(); + + final theme = Theme.of(context); + return DefaultTextStyle.merge( + style: theme.textTheme.bodySmall!.copyWith(fontFeatures: const [FontFeature.disable('smcp')]), + child: ValueListenableBuilder<ProgressEvent>( + valueListenable: source.progressNotifier, + builder: (context, progress, snapshot) { + return Text.rich( + TextSpan( + children: [ + TextSpan(text: subtitle), + if (progress.total != 0 && sourceState != SourceState.locatingCountries) ...[ + const WidgetSpan(child: SizedBox(width: 8)), + TextSpan( + text: '${progress.done}/${progress.total}', + style: TextStyle(color: theme.isDark ? Colors.white30 : Colors.black26), + ), + ] + ], + ), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + }, + ), + ); + } +} diff --git a/lib/widgets/common/app_bar/app_bar_title.dart b/lib/widgets/common/app_bar/app_bar_title.dart new file mode 100644 index 0000000..cd9f0f9 --- /dev/null +++ b/lib/widgets/common/app_bar/app_bar_title.dart @@ -0,0 +1,28 @@ +import 'package:flutter/material.dart'; + +class InteractiveAppBarTitle extends StatelessWidget { + final GestureTapCallback? onTap; + final Widget child; + + const InteractiveAppBarTitle({ + super.key, + this.onTap, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return GestureDetector( + onTap: onTap, + // use a `Container` with a dummy color to make it expand + // so that we can also detect taps around the title `Text` + child: Container( + alignment: AlignmentDirectional.centerStart, + color: Colors.transparent, + height: textScaler.scale(kToolbarHeight), + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/app_bar/crumb_line.dart b/lib/widgets/common/app_bar/crumb_line.dart new file mode 100644 index 0000000..580f1ec --- /dev/null +++ b/lib/widgets/common/app_bar/crumb_line.dart @@ -0,0 +1,106 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CrumbLine<T> extends StatefulWidget { + final List<String> Function(BuildContext context) split; + final T Function(BuildContext context, int index) combine; + final void Function(T combined) onTap; + + static const EdgeInsets padding = EdgeInsets.only(top: 6, bottom: 20); + + const CrumbLine({ + super.key, + required this.split, + required this.combine, + required this.onTap, + }); + + @override + State<CrumbLine<T>> createState() => _CrumbLineState<T>(); + + static double getPreferredHeight(TextScaler textScaler) => textScaler.scale(22) + padding.vertical; +} + +class _CrumbLineState<T> extends State<CrumbLine<T>> { + final ScrollController _scrollController = ScrollController(); + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + @override + void didUpdateWidget(covariant CrumbLine<T> oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.split(context).length < widget.split(context).length) { + // scroll to show last crumb + WidgetsBinding.instance.addPostFrameCallback((_) { + final animate = context.read<Settings>().animate; + final extent = _scrollController.position.maxScrollExtent; + if (animate) { + _scrollController.animateTo( + extent, + duration: const Duration(milliseconds: 500), + curve: Curves.easeOutQuad, + ); + } else { + _scrollController.jumpTo(extent); + } + }); + } + } + + @override + Widget build(BuildContext context) { + final parts = widget.split(context); + + final crumbColor = DefaultTextStyle.of(context).style.color; + return ListView.builder( + scrollDirection: Axis.horizontal, + controller: _scrollController, + padding: const EdgeInsets.symmetric(horizontal: 8), + itemBuilder: (context, index) { + Widget _buildText(String text) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Text(text), + ); + + if (index >= parts.length) return const SizedBox(); + final text = parts[index]; + if (index == parts.length - 1) { + return Center( + child: DefaultTextStyle.merge( + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + ), + child: _buildText(text), + ), + ); + } + return GestureDetector( + onTap: parts.isNotEmpty ? () => widget.onTap(widget.combine(context, index)) : null, + child: Container( + // use a `Container` with a dummy color to make it expand + // so that we can also detect taps around the title `Text` + color: Colors.transparent, + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + _buildText(text), + Icon( + AIcons.next, + color: crumbColor, + ), + ], + ), + ), + ); + }, + itemCount: parts.length, + ); + } +} diff --git a/lib/widgets/common/app_bar/sliver_app_bar_title.dart b/lib/widgets/common/app_bar/sliver_app_bar_title.dart new file mode 100644 index 0000000..08b15cf --- /dev/null +++ b/lib/widgets/common/app_bar/sliver_app_bar_title.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +// as of Flutter v2.8.1, fading opacity in `SliverAppBar` +// is not applied to title when `appBarTheme.titleTextStyle` is defined, +// so this wrapper manually applies opacity to the default text style +class SliverAppBarTitleWrapper extends StatelessWidget { + final Widget child; + + const SliverAppBarTitleWrapper({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final toolbarOpacity = context.dependOnInheritedWidgetOfExactType<FlexibleSpaceBarSettings>()!.toolbarOpacity; + final baseColor = (DefaultTextStyle.of(context).style.color ?? Theme.of(context).textTheme.titleLarge!.color!); + return DefaultTextStyle.merge( + style: TextStyle(color: baseColor.withValues(alpha: toolbarOpacity)), + child: child, + ); + } +} diff --git a/lib/widgets/common/aves_highlight.dart b/lib/widgets/common/aves_highlight.dart new file mode 100644 index 0000000..3a2f4f0 --- /dev/null +++ b/lib/widgets/common/aves_highlight.dart @@ -0,0 +1,103 @@ +// ignore_for_file: depend_on_referenced_packages +import 'package:flutter/material.dart'; +import 'package:highlight/highlight.dart' show highlight, Node; + +// adapted from package `flutter_highlight` v0.7.0 `HighlightView` +// TODO TLAD use the TextSpan getter when this is fixed: https://github.com/git-touch/highlight/issues/6 + +/// Highlight Flutter Widget +class AvesHighlightView extends StatelessWidget { + /// The original code to be highlighted + final String source; + + /// Highlight language + /// + /// It is recommended to give it a value for performance + /// + /// [All available languages](https://github.com/pd4d10/highlight/tree/master/highlight/lib/languages) + final String? language; + + /// Highlight theme + /// + /// [All available themes](https://github.com/pd4d10/highlight/blob/master/flutter_highlight/lib/themes) + final Map<String, TextStyle> theme; + + /// Padding + final EdgeInsetsGeometry? padding; + + /// Text styles + /// + /// Specify text styles such as font family and font size + final TextStyle? textStyle; + + AvesHighlightView({ + super.key, + required String input, + this.language, + this.theme = const {}, + this.padding, + this.textStyle, + int tabSize = 8, // TODO: https://github.com/flutter/flutter/issues/50087 + }) : source = input.replaceAll('\t', ' ' * tabSize); + + List<TextSpan> _convert(List<Node> nodes) { + final spans = <TextSpan>[]; + var currentSpans = spans; + final stack = <List<TextSpan>>[]; + + void _traverse(Node node) { + if (node.value != null) { + currentSpans.add(node.className == null ? TextSpan(text: node.value) : TextSpan(text: node.value, style: theme[node.className!])); + } else if (node.children != null) { + final tmp = <TextSpan>[]; + currentSpans.add(TextSpan(children: tmp, style: theme[node.className!])); + stack.add(currentSpans); + currentSpans = tmp; + + node.children!.forEach((n) { + _traverse(n); + if (n == node.children!.last) { + currentSpans = stack.isEmpty ? spans : stack.removeLast(); + } + }); + } + } + + for (var node in nodes) { + _traverse(node); + } + + return spans; + } + + static const _rootKey = 'root'; + static const _defaultFontColor = Color(0xff000000); + static const _defaultBackgroundColor = Color(0xffffffff); + + // TODO: dart:io is not available at web platform currently + // See: https://github.com/flutter/flutter/issues/39998 + // So we just use monospace here for now + static const _defaultFontFamily = 'monospace'; + + @override + Widget build(BuildContext context) { + var _textStyle = TextStyle( + fontFamily: _defaultFontFamily, + color: theme[_rootKey]?.color ?? _defaultFontColor, + ); + if (textStyle != null) { + _textStyle = _textStyle.merge(textStyle); + } + + return Container( + color: theme[_rootKey]?.backgroundColor ?? _defaultBackgroundColor, + padding: padding, + child: SelectableText.rich( + TextSpan( + style: _textStyle, + children: _convert(highlight.parse(source, language: language).nodes!), + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/circle.dart b/lib/widgets/common/basic/circle.dart new file mode 100644 index 0000000..0b3fdba --- /dev/null +++ b/lib/widgets/common/basic/circle.dart @@ -0,0 +1,108 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; + +class CircularIndicator extends StatefulWidget { + final double radius, lineWidth, percent; + final Color background, foreground; + final Widget center; + + const CircularIndicator({ + super.key, + required this.radius, + required this.lineWidth, + required this.percent, + required this.background, + required this.foreground, + required this.center, + }); + + @override + State<CircularIndicator> createState() => _CircularIndicatorState(); +} + +class _CircularIndicatorState extends State<CircularIndicator> { + @override + Widget build(BuildContext context) { + return SizedBox.square( + dimension: widget.radius * 2, + child: Stack( + alignment: Alignment.center, + children: [ + _Circle( + radius: widget.radius, + lineWidth: widget.lineWidth, + percent: 1.0, + color: widget.background, + ), + _Circle( + radius: widget.radius, + lineWidth: widget.lineWidth, + percent: widget.percent, + color: widget.foreground, + ), + widget.center, + ], + ), + ); + } +} + +class _Circle extends StatelessWidget { + final double radius, lineWidth, percent; + final Color color; + + const _Circle({ + required this.radius, + required this.lineWidth, + required this.percent, + required this.color, + }); + + @override + Widget build(BuildContext context) { + return CustomPaint( + size: Size.square(radius), + painter: _CirclePainter( + lineWidth: lineWidth, + radius: radius - lineWidth / 2, + color: color, + percent: percent, + ), + ); + } +} + +class _CirclePainter extends CustomPainter { + final double radius, lineWidth, percent; + final Color color; + + const _CirclePainter({ + required this.radius, + required this.lineWidth, + required this.percent, + required this.color, + }); + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + final paint = Paint() + ..style = PaintingStyle.stroke + ..color = color + ..strokeWidth = lineWidth; + + canvas.translate(center.dx, center.dy); + canvas.rotate(-pi / 2); + canvas.drawArc( + Rect.fromCircle(center: Offset.zero, radius: radius), + 0, + 2 * pi * percent, + false, + paint, + ); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/basic/color_indicator.dart b/lib/widgets/common/basic/color_indicator.dart new file mode 100644 index 0000000..85b5da0 --- /dev/null +++ b/lib/widgets/common/basic/color_indicator.dart @@ -0,0 +1,46 @@ +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:flutter/widgets.dart'; + +class ColorIndicator extends StatelessWidget { + final Color? value; + final Color? alternate; + final Widget? child; + + static const double radius = 16; + + const ColorIndicator({ + super.key, + required this.value, + this.alternate, + this.child, + }); + + @override + Widget build(BuildContext context) { + const dimension = radius * 2; + + Gradient? gradient; + final _value = value; + final _alternate = alternate; + if (_value != null && _alternate != null && _alternate != _value) { + gradient = LinearGradient( + begin: AlignmentDirectional.topStart, + end: AlignmentDirectional.bottomEnd, + colors: [_value, _value, _alternate, _alternate], + stops: const [0, .5, .5, 1], + ); + } + + return Container( + height: dimension, + width: dimension, + decoration: BoxDecoration( + color: _value, + border: AvesBorder.border(context), + gradient: gradient, + shape: BoxShape.circle, + ), + child: child, + ); + } +} diff --git a/lib/widgets/common/basic/derived_material_localization.dart b/lib/widgets/common/basic/derived_material_localization.dart new file mode 100644 index 0000000..59bdca1 --- /dev/null +++ b/lib/widgets/common/basic/derived_material_localization.dart @@ -0,0 +1,524 @@ +import 'package:aves/services/common/services.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +// apply custom regional preferences on context localization +// until this is fixed: https://github.com/flutter/flutter/issues/122274 +class MaterialLocalizationsRegionalizer extends StatefulWidget { + final Widget child; + + const MaterialLocalizationsRegionalizer({ + super.key, + required this.child, + }); + + @override + State<MaterialLocalizationsRegionalizer> createState() => _MaterialLocalizationsRegionalizerState(); +} + +class _MaterialLocalizationsRegionalizerState extends State<MaterialLocalizationsRegionalizer> { + late final Future<int?> _firstDayOfWeekLoader; + + @override + void initState() { + super.initState(); + _firstDayOfWeekLoader = deviceService.getFirstDayOfWeekIndex(); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder<int?>( + future: _firstDayOfWeekLoader, + builder: (context, snapshot) { + final firstDayOfWeekIndex = snapshot.data; + final localizationsDelegate = DerivedMaterialLocalizationsDelegate( + Localizations.localeOf(context), + DerivedMaterialLocalizations( + parent: MaterialLocalizations.of(context), + firstDayOfWeekIndex: firstDayOfWeekIndex, + ), + ); + return Localizations.override( + context: context, + delegates: [localizationsDelegate], + child: widget.child, + ); + }, + ); + } +} + +class DerivedMaterialLocalizationsDelegate extends LocalizationsDelegate<MaterialLocalizations> { + final Locale locale; + final MaterialLocalizations localizations; + + const DerivedMaterialLocalizationsDelegate(this.locale, this.localizations); + + @override + bool isSupported(Locale locale) => locale == this.locale; + + @override + Future<MaterialLocalizations> load(Locale locale) async { + return SynchronousFuture<MaterialLocalizations>(localizations); + } + + @override + bool shouldReload(DerivedMaterialLocalizationsDelegate old) => true; +} + +class DerivedMaterialLocalizations extends MaterialLocalizations { + final MaterialLocalizations parent; + final int? _firstDayOfWeekIndex; + + DerivedMaterialLocalizations({ + required this.parent, + int? firstDayOfWeekIndex, + }) : _firstDayOfWeekIndex = firstDayOfWeekIndex; + + @override + String aboutListTileTitle(String applicationName) => parent.aboutListTileTitle(applicationName); + + @override + String get alertDialogLabel => parent.alertDialogLabel; + + @override + String get anteMeridiemAbbreviation => parent.anteMeridiemAbbreviation; + + @override + String get backButtonTooltip => parent.backButtonTooltip; + + @override + String get bottomSheetLabel => parent.bottomSheetLabel; + + @override + String get calendarModeButtonLabel => parent.calendarModeButtonLabel; + + @override + String get cancelButtonLabel => parent.cancelButtonLabel; + + @override + String get clearButtonTooltip => parent.clearButtonTooltip; + + @override + String get closeButtonLabel => parent.closeButtonLabel; + + @override + String get closeButtonTooltip => parent.closeButtonTooltip; + + @override + String get continueButtonLabel => parent.continueButtonLabel; + + @override + String get copyButtonLabel => parent.copyButtonLabel; + + @override + String get currentDateLabel => parent.currentDateLabel; + + @override + String get cutButtonLabel => parent.cutButtonLabel; + + @override + String get dateHelpText => parent.dateHelpText; + + @override + String get dateInputLabel => parent.dateInputLabel; + + @override + String get dateOutOfRangeLabel => parent.dateOutOfRangeLabel; + + @override + String get datePickerHelpText => parent.datePickerHelpText; + + @override + String dateRangeEndDateSemanticLabel(String formattedDate) => parent.dateRangeEndDateSemanticLabel(formattedDate); + + @override + String get dateRangeEndLabel => parent.dateRangeEndLabel; + + @override + String get dateRangePickerHelpText => parent.dateRangePickerHelpText; + + @override + String dateRangeStartDateSemanticLabel(String formattedDate) => parent.dateRangeStartDateSemanticLabel(formattedDate); + + @override + String get dateRangeStartLabel => parent.dateRangeStartLabel; + + @override + String get dateSeparator => parent.dateSeparator; + + @override + String get deleteButtonTooltip => parent.deleteButtonTooltip; + + @override + String get dialModeButtonLabel => parent.dialModeButtonLabel; + + @override + String get dialogLabel => parent.dialogLabel; + + @override + String get drawerLabel => parent.drawerLabel; + + @override + int get firstDayOfWeekIndex => _firstDayOfWeekIndex ?? parent.firstDayOfWeekIndex; + + @override + String get firstPageTooltip => parent.firstPageTooltip; + + @override + String formatCompactDate(DateTime date) => parent.formatCompactDate(date); + + @override + String formatDecimal(int number) => parent.formatDecimal(number); + + @override + String formatFullDate(DateTime date) => parent.formatFullDate(date); + + @override + String formatHour(TimeOfDay timeOfDay, {bool alwaysUse24HourFormat = false}) => parent.formatHour(timeOfDay, alwaysUse24HourFormat: alwaysUse24HourFormat); + + @override + String formatMediumDate(DateTime date) => parent.formatMediumDate(date); + + @override + String formatMinute(TimeOfDay timeOfDay) => parent.formatMinute(timeOfDay); + + @override + String formatMonthYear(DateTime date) => parent.formatMonthYear(date); + + @override + String formatShortDate(DateTime date) => parent.formatShortDate(date); + + @override + String formatShortMonthDay(DateTime date) => parent.formatShortMonthDay(date); + + @override + String formatTimeOfDay(TimeOfDay timeOfDay, {bool alwaysUse24HourFormat = false}) => parent.formatTimeOfDay(timeOfDay); + + @override + String formatYear(DateTime date) => parent.formatYear(date); + + @override + String get hideAccountsLabel => parent.hideAccountsLabel; + + @override + String get inputDateModeButtonLabel => parent.inputDateModeButtonLabel; + + @override + String get inputTimeModeButtonLabel => parent.inputTimeModeButtonLabel; + + @override + String get invalidDateFormatLabel => parent.invalidDateFormatLabel; + + @override + String get invalidDateRangeLabel => parent.invalidDateRangeLabel; + + @override + String get invalidTimeLabel => parent.invalidTimeLabel; + + @override + String get keyboardKeyAlt => parent.keyboardKeyAlt; + + @override + String get keyboardKeyAltGraph => parent.keyboardKeyAltGraph; + + @override + String get keyboardKeyBackspace => parent.keyboardKeyBackspace; + + @override + String get keyboardKeyCapsLock => parent.keyboardKeyCapsLock; + + @override + String get keyboardKeyChannelDown => parent.keyboardKeyChannelDown; + + @override + String get keyboardKeyChannelUp => parent.keyboardKeyChannelUp; + + @override + String get keyboardKeyControl => parent.keyboardKeyControl; + + @override + String get keyboardKeyDelete => parent.keyboardKeyDelete; + + @override + String get keyboardKeyEject => parent.keyboardKeyEject; + + @override + String get keyboardKeyEnd => parent.keyboardKeyEnd; + + @override + String get keyboardKeyEscape => parent.keyboardKeyEscape; + + @override + String get keyboardKeyFn => parent.keyboardKeyFn; + + @override + String get keyboardKeyHome => parent.keyboardKeyHome; + + @override + String get keyboardKeyInsert => parent.keyboardKeyInsert; + + @override + String get keyboardKeyMeta => parent.keyboardKeyMeta; + + @override + String get keyboardKeyMetaMacOs => parent.keyboardKeyMetaMacOs; + + @override + String get keyboardKeyMetaWindows => parent.keyboardKeyMetaWindows; + + @override + String get keyboardKeyNumLock => parent.keyboardKeyNumLock; + + @override + String get keyboardKeyNumpad0 => parent.keyboardKeyNumpad0; + + @override + String get keyboardKeyNumpad1 => parent.keyboardKeyNumpad1; + + @override + String get keyboardKeyNumpad2 => parent.keyboardKeyNumpad2; + + @override + String get keyboardKeyNumpad3 => parent.keyboardKeyNumpad3; + + @override + String get keyboardKeyNumpad4 => parent.keyboardKeyNumpad4; + + @override + String get keyboardKeyNumpad5 => parent.keyboardKeyNumpad5; + + @override + String get keyboardKeyNumpad6 => parent.keyboardKeyNumpad6; + + @override + String get keyboardKeyNumpad7 => parent.keyboardKeyNumpad7; + + @override + String get keyboardKeyNumpad8 => parent.keyboardKeyNumpad8; + + @override + String get keyboardKeyNumpad9 => parent.keyboardKeyNumpad9; + + @override + String get keyboardKeyNumpadAdd => parent.keyboardKeyNumpadAdd; + + @override + String get keyboardKeyNumpadComma => parent.keyboardKeyNumpadComma; + + @override + String get keyboardKeyNumpadDecimal => parent.keyboardKeyNumpadDecimal; + + @override + String get keyboardKeyNumpadDivide => parent.keyboardKeyNumpadDivide; + + @override + String get keyboardKeyNumpadEnter => parent.keyboardKeyNumpadEnter; + + @override + String get keyboardKeyNumpadEqual => parent.keyboardKeyNumpadEqual; + + @override + String get keyboardKeyNumpadMultiply => parent.keyboardKeyNumpadMultiply; + + @override + String get keyboardKeyNumpadParenLeft => parent.keyboardKeyNumpadParenLeft; + + @override + String get keyboardKeyNumpadParenRight => parent.keyboardKeyNumpadParenRight; + + @override + String get keyboardKeyNumpadSubtract => parent.keyboardKeyNumpadSubtract; + + @override + String get keyboardKeyPageDown => parent.keyboardKeyPageDown; + + @override + String get keyboardKeyPageUp => parent.keyboardKeyPageUp; + + @override + String get keyboardKeyPower => parent.keyboardKeyPower; + + @override + String get keyboardKeyPowerOff => parent.keyboardKeyPowerOff; + + @override + String get keyboardKeyPrintScreen => parent.keyboardKeyPrintScreen; + + @override + String get keyboardKeyScrollLock => parent.keyboardKeyScrollLock; + + @override + String get keyboardKeySelect => parent.keyboardKeySelect; + + @override + String get keyboardKeyShift => parent.keyboardKeyShift; + + @override + String get keyboardKeySpace => parent.keyboardKeySpace; + + @override + String get lastPageTooltip => parent.lastPageTooltip; + + @override + String licensesPackageDetailText(int licenseCount) => parent.licensesPackageDetailText(licenseCount); + + @override + String get licensesPageTitle => parent.licensesPageTitle; + + @override + String get lookUpButtonLabel => parent.lookUpButtonLabel; + + @override + String get menuBarMenuLabel => parent.menuBarMenuLabel; + + @override + String get menuDismissLabel => parent.menuDismissLabel; + + @override + String get modalBarrierDismissLabel => parent.modalBarrierDismissLabel; + + @override + String get moreButtonTooltip => parent.moreButtonTooltip; + + @override + List<String> get narrowWeekdays => parent.narrowWeekdays; + + @override + String get nextMonthTooltip => parent.nextMonthTooltip; + + @override + String get nextPageTooltip => parent.nextPageTooltip; + + @override + String get okButtonLabel => parent.okButtonLabel; + + @override + String get openAppDrawerTooltip => parent.openAppDrawerTooltip; + + @override + String pageRowsInfoTitle(int firstRow, int lastRow, int rowCount, bool rowCountIsApproximate) => parent.pageRowsInfoTitle(firstRow, lastRow, rowCount, rowCountIsApproximate); + + @override + DateTime? parseCompactDate(String? inputString) => parent.parseCompactDate(inputString); + + @override + String get pasteButtonLabel => parent.pasteButtonLabel; + + @override + String get popupMenuLabel => parent.popupMenuLabel; + + @override + String get postMeridiemAbbreviation => parent.postMeridiemAbbreviation; + + @override + String get previousMonthTooltip => parent.previousMonthTooltip; + + @override + String get previousPageTooltip => parent.previousPageTooltip; + + @override + String get refreshIndicatorSemanticLabel => parent.refreshIndicatorSemanticLabel; + + @override + String remainingTextFieldCharacterCount(int remaining) => parent.remainingTextFieldCharacterCount(remaining); + + @override + String get reorderItemDown => throw UnimplementedError(); + + @override + String get reorderItemLeft => throw UnimplementedError(); + + @override + String get reorderItemRight => throw UnimplementedError(); + + @override + String get reorderItemToEnd => throw UnimplementedError(); + + @override + String get reorderItemToStart => throw UnimplementedError(); + + @override + String get reorderItemUp => throw UnimplementedError(); + + @override + String get rowsPerPageTitle => parent.rowsPerPageTitle; + + @override + String get saveButtonLabel => parent.saveButtonLabel; + + @override + String get scanTextButtonLabel => parent.scanTextButtonLabel; + + @override + String get scrimLabel => parent.scrimLabel; + + @override + String scrimOnTapHint(String modalRouteContentName) => parent.scrimOnTapHint(modalRouteContentName); + + @override + ScriptCategory get scriptCategory => parent.scriptCategory; + + @override + String get searchFieldLabel => parent.searchFieldLabel; + + @override + String get searchWebButtonLabel => parent.searchWebButtonLabel; + + @override + String get selectAllButtonLabel => parent.selectAllButtonLabel; + + @override + String get selectYearSemanticsLabel => parent.selectYearSemanticsLabel; + + @override + String get selectedDateLabel => parent.selectedDateLabel; + + @override + String selectedRowCountTitle(int selectedRowCount) => parent.selectedRowCountTitle(selectedRowCount); + + @override + String get shareButtonLabel => parent.shareButtonLabel; + + @override + String get showAccountsLabel => parent.showAccountsLabel; + + @override + String get showMenuTooltip => parent.showMenuTooltip; + + @override + String get signedInLabel => parent.signedInLabel; + + @override + String tabLabel({required int tabIndex, required int tabCount}) => parent.tabLabel(tabIndex: tabIndex, tabCount: tabCount); + + @override + TimeOfDayFormat timeOfDayFormat({bool alwaysUse24HourFormat = false}) => parent.timeOfDayFormat(alwaysUse24HourFormat: alwaysUse24HourFormat); + + @override + String get timePickerDialHelpText => parent.timePickerDialHelpText; + + @override + String get timePickerHourLabel => parent.timePickerHourLabel; + + @override + String get timePickerHourModeAnnouncement => parent.timePickerHourModeAnnouncement; + + @override + String get timePickerInputHelpText => parent.timePickerInputHelpText; + + @override + String get timePickerMinuteLabel => parent.timePickerMinuteLabel; + + @override + String get timePickerMinuteModeAnnouncement => parent.timePickerMinuteModeAnnouncement; + + @override + String get unspecifiedDate => parent.unspecifiedDate; + + @override + String get unspecifiedDateRange => parent.unspecifiedDateRange; + + @override + String get viewLicensesButtonLabel => parent.viewLicensesButtonLabel; +} diff --git a/lib/widgets/common/basic/draggable_scrollbar/arrow_clipper.dart b/lib/widgets/common/basic/draggable_scrollbar/arrow_clipper.dart new file mode 100644 index 0000000..94deba5 --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/arrow_clipper.dart @@ -0,0 +1,38 @@ +import 'package:flutter/rendering.dart'; + +class ArrowClipper extends CustomClipper<Path> { + @override + Path getClip(Size size) { + final path = Path(); + path.lineTo(0.0, size.height); + path.lineTo(size.width, size.height); + path.lineTo(size.width, 0.0); + path.lineTo(0.0, 0.0); + path.close(); + + const double arrowWidth = 8.0; + final startPointX = (size.width - arrowWidth) / 2; + var startPointY = size.height / 2 - arrowWidth / 2; + path.moveTo(startPointX, startPointY); + path.lineTo(startPointX + arrowWidth / 2, startPointY - arrowWidth / 2); + path.lineTo(startPointX + arrowWidth, startPointY); + path.lineTo(startPointX + arrowWidth, startPointY + 1.0); + path.lineTo(startPointX + arrowWidth / 2, startPointY - arrowWidth / 2 + 1.0); + path.lineTo(startPointX, startPointY + 1.0); + path.close(); + + startPointY = size.height / 2 + arrowWidth / 2; + path.moveTo(startPointX + arrowWidth, startPointY); + path.lineTo(startPointX + arrowWidth / 2, startPointY + arrowWidth / 2); + path.lineTo(startPointX, startPointY); + path.lineTo(startPointX, startPointY - 1.0); + path.lineTo(startPointX + arrowWidth / 2, startPointY + arrowWidth / 2 - 1.0); + path.lineTo(startPointX + arrowWidth, startPointY - 1.0); + path.close(); + + return path; + } + + @override + bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false; +} diff --git a/lib/widgets/common/basic/draggable_scrollbar/notifications.dart b/lib/widgets/common/basic/draggable_scrollbar/notifications.dart new file mode 100644 index 0000000..28ca11d --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/notifications.dart @@ -0,0 +1,10 @@ +import 'package:flutter/widgets.dart'; + +@immutable +class DraggableScrollbarNotification extends Notification { + final DraggableScrollbarEvent event; + + const DraggableScrollbarNotification(this.event); +} + +enum DraggableScrollbarEvent { dragStart, dragEnd } diff --git a/lib/widgets/common/basic/draggable_scrollbar/scroll_label.dart b/lib/widgets/common/basic/draggable_scrollbar/scroll_label.dart new file mode 100644 index 0000000..e42c171 --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/scroll_label.dart @@ -0,0 +1,30 @@ +import 'package:flutter/material.dart'; + +class ScrollLabel extends StatelessWidget { + final Animation<double> animation; + final Color backgroundColor; + final Widget child; + + const ScrollLabel({ + super.key, + required this.child, + required this.animation, + required this.backgroundColor, + }); + + @override + Widget build(BuildContext context) { + return FadeTransition( + opacity: animation, + child: Container( + margin: const EdgeInsetsDirectional.only(end: 12.0), + child: Material( + elevation: 4.0, + color: backgroundColor, + borderRadius: const BorderRadius.all(Radius.circular(16)), + child: child, + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/draggable_scrollbar/scrollbar.dart b/lib/widgets/common/basic/draggable_scrollbar/scrollbar.dart new file mode 100644 index 0000000..245e2a6 --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/scrollbar.dart @@ -0,0 +1,364 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/notifications.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/scroll_label.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/transition.dart'; +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:flutter/widgets.dart'; + +/* + adapted from package `draggable_scrollbar` v0.0.4: + - removed default thumb builders + - allow any `ScrollView` as child + - allow any `Widget` as label content + - moved out constraints responsibility + - various extent & thumb positioning fixes + - null safety + - directionality aware + */ + +/// Build the Scroll Thumb and label using the current configuration +typedef ScrollThumbBuilder = Widget Function( + Color backgroundColor, + Animation<double> thumbAnimation, + Animation<double> labelAnimation, + double height, { + Widget? labelText, +}); + +/// Build a Text widget using the current scroll offset +typedef OffsetLabelBuilder = Widget Function(double offsetY); +typedef TextLabelBuilder = Widget Function(String label); + +/// A widget that will display a BoxScrollView with a ScrollThumb that can be dragged +/// for quick navigation of the BoxScrollView. +class DraggableScrollbar extends StatefulWidget { + /// The background color of the label and thumb + final Color backgroundColor; + + final Map<double, String> Function()? crumbsBuilder; + + final Size scrollThumbSize; + + /// A function that builds a thumb using the current configuration + final ScrollThumbBuilder scrollThumbBuilder; + + /// The amount of padding that should surround the thumb + final EdgeInsets padding; + + /// Determines how quickly the scrollbar will animate in and out + final Duration scrollbarAnimationDuration; + + /// How long should the thumb be visible before fading out + final Duration scrollbarTimeToFade; + + /// Build a Text widget from the current offset in the BoxScrollView + final OffsetLabelBuilder labelTextBuilder; + + final TextLabelBuilder crumbTextBuilder; + + /// The ScrollController for the BoxScrollView + final ScrollController controller; + + final double Function(double scrollOffset, double offsetIncrement)? dragOffsetSnapper; + + /// The view that will be scrolled with the scroll thumb + final Widget child; + + const DraggableScrollbar({ + super.key, + required this.backgroundColor, + required this.scrollThumbSize, + required this.scrollThumbBuilder, + required this.controller, + this.dragOffsetSnapper, + this.crumbsBuilder, + this.padding = EdgeInsets.zero, + this.scrollbarAnimationDuration = const Duration(milliseconds: 300), + this.scrollbarTimeToFade = const Duration(milliseconds: 1000), + required this.labelTextBuilder, + required this.crumbTextBuilder, + required this.child, + }); + + @override + State<DraggableScrollbar> createState() => _DraggableScrollbarState(); + + static const double labelThumbPadding = 16; + + static Widget buildScrollThumbAndLabel({ + required Widget scrollThumb, + required Color backgroundColor, + required Animation<double> thumbAnimation, + required Animation<double> labelAnimation, + required Widget? labelText, + }) { + final scrollThumbAndLabel = labelText == null + ? scrollThumb + : Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + ScrollLabel( + animation: labelAnimation, + backgroundColor: backgroundColor, + child: labelText, + ), + const SizedBox(width: labelThumbPadding), + scrollThumb, + ], + ); + return SlideFadeTransition( + animation: thumbAnimation, + child: scrollThumbAndLabel, + ); + } +} + +class _DraggableScrollbarState extends State<DraggableScrollbar> with TickerProviderStateMixin { + final ValueNotifier<double> _thumbOffsetNotifier = ValueNotifier(0), _viewOffsetNotifier = ValueNotifier(0); + bool _isDragInProcess = false; + double _boundlessThumbOffset = 0, _offsetIncrement = 0; + late Offset _longPressLastGlobalPosition; + + late AnimationController _thumbAnimationController; + late CurvedAnimation _thumbAnimation; + late AnimationController _labelAnimationController; + late CurvedAnimation _labelAnimation; + Timer? _fadeoutTimer; + Map<double, String>? _percentCrumbs; + final Map<double, String> _viewportCrumbs = {}; + + static const double crumbPadding = 30; + static const double crumbMinViewportRatio = 4; + + @override + void initState() { + super.initState(); + + _thumbAnimationController = AnimationController( + vsync: this, + duration: widget.scrollbarAnimationDuration, + ); + + _thumbAnimation = CurvedAnimation( + parent: _thumbAnimationController, + curve: Curves.fastOutSlowIn, + ); + + _labelAnimationController = AnimationController( + vsync: this, + duration: widget.scrollbarAnimationDuration, + ); + + _labelAnimation = CurvedAnimation( + parent: _labelAnimationController, + curve: Curves.fastOutSlowIn, + ); + } + + @override + void didUpdateWidget(covariant DraggableScrollbar oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.crumbsBuilder != widget.crumbsBuilder) { + _percentCrumbs = null; + } + } + + @override + void dispose() { + _thumbAnimation.dispose(); + _thumbAnimationController.dispose(); + _labelAnimation.dispose(); + _labelAnimationController.dispose(); + _fadeoutTimer?.cancel(); + super.dispose(); + } + + ScrollController get controller => widget.controller; + + double get scrollBarHeight => context.size!.height - widget.padding.vertical; + + double get thumbMaxScrollExtent => scrollBarHeight - widget.scrollThumbSize.height; + + double get thumbMinScrollExtent => 0.0; + + @override + Widget build(BuildContext context) { + return NotificationListener<ScrollNotification>( + onNotification: (notification) { + _onScrollNotification(notification); + return false; + }, + child: Stack( + children: [ + RepaintBoundary( + child: widget.child, + ), + if (_isDragInProcess) + ..._viewportCrumbs.entries.map((kv) { + final offset = kv.key; + final label = kv.value; + return Positioned.directional( + textDirection: Directionality.of(context), + top: offset, + end: DraggableScrollbar.labelThumbPadding + widget.scrollThumbSize.width, + child: Padding( + padding: widget.padding, + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: widget.scrollThumbSize.height), + child: Center( + child: ScrollLabel( + animation: kAlwaysCompleteAnimation, + backgroundColor: widget.backgroundColor, + child: widget.crumbTextBuilder(label), + ), + ), + ), + ), + ); + }), + // exclude semantics, otherwise this layer will block access to content layers below when using TalkBack + ExcludeSemantics( + child: RepaintBoundary( + child: AGestureDetector( + onLongPressStart: (details) { + _longPressLastGlobalPosition = details.globalPosition; + _onVerticalDragStart(); + }, + onLongPressMoveUpdate: (details) { + final dy = (details.globalPosition - _longPressLastGlobalPosition).dy; + _longPressLastGlobalPosition = details.globalPosition; + _onVerticalDragUpdate(dy); + }, + onLongPressEnd: (_) => _onVerticalDragEnd(), + onVerticalDragStart: (_) => _onVerticalDragStart(), + onVerticalDragUpdate: (details) => _onVerticalDragUpdate(details.delta.dy), + onVerticalDragEnd: (_) => _onVerticalDragEnd(), + longPressTimeout: settings.longPressTimeout, + child: ValueListenableBuilder<double>( + valueListenable: _thumbOffsetNotifier, + builder: (context, thumbOffset, child) => Container( + alignment: AlignmentDirectional.topEnd, + padding: EdgeInsets.only(top: thumbOffset) + widget.padding, + child: widget.scrollThumbBuilder( + widget.backgroundColor, + _thumbAnimation, + _labelAnimation, + widget.scrollThumbSize.height, + labelText: _isDragInProcess + ? ValueListenableBuilder<double>( + valueListenable: _viewOffsetNotifier, + builder: (context, viewOffset, child) => widget.labelTextBuilder(viewOffset + thumbOffset), + ) + : null, + ), + ), + ), + ), + ), + ), + ], + ), + ); + } + + void _onScrollNotification(ScrollNotification notification) { + final scrollMetrics = notification.metrics; + + // do not update the thumb if we cannot actually scroll + if (scrollMetrics.minScrollExtent >= scrollMetrics.maxScrollExtent) return; + + _viewOffsetNotifier.value = scrollMetrics.pixels; + + // we update the thumb position from the scrolled offset + // when the user is not dragging the thumb + if (!_isDragInProcess) { + if (notification is ScrollUpdateNotification) { + final scrollExtent = (scrollMetrics.pixels / scrollMetrics.maxScrollExtent * thumbMaxScrollExtent); + _thumbOffsetNotifier.value = thumbMaxScrollExtent > thumbMinScrollExtent ? scrollExtent.clamp(thumbMinScrollExtent, thumbMaxScrollExtent) : thumbMinScrollExtent; + } + + if (notification is ScrollUpdateNotification || notification is OverscrollNotification) { + _showThumb(); + _scheduleFadeout(); + } + } + } + + void _onVerticalDragStart() { + const DraggableScrollbarNotification(DraggableScrollbarEvent.dragStart).dispatch(context); + _boundlessThumbOffset = _thumbOffsetNotifier.value; + _offsetIncrement = 1 / thumbMaxScrollExtent * controller.position.maxScrollExtent; + _labelAnimationController.forward(); + _fadeoutTimer?.cancel(); + _showThumb(); + _updateViewportCrumbs(); + setState(() => _isDragInProcess = true); + } + + void _onVerticalDragUpdate(double deltaY) { + _showThumb(); + if (_isDragInProcess && thumbMinScrollExtent < thumbMaxScrollExtent) { + // thumb offset + _boundlessThumbOffset += deltaY; + _thumbOffsetNotifier.value = _boundlessThumbOffset.clamp(thumbMinScrollExtent, thumbMaxScrollExtent); + + // scroll offset + final min = controller.position.minScrollExtent; + final max = controller.position.maxScrollExtent; + final scrollOffset = _thumbOffsetNotifier.value / thumbMaxScrollExtent * max; + controller.jumpTo((widget.dragOffsetSnapper?.call(scrollOffset, _offsetIncrement) ?? scrollOffset).clamp(min, max)); + } + } + + void _onVerticalDragEnd() { + const DraggableScrollbarNotification(DraggableScrollbarEvent.dragEnd).dispatch(context); + _scheduleFadeout(); + setState(() => _isDragInProcess = false); + } + + void _showThumb() { + if (_thumbAnimationController.status != AnimationStatus.forward) { + _thumbAnimationController.forward(); + } + } + + void _scheduleFadeout() { + _fadeoutTimer?.cancel(); + _fadeoutTimer = Timer(widget.scrollbarTimeToFade, () { + _thumbAnimationController.reverse(); + _labelAnimationController.reverse(); + _fadeoutTimer = null; + }); + } + + void _updateViewportCrumbs() { + _viewportCrumbs.clear(); + final crumbsBuilder = widget.crumbsBuilder; + if (crumbsBuilder != null) { + final maxOffset = thumbMaxScrollExtent; + final position = controller.position; + if (position.maxScrollExtent / position.viewportDimension > crumbMinViewportRatio) { + double lastLabelOffset = -crumbPadding; + _percentCrumbs ??= crumbsBuilder(); + _percentCrumbs!.entries.forEach((kv) { + final percent = kv.key; + final label = kv.value; + final labelOffset = percent * maxOffset; + if (labelOffset >= lastLabelOffset + crumbPadding) { + lastLabelOffset = labelOffset; + _viewportCrumbs[labelOffset] = label; + } + }); + // hide lonesome crumb, whether it is because of a single section, + // or because multiple sections collapsed to a single crumb + if (_viewportCrumbs.length == 1) { + _viewportCrumbs.clear(); + } + } + } + } +} diff --git a/lib/widgets/common/basic/draggable_scrollbar/transition.dart b/lib/widgets/common/basic/draggable_scrollbar/transition.dart new file mode 100644 index 0000000..2eeb3a3 --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/transition.dart @@ -0,0 +1,31 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class SlideFadeTransition extends StatelessWidget { + final Animation<double> animation; + final Widget child; + + const SlideFadeTransition({ + super.key, + required this.animation, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: animation, + builder: (context, child) => animation.value == 0.0 ? Container() : child!, + child: SlideTransition( + position: Tween( + begin: Offset((context.isRtl ? -1 : 1) * .3, 0), + end: Offset.zero, + ).animate(animation), + child: FadeTransition( + opacity: animation, + child: child, + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/font_size_icon_theme.dart b/lib/widgets/common/basic/font_size_icon_theme.dart new file mode 100644 index 0000000..0ef46d6 --- /dev/null +++ b/lib/widgets/common/basic/font_size_icon_theme.dart @@ -0,0 +1,23 @@ +import 'package:flutter/widgets.dart'; + +// scale icons according to text scale +class FontSizeIconTheme extends StatelessWidget { + final Widget child; + + const FontSizeIconTheme({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + final iconTheme = IconTheme.of(context); + return IconTheme( + data: iconTheme.copyWith( + size: textScaler.scale(iconTheme.size!), + ), + child: child, + ); + } +} diff --git a/lib/widgets/common/basic/gestures/gesture_detector.dart b/lib/widgets/common/basic/gestures/gesture_detector.dart new file mode 100644 index 0000000..e7a6d08 --- /dev/null +++ b/lib/widgets/common/basic/gestures/gesture_detector.dart @@ -0,0 +1,992 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +// as of Flutter v3.27.1, `GestureDetector` does not allow setting long press delay +// adapted from Flutter `GestureDetector` in `/widgets/gesture_detector.dart` +class AGestureDetector extends StatelessWidget { + /// Creates a widget that detects gestures. + /// + /// Pan and scale callbacks cannot be used simultaneously because scale is a + /// superset of pan. Use the scale callbacks instead. + /// + /// Horizontal and vertical drag callbacks cannot be used simultaneously + /// because a combination of a horizontal and vertical drag is a pan. + /// Use the pan callbacks instead. + /// + /// {@youtube 560 315 https://www.youtube.com/watch?v=WhVXkCFPmK4} + /// + /// By default, gesture detectors contribute semantic information to the tree + /// that is used by assistive technology. + AGestureDetector({ + super.key, + this.child, + this.onTapDown, + this.onTapUp, + this.onTap, + this.onTapCancel, + this.onSecondaryTap, + this.onSecondaryTapDown, + this.onSecondaryTapUp, + this.onSecondaryTapCancel, + this.onTertiaryTapDown, + this.onTertiaryTapUp, + this.onTertiaryTapCancel, + this.onDoubleTapDown, + this.onDoubleTap, + this.onDoubleTapCancel, + this.onLongPressDown, + this.onLongPressCancel, + this.onLongPress, + this.onLongPressStart, + this.onLongPressMoveUpdate, + this.onLongPressUp, + this.onLongPressEnd, + this.onSecondaryLongPressDown, + this.onSecondaryLongPressCancel, + this.onSecondaryLongPress, + this.onSecondaryLongPressStart, + this.onSecondaryLongPressMoveUpdate, + this.onSecondaryLongPressUp, + this.onSecondaryLongPressEnd, + this.onTertiaryLongPressDown, + this.onTertiaryLongPressCancel, + this.onTertiaryLongPress, + this.onTertiaryLongPressStart, + this.onTertiaryLongPressMoveUpdate, + this.onTertiaryLongPressUp, + this.onTertiaryLongPressEnd, + this.onVerticalDragDown, + this.onVerticalDragStart, + this.onVerticalDragUpdate, + this.onVerticalDragEnd, + this.onVerticalDragCancel, + this.onHorizontalDragDown, + this.onHorizontalDragStart, + this.onHorizontalDragUpdate, + this.onHorizontalDragEnd, + this.onHorizontalDragCancel, + this.onForcePressStart, + this.onForcePressPeak, + this.onForcePressUpdate, + this.onForcePressEnd, + this.onPanDown, + this.onPanStart, + this.onPanUpdate, + this.onPanEnd, + this.onPanCancel, + this.onScaleStart, + this.onScaleUpdate, + this.onScaleEnd, + this.behavior, + this.excludeFromSemantics = false, + this.dragStartBehavior = DragStartBehavior.start, + this.trackpadScrollCausesScale = false, + this.trackpadScrollToScaleFactor = kDefaultTrackpadScrollToScaleFactor, + this.supportedDevices, + this.longPressTimeout = kLongPressTimeout, + }) : assert(() { + final bool haveVerticalDrag = onVerticalDragStart != null || onVerticalDragUpdate != null || onVerticalDragEnd != null; + final bool haveHorizontalDrag = onHorizontalDragStart != null || onHorizontalDragUpdate != null || onHorizontalDragEnd != null; + final bool havePan = onPanStart != null || onPanUpdate != null || onPanEnd != null; + final bool haveScale = onScaleStart != null || onScaleUpdate != null || onScaleEnd != null; + if (havePan || haveScale) { + if (havePan && haveScale) { + throw FlutterError.fromParts(<DiagnosticsNode>[ + ErrorSummary('Incorrect GestureDetector arguments.'), + ErrorDescription( + 'Having both a pan gesture recognizer and a scale gesture recognizer is redundant; scale is a superset of pan.', + ), + ErrorHint('Just use the scale gesture recognizer.'), + ]); + } + final String recognizer = havePan ? 'pan' : 'scale'; + if (haveVerticalDrag && haveHorizontalDrag) { + throw FlutterError( + 'Incorrect GestureDetector arguments.\n' + 'Simultaneously having a vertical drag gesture recognizer, a horizontal drag gesture recognizer, and a $recognizer gesture recognizer ' + 'will result in the $recognizer gesture recognizer being ignored, since the other two will catch all drags.', + ); + } + } + return true; + }()); + + /// The widget below this widget in the tree. + /// + /// {@macro flutter.widgets.ProxyWidget.child} + final Widget? child; + + /// A pointer that might cause a tap with a primary button has contacted the + /// screen at a particular location. + /// + /// This is called after a short timeout, even if the winning gesture has not + /// yet been selected. If the tap gesture wins, [onTapUp] will be called, + /// otherwise [onTapCancel] will be called. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapDownCallback? onTapDown; + + /// A pointer that will trigger a tap with a primary button has stopped + /// contacting the screen at a particular location. + /// + /// This triggers immediately before [onTap] in the case of the tap gesture + /// winning. If the tap gesture did not win, [onTapCancel] is called instead. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapUpCallback? onTapUp; + + /// A tap with a primary button has occurred. + /// + /// This triggers when the tap gesture wins. If the tap gesture did not win, + /// [onTapCancel] is called instead. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [onTapUp], which is called at the same time but includes details + /// regarding the pointer position. + final GestureTapCallback? onTap; + + /// The pointer that previously triggered [onTapDown] will not end up causing + /// a tap. + /// + /// This is called after [onTapDown], and instead of [onTapUp] and [onTap], if + /// the tap gesture did not win. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapCancelCallback? onTapCancel; + + /// A tap with a secondary button has occurred. + /// + /// This triggers when the tap gesture wins. If the tap gesture did not win, + /// [onSecondaryTapCancel] is called instead. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [onSecondaryTapUp], which is called at the same time but includes details + /// regarding the pointer position. + final GestureTapCallback? onSecondaryTap; + + /// A pointer that might cause a tap with a secondary button has contacted the + /// screen at a particular location. + /// + /// This is called after a short timeout, even if the winning gesture has not + /// yet been selected. If the tap gesture wins, [onSecondaryTapUp] will be + /// called, otherwise [onSecondaryTapCancel] will be called. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + final GestureTapDownCallback? onSecondaryTapDown; + + /// A pointer that will trigger a tap with a secondary button has stopped + /// contacting the screen at a particular location. + /// + /// This triggers in the case of the tap gesture winning. If the tap gesture + /// did not win, [onSecondaryTapCancel] is called instead. + /// + /// See also: + /// + /// * [onSecondaryTap], a handler triggered right after this one that doesn't + /// pass any details about the tap. + /// * [kSecondaryButton], the button this callback responds to. + final GestureTapUpCallback? onSecondaryTapUp; + + /// The pointer that previously triggered [onSecondaryTapDown] will not end up + /// causing a tap. + /// + /// This is called after [onSecondaryTapDown], and instead of + /// [onSecondaryTapUp], if the tap gesture did not win. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + final GestureTapCancelCallback? onSecondaryTapCancel; + + /// A pointer that might cause a tap with a tertiary button has contacted the + /// screen at a particular location. + /// + /// This is called after a short timeout, even if the winning gesture has not + /// yet been selected. If the tap gesture wins, [onTertiaryTapUp] will be + /// called, otherwise [onTertiaryTapCancel] will be called. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + final GestureTapDownCallback? onTertiaryTapDown; + + /// A pointer that will trigger a tap with a tertiary button has stopped + /// contacting the screen at a particular location. + /// + /// This triggers in the case of the tap gesture winning. If the tap gesture + /// did not win, [onTertiaryTapCancel] is called instead. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + final GestureTapUpCallback? onTertiaryTapUp; + + /// The pointer that previously triggered [onTertiaryTapDown] will not end up + /// causing a tap. + /// + /// This is called after [onTertiaryTapDown], and instead of + /// [onTertiaryTapUp], if the tap gesture did not win. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + final GestureTapCancelCallback? onTertiaryTapCancel; + + /// A pointer that might cause a double tap has contacted the screen at a + /// particular location. + /// + /// Triggered immediately after the down event of the second tap. + /// + /// If the user completes the double tap and the gesture wins, [onDoubleTap] + /// will be called after this callback. Otherwise, [onDoubleTapCancel] will + /// be called after this callback. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapDownCallback? onDoubleTapDown; + + /// The user has tapped the screen with a primary button at the same location + /// twice in quick succession. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapCallback? onDoubleTap; + + /// The pointer that previously triggered [onDoubleTapDown] will not end up + /// causing a double tap. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapCancelCallback? onDoubleTapCancel; + + /// The pointer has contacted the screen with a primary button, which might + /// be the start of a long-press. + /// + /// This triggers after the pointer down event. + /// + /// If the user completes the long-press, and this gesture wins, + /// [onLongPressStart] will be called after this callback. Otherwise, + /// [onLongPressCancel] will be called after this callback. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [onSecondaryLongPressDown], a similar callback but for a secondary button. + /// * [onTertiaryLongPressDown], a similar callback but for a tertiary button. + /// * [LongPressGestureRecognizer.onLongPressDown], which exposes this + /// callback at the gesture layer. + final GestureLongPressDownCallback? onLongPressDown; + + /// A pointer that previously triggered [onLongPressDown] will not end up + /// causing a long-press. + /// + /// This triggers once the gesture loses if [onLongPressDown] has previously + /// been triggered. + /// + /// If the user completed the long-press, and the gesture won, then + /// [onLongPressStart] and [onLongPress] are called instead. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressCancel], which exposes this + /// callback at the gesture layer. + final GestureLongPressCancelCallback? onLongPressCancel; + + /// Called when a long press gesture with a primary button has been recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately after) [onLongPressStart]. + /// The only difference between the two is that this callback does not + /// contain details of the position at which the pointer initially contacted + /// the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPress], which exposes this + /// callback at the gesture layer. + final GestureLongPressCallback? onLongPress; + + /// Called when a long press gesture with a primary button has been recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately before) [onLongPress]. + /// The only difference between the two is that this callback contains + /// details of the position at which the pointer initially contacted the + /// screen, whereas [onLongPress] does not. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressStart], which exposes this + /// callback at the gesture layer. + final GestureLongPressStartCallback? onLongPressStart; + + /// A pointer has been drag-moved after a long-press with a primary button. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressMoveUpdate], which exposes this + /// callback at the gesture layer. + final GestureLongPressMoveUpdateCallback? onLongPressMoveUpdate; + + /// A pointer that has triggered a long-press with a primary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately after) [onLongPressEnd]. + /// The only difference between the two is that this callback does not + /// contain details of the state of the pointer when it stopped contacting + /// the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressUp], which exposes this + /// callback at the gesture layer. + final GestureLongPressUpCallback? onLongPressUp; + + /// A pointer that has triggered a long-press with a primary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately before) [onLongPressUp]. + /// The only difference between the two is that this callback contains + /// details of the state of the pointer when it stopped contacting the + /// screen, whereas [onLongPressUp] does not. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressEnd], which exposes this + /// callback at the gesture layer. + final GestureLongPressEndCallback? onLongPressEnd; + + /// The pointer has contacted the screen with a secondary button, which might + /// be the start of a long-press. + /// + /// This triggers after the pointer down event. + /// + /// If the user completes the long-press, and this gesture wins, + /// [onSecondaryLongPressStart] will be called after this callback. Otherwise, + /// [onSecondaryLongPressCancel] will be called after this callback. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [onLongPressDown], a similar callback but for a secondary button. + /// * [onTertiaryLongPressDown], a similar callback but for a tertiary button. + /// * [LongPressGestureRecognizer.onSecondaryLongPressDown], which exposes + /// this callback at the gesture layer. + final GestureLongPressDownCallback? onSecondaryLongPressDown; + + /// A pointer that previously triggered [onSecondaryLongPressDown] will not + /// end up causing a long-press. + /// + /// This triggers once the gesture loses if [onSecondaryLongPressDown] has + /// previously been triggered. + /// + /// If the user completed the long-press, and the gesture won, then + /// [onSecondaryLongPressStart] and [onSecondaryLongPress] are called instead. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressCancel], which exposes + /// this callback at the gesture layer. + final GestureLongPressCancelCallback? onSecondaryLongPressCancel; + + /// Called when a long press gesture with a secondary button has been + /// recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately after) + /// [onSecondaryLongPressStart]. The only difference between the two is that + /// this callback does not contain details of the position at which the + /// pointer initially contacted the screen. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPress], which exposes + /// this callback at the gesture layer. + final GestureLongPressCallback? onSecondaryLongPress; + + /// Called when a long press gesture with a secondary button has been + /// recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately before) + /// [onSecondaryLongPress]. The only difference between the two is that this + /// callback contains details of the position at which the pointer initially + /// contacted the screen, whereas [onSecondaryLongPress] does not. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressStart], which exposes + /// this callback at the gesture layer. + final GestureLongPressStartCallback? onSecondaryLongPressStart; + + /// A pointer has been drag-moved after a long press with a secondary button. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressMoveUpdate], which exposes + /// this callback at the gesture layer. + final GestureLongPressMoveUpdateCallback? onSecondaryLongPressMoveUpdate; + + /// A pointer that has triggered a long-press with a secondary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately after) + /// [onSecondaryLongPressEnd]. The only difference between the two is that + /// this callback does not contain details of the state of the pointer when + /// it stopped contacting the screen. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressUp], which exposes + /// this callback at the gesture layer. + final GestureLongPressUpCallback? onSecondaryLongPressUp; + + /// A pointer that has triggered a long-press with a secondary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately before) + /// [onSecondaryLongPressUp]. The only difference between the two is that + /// this callback contains details of the state of the pointer when it + /// stopped contacting the screen, whereas [onSecondaryLongPressUp] does not. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressEnd], which exposes + /// this callback at the gesture layer. + final GestureLongPressEndCallback? onSecondaryLongPressEnd; + + /// The pointer has contacted the screen with a tertiary button, which might + /// be the start of a long-press. + /// + /// This triggers after the pointer down event. + /// + /// If the user completes the long-press, and this gesture wins, + /// [onTertiaryLongPressStart] will be called after this callback. Otherwise, + /// [onTertiaryLongPressCancel] will be called after this callback. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [onLongPressDown], a similar callback but for a primary button. + /// * [onSecondaryLongPressDown], a similar callback but for a secondary button. + /// * [LongPressGestureRecognizer.onTertiaryLongPressDown], which exposes + /// this callback at the gesture layer. + final GestureLongPressDownCallback? onTertiaryLongPressDown; + + /// A pointer that previously triggered [onTertiaryLongPressDown] will not + /// end up causing a long-press. + /// + /// This triggers once the gesture loses if [onTertiaryLongPressDown] has + /// previously been triggered. + /// + /// If the user completed the long-press, and the gesture won, then + /// [onTertiaryLongPressStart] and [onTertiaryLongPress] are called instead. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressCancel], which exposes + /// this callback at the gesture layer. + final GestureLongPressCancelCallback? onTertiaryLongPressCancel; + + /// Called when a long press gesture with a tertiary button has been + /// recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately after) + /// [onTertiaryLongPressStart]. The only difference between the two is that + /// this callback does not contain details of the position at which the + /// pointer initially contacted the screen. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPress], which exposes + /// this callback at the gesture layer. + final GestureLongPressCallback? onTertiaryLongPress; + + /// Called when a long press gesture with a tertiary button has been + /// recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately before) + /// [onTertiaryLongPress]. The only difference between the two is that this + /// callback contains details of the position at which the pointer initially + /// contacted the screen, whereas [onTertiaryLongPress] does not. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressStart], which exposes + /// this callback at the gesture layer. + final GestureLongPressStartCallback? onTertiaryLongPressStart; + + /// A pointer has been drag-moved after a long press with a tertiary button. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressMoveUpdate], which exposes + /// this callback at the gesture layer. + final GestureLongPressMoveUpdateCallback? onTertiaryLongPressMoveUpdate; + + /// A pointer that has triggered a long-press with a tertiary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately after) + /// [onTertiaryLongPressEnd]. The only difference between the two is that + /// this callback does not contain details of the state of the pointer when + /// it stopped contacting the screen. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressUp], which exposes + /// this callback at the gesture layer. + final GestureLongPressUpCallback? onTertiaryLongPressUp; + + /// A pointer that has triggered a long-press with a tertiary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately before) + /// [onTertiaryLongPressUp]. The only difference between the two is that + /// this callback contains details of the state of the pointer when it + /// stopped contacting the screen, whereas [onTertiaryLongPressUp] does not. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressEnd], which exposes + /// this callback at the gesture layer. + final GestureLongPressEndCallback? onTertiaryLongPressEnd; + + /// A pointer has contacted the screen with a primary button and might begin + /// to move vertically. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragDownCallback? onVerticalDragDown; + + /// A pointer has contacted the screen with a primary button and has begun to + /// move vertically. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragStartCallback? onVerticalDragStart; + + /// A pointer that is in contact with the screen with a primary button and + /// moving vertically has moved in the vertical direction. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragUpdateCallback? onVerticalDragUpdate; + + /// A pointer that was previously in contact with the screen with a primary + /// button and moving vertically is no longer in contact with the screen and + /// was moving at a specific velocity when it stopped contacting the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragEndCallback? onVerticalDragEnd; + + /// The pointer that previously triggered [onVerticalDragDown] did not + /// complete. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragCancelCallback? onVerticalDragCancel; + + /// A pointer has contacted the screen with a primary button and might begin + /// to move horizontally. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragDownCallback? onHorizontalDragDown; + + /// A pointer has contacted the screen with a primary button and has begun to + /// move horizontally. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragStartCallback? onHorizontalDragStart; + + /// A pointer that is in contact with the screen with a primary button and + /// moving horizontally has moved in the horizontal direction. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragUpdateCallback? onHorizontalDragUpdate; + + /// A pointer that was previously in contact with the screen with a primary + /// button and moving horizontally is no longer in contact with the screen and + /// was moving at a specific velocity when it stopped contacting the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragEndCallback? onHorizontalDragEnd; + + /// The pointer that previously triggered [onHorizontalDragDown] did not + /// complete. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragCancelCallback? onHorizontalDragCancel; + + /// A pointer has contacted the screen with a primary button and might begin + /// to move. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragDownCallback? onPanDown; + + /// A pointer has contacted the screen with a primary button and has begun to + /// move. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragStartCallback? onPanStart; + + /// A pointer that is in contact with the screen with a primary button and + /// moving has moved again. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragUpdateCallback? onPanUpdate; + + /// A pointer that was previously in contact with the screen with a primary + /// button and moving is no longer in contact with the screen and was moving + /// at a specific velocity when it stopped contacting the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragEndCallback? onPanEnd; + + /// The pointer that previously triggered [onPanDown] did not complete. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragCancelCallback? onPanCancel; + + /// The pointers in contact with the screen have established a focal point and + /// initial scale of 1.0. + final GestureScaleStartCallback? onScaleStart; + + /// The pointers in contact with the screen have indicated a new focal point + /// and/or scale. + final GestureScaleUpdateCallback? onScaleUpdate; + + /// The pointers are no longer in contact with the screen. + final GestureScaleEndCallback? onScaleEnd; + + /// The pointer is in contact with the screen and has pressed with sufficient + /// force to initiate a force press. The amount of force is at least + /// [ForcePressGestureRecognizer.startPressure]. + /// + /// This callback will only be fired on devices with pressure + /// detecting screens. + final GestureForcePressStartCallback? onForcePressStart; + + /// The pointer is in contact with the screen and has pressed with the maximum + /// force. The amount of force is at least + /// [ForcePressGestureRecognizer.peakPressure]. + /// + /// This callback will only be fired on devices with pressure + /// detecting screens. + final GestureForcePressPeakCallback? onForcePressPeak; + + /// A pointer is in contact with the screen, has previously passed the + /// [ForcePressGestureRecognizer.startPressure] and is either moving on the + /// plane of the screen, pressing the screen with varying forces or both + /// simultaneously. + /// + /// This callback will only be fired on devices with pressure + /// detecting screens. + final GestureForcePressUpdateCallback? onForcePressUpdate; + + /// The pointer tracked by [onForcePressStart] is no longer in contact with the screen. + /// + /// This callback will only be fired on devices with pressure + /// detecting screens. + final GestureForcePressEndCallback? onForcePressEnd; + + /// How this gesture detector should behave during hit testing when deciding + /// how the hit test propagates to children and whether to consider targets + /// behind this one. + /// + /// This defaults to [HitTestBehavior.deferToChild] if [child] is not null and + /// [HitTestBehavior.translucent] if child is null. + /// + /// See [HitTestBehavior] for the allowed values and their meanings. + final HitTestBehavior? behavior; + + /// Whether to exclude these gestures from the semantics tree. For + /// example, the long-press gesture for showing a tooltip is + /// excluded because the tooltip itself is included in the semantics + /// tree directly and so having a gesture to show it would result in + /// duplication of information. + final bool excludeFromSemantics; + + /// Determines the way that drag start behavior is handled. + /// + /// If set to [DragStartBehavior.start], gesture drag behavior will + /// begin at the position where the drag gesture won the arena. If set to + /// [DragStartBehavior.down] it will begin at the position where a down event + /// is first detected. + /// + /// In general, setting this to [DragStartBehavior.start] will make drag + /// animation smoother and setting it to [DragStartBehavior.down] will make + /// drag behavior feel slightly more reactive. + /// + /// By default, the drag start behavior is [DragStartBehavior.start]. + /// + /// Only the [DragGestureRecognizer.onStart] callbacks for the + /// [VerticalDragGestureRecognizer], [HorizontalDragGestureRecognizer] and + /// [PanGestureRecognizer] are affected by this setting. + /// + /// See also: + /// + /// * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors. + final DragStartBehavior dragStartBehavior; + + /// The kind of devices that are allowed to be recognized. + /// + /// If set to null, events from all device types will be recognized. Defaults to null. + final Set<PointerDeviceKind>? supportedDevices; + + /// {@macro flutter.gestures.scale.trackpadScrollCausesScale} + final bool trackpadScrollCausesScale; + + /// {@macro flutter.gestures.scale.trackpadScrollToScaleFactor} + final Offset trackpadScrollToScaleFactor; + + final Duration longPressTimeout; + + @override + Widget build(BuildContext context) { + final Map<Type, GestureRecognizerFactory> gestures = <Type, GestureRecognizerFactory>{}; + final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context); + final ScrollBehavior configuration = ScrollConfiguration.of(context); + + if (onTapDown != null || onTapUp != null || onTap != null || onTapCancel != null || onSecondaryTap != null || onSecondaryTapDown != null || onSecondaryTapUp != null || onSecondaryTapCancel != null || onTertiaryTapDown != null || onTertiaryTapUp != null || onTertiaryTapCancel != null) { + gestures[TapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( + () => TapGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onTapDown = onTapDown + ..onTapUp = onTapUp + ..onTap = onTap + ..onTapCancel = onTapCancel + ..onSecondaryTap = onSecondaryTap + ..onSecondaryTapDown = onSecondaryTapDown + ..onSecondaryTapUp = onSecondaryTapUp + ..onSecondaryTapCancel = onSecondaryTapCancel + ..onTertiaryTapDown = onTertiaryTapDown + ..onTertiaryTapUp = onTertiaryTapUp + ..onTertiaryTapCancel = onTertiaryTapCancel + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onDoubleTap != null || onDoubleTapDown != null || onDoubleTapCancel != null) { + gestures[DoubleTapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<DoubleTapGestureRecognizer>( + () => DoubleTapGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onDoubleTapDown = onDoubleTapDown + ..onDoubleTap = onDoubleTap + ..onDoubleTapCancel = onDoubleTapCancel + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onLongPressDown != null || onLongPressCancel != null || onLongPress != null || onLongPressStart != null || onLongPressMoveUpdate != null || onLongPressUp != null || onLongPressEnd != null || onSecondaryLongPressDown != null || onSecondaryLongPressCancel != null || onSecondaryLongPress != null || onSecondaryLongPressStart != null || onSecondaryLongPressMoveUpdate != null || onSecondaryLongPressUp != null || onSecondaryLongPressEnd != null || onTertiaryLongPressDown != null || onTertiaryLongPressCancel != null || onTertiaryLongPress != null || onTertiaryLongPressStart != null || onTertiaryLongPressMoveUpdate != null || onTertiaryLongPressUp != null || onTertiaryLongPressEnd != null) { + gestures[LongPressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( + () => LongPressGestureRecognizer(duration: longPressTimeout, debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onLongPressDown = onLongPressDown + ..onLongPressCancel = onLongPressCancel + ..onLongPress = onLongPress + ..onLongPressStart = onLongPressStart + ..onLongPressMoveUpdate = onLongPressMoveUpdate + ..onLongPressUp = onLongPressUp + ..onLongPressEnd = onLongPressEnd + ..onSecondaryLongPressDown = onSecondaryLongPressDown + ..onSecondaryLongPressCancel = onSecondaryLongPressCancel + ..onSecondaryLongPress = onSecondaryLongPress + ..onSecondaryLongPressStart = onSecondaryLongPressStart + ..onSecondaryLongPressMoveUpdate = onSecondaryLongPressMoveUpdate + ..onSecondaryLongPressUp = onSecondaryLongPressUp + ..onSecondaryLongPressEnd = onSecondaryLongPressEnd + ..onTertiaryLongPressDown = onTertiaryLongPressDown + ..onTertiaryLongPressCancel = onTertiaryLongPressCancel + ..onTertiaryLongPress = onTertiaryLongPress + ..onTertiaryLongPressStart = onTertiaryLongPressStart + ..onTertiaryLongPressMoveUpdate = onTertiaryLongPressMoveUpdate + ..onTertiaryLongPressUp = onTertiaryLongPressUp + ..onTertiaryLongPressEnd = onTertiaryLongPressEnd + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onVerticalDragDown != null || onVerticalDragStart != null || onVerticalDragUpdate != null || onVerticalDragEnd != null || onVerticalDragCancel != null) { + gestures[VerticalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<VerticalDragGestureRecognizer>( + () => VerticalDragGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onDown = onVerticalDragDown + ..onStart = onVerticalDragStart + ..onUpdate = onVerticalDragUpdate + ..onEnd = onVerticalDragEnd + ..onCancel = onVerticalDragCancel + ..dragStartBehavior = dragStartBehavior + ..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context) + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onHorizontalDragDown != null || onHorizontalDragStart != null || onHorizontalDragUpdate != null || onHorizontalDragEnd != null || onHorizontalDragCancel != null) { + gestures[HorizontalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>( + () => HorizontalDragGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onDown = onHorizontalDragDown + ..onStart = onHorizontalDragStart + ..onUpdate = onHorizontalDragUpdate + ..onEnd = onHorizontalDragEnd + ..onCancel = onHorizontalDragCancel + ..dragStartBehavior = dragStartBehavior + ..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context) + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onPanDown != null || onPanStart != null || onPanUpdate != null || onPanEnd != null || onPanCancel != null) { + gestures[PanGestureRecognizer] = GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>( + () => PanGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onDown = onPanDown + ..onStart = onPanStart + ..onUpdate = onPanUpdate + ..onEnd = onPanEnd + ..onCancel = onPanCancel + ..dragStartBehavior = dragStartBehavior + ..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context) + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onScaleStart != null || onScaleUpdate != null || onScaleEnd != null) { + gestures[ScaleGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ScaleGestureRecognizer>( + () => ScaleGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onStart = onScaleStart + ..onUpdate = onScaleUpdate + ..onEnd = onScaleEnd + ..dragStartBehavior = dragStartBehavior + ..gestureSettings = gestureSettings + ..trackpadScrollCausesScale = trackpadScrollCausesScale + ..trackpadScrollToScaleFactor = trackpadScrollToScaleFactor + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onForcePressStart != null || onForcePressPeak != null || onForcePressUpdate != null || onForcePressEnd != null) { + gestures[ForcePressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ForcePressGestureRecognizer>( + () => ForcePressGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onStart = onForcePressStart + ..onPeak = onForcePressPeak + ..onUpdate = onForcePressUpdate + ..onEnd = onForcePressEnd + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + return RawGestureDetector( + gestures: gestures, + behavior: behavior, + excludeFromSemantics: excludeFromSemantics, + child: child, + ); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(EnumProperty<DragStartBehavior>('startBehavior', dragStartBehavior)); + } +} diff --git a/lib/widgets/common/basic/gestures/ink_well.dart b/lib/widgets/common/basic/gestures/ink_well.dart new file mode 100644 index 0000000..1c3c854 --- /dev/null +++ b/lib/widgets/common/basic/gestures/ink_well.dart @@ -0,0 +1,1089 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +// as of Flutter v3.27.1, `InkResponse` does not allow setting long press delay +// adapted from Flutter `InkResponse` and related classes in `/material/ink_well.dart` +class AInkResponse extends StatelessWidget { + /// Creates an area of a [Material] that responds to touch. + /// + /// Must have an ancestor [Material] widget in which to cause ink reactions. + const AInkResponse({ + super.key, + this.child, + this.onTap, + this.onTapDown, + this.onTapUp, + this.onTapCancel, + this.onDoubleTap, + this.onLongPress, + this.onSecondaryTap, + this.onSecondaryTapUp, + this.onSecondaryTapDown, + this.onSecondaryTapCancel, + this.onHighlightChanged, + this.onHover, + this.mouseCursor, + this.containedInkWell = false, + this.highlightShape = BoxShape.circle, + this.radius, + this.borderRadius, + this.customBorder, + this.focusColor, + this.hoverColor, + this.highlightColor, + this.overlayColor, + this.splashColor, + this.splashFactory, + this.enableFeedback = true, + this.excludeFromSemantics = false, + this.focusNode, + this.canRequestFocus = true, + this.onFocusChange, + this.autofocus = false, + this.statesController, + this.hoverDuration, + this.longPressTimeout = kLongPressTimeout, + }); + + /// The widget below this widget in the tree. + /// + /// {@macro flutter.widgets.ProxyWidget.child} + final Widget? child; + + /// Called when the user taps this part of the material. + final GestureTapCallback? onTap; + + /// Called when the user taps down this part of the material. + final GestureTapDownCallback? onTapDown; + + /// Called when the user releases a tap that was started on this part of the + /// material. [onTap] is called immediately after. + final GestureTapUpCallback? onTapUp; + + /// Called when the user cancels a tap that was started on this part of the + /// material. + final GestureTapCallback? onTapCancel; + + /// Called when the user double taps this part of the material. + final GestureTapCallback? onDoubleTap; + + /// Called when the user long-presses on this part of the material. + final GestureLongPressCallback? onLongPress; + + /// Called when the user taps this part of the material with a secondary button. + final GestureTapCallback? onSecondaryTap; + + /// Called when the user taps down on this part of the material with a + /// secondary button. + final GestureTapDownCallback? onSecondaryTapDown; + + /// Called when the user releases a secondary button tap that was started on + /// this part of the material. [onSecondaryTap] is called immediately after. + final GestureTapUpCallback? onSecondaryTapUp; + + /// Called when the user cancels a secondary button tap that was started on + /// this part of the material. + final GestureTapCallback? onSecondaryTapCancel; + + /// Called when this part of the material either becomes highlighted or stops + /// being highlighted. + /// + /// The value passed to the callback is true if this part of the material has + /// become highlighted and false if this part of the material has stopped + /// being highlighted. + /// + /// If all of [onTap], [onDoubleTap], and [onLongPress] become null while a + /// gesture is ongoing, then [onTapCancel] will be fired and + /// [onHighlightChanged] will be fired with the value false _during the + /// build_. This means, for instance, that in that scenario [State.setState] + /// cannot be called. + final ValueChanged<bool>? onHighlightChanged; + + /// Called when a pointer enters or exits the ink response area. + /// + /// The value passed to the callback is true if a pointer has entered this + /// part of the material and false if a pointer has exited this part of the + /// material. + final ValueChanged<bool>? onHover; + + /// The cursor for a mouse pointer when it enters or is hovering over the + /// widget. + /// + /// If [mouseCursor] is a [WidgetStateProperty<MouseCursor>], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: + /// + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. + final MouseCursor? mouseCursor; + + /// Whether this ink response should be clipped its bounds. + /// + /// This flag also controls whether the splash migrates to the center of the + /// [InkResponse] or not. If [containedInkWell] is true, the splash remains + /// centered around the tap location. If it is false, the splash migrates to + /// the center of the [InkResponse] as it grows. + /// + /// See also: + /// + /// * [highlightShape], the shape of the focus, hover, and pressed + /// highlights. + /// * [borderRadius], which controls the corners when the box is a rectangle. + /// * [getRectCallback], which controls the size and position of the box when + /// it is a rectangle. + final bool containedInkWell; + + /// The shape (e.g., circle, rectangle) to use for the highlight drawn around + /// this part of the material when pressed, hovered over, or focused. + /// + /// The same shape is used for the pressed highlight (see [highlightColor]), + /// the focus highlight (see [focusColor]), and the hover highlight (see + /// [hoverColor]). + /// + /// If the shape is [BoxShape.circle], then the highlight is centered on the + /// [InkResponse]. If the shape is [BoxShape.rectangle], then the highlight + /// fills the [InkResponse], or the rectangle provided by [getRectCallback] if + /// the callback is specified. + /// + /// See also: + /// + /// * [containedInkWell], which controls clipping behavior. + /// * [borderRadius], which controls the corners when the box is a rectangle. + /// * [highlightColor], the color of the highlight. + /// * [getRectCallback], which controls the size and position of the box when + /// it is a rectangle. + final BoxShape highlightShape; + + /// The radius of the ink splash. + /// + /// Splashes grow up to this size. By default, this size is determined from + /// the size of the rectangle provided by [getRectCallback], or the size of + /// the [InkResponse] itself. + /// + /// See also: + /// + /// * [splashColor], the color of the splash. + /// * [splashFactory], which defines the appearance of the splash. + final double? radius; + + /// The border radius of the containing rectangle. This is effective only if + /// [highlightShape] is [BoxShape.rectangle]. + /// + /// If this is null, it is interpreted as [BorderRadius.zero]. + final BorderRadius? borderRadius; + + /// The custom clip border. + /// + /// If this is null, the ink response will not clip its content. + final ShapeBorder? customBorder; + + /// The color of the ink response when the parent widget is focused. If this + /// property is null then the focus color of the theme, + /// [ThemeData.focusColor], will be used. + /// + /// See also: + /// + /// * [highlightShape], the shape of the focus, hover, and pressed + /// highlights. + /// * [hoverColor], the color of the hover highlight. + /// * [splashColor], the color of the splash. + /// * [splashFactory], which defines the appearance of the splash. + final Color? focusColor; + + /// The color of the ink response when a pointer is hovering over it. If this + /// property is null then the hover color of the theme, + /// [ThemeData.hoverColor], will be used. + /// + /// See also: + /// + /// * [highlightShape], the shape of the focus, hover, and pressed + /// highlights. + /// * [highlightColor], the color of the pressed highlight. + /// * [focusColor], the color of the focus highlight. + /// * [splashColor], the color of the splash. + /// * [splashFactory], which defines the appearance of the splash. + final Color? hoverColor; + + /// The highlight color of the ink response when pressed. If this property is + /// null then the highlight color of the theme, [ThemeData.highlightColor], + /// will be used. + /// + /// See also: + /// + /// * [hoverColor], the color of the hover highlight. + /// * [focusColor], the color of the focus highlight. + /// * [highlightShape], the shape of the focus, hover, and pressed + /// highlights. + /// * [splashColor], the color of the splash. + /// * [splashFactory], which defines the appearance of the splash. + final Color? highlightColor; + + /// Defines the ink response focus, hover, and splash colors. + /// + /// This default null property can be used as an alternative to + /// [focusColor], [hoverColor], [highlightColor], and + /// [splashColor]. If non-null, it is resolved against one of + /// [WidgetState.focused], [WidgetState.hovered], and + /// [WidgetState.pressed]. It's convenient to use when the parent + /// widget can pass along its own WidgetStateProperty value for + /// the overlay color. + /// + /// [WidgetState.pressed] triggers a ripple (an ink splash), per + /// the current Material Design spec. The [overlayColor] doesn't map + /// a state to [highlightColor] because a separate highlight is not + /// used by the current design guidelines. See + /// https://material.io/design/interaction/states.html#pressed + /// + /// If the overlay color is null or resolves to null, then [focusColor], + /// [hoverColor], [splashColor] and their defaults are used instead. + /// + /// See also: + /// + /// * The Material Design specification for overlay colors and how they + /// match a component's state: + /// <https://material.io/design/interaction/states.html#anatomy>. + final WidgetStateProperty<Color?>? overlayColor; + + /// The splash color of the ink response. If this property is null then the + /// splash color of the theme, [ThemeData.splashColor], will be used. + /// + /// See also: + /// + /// * [splashFactory], which defines the appearance of the splash. + /// * [radius], the (maximum) size of the ink splash. + /// * [highlightColor], the color of the highlight. + final Color? splashColor; + + /// Defines the appearance of the splash. + /// + /// Defaults to the value of the theme's splash factory: [ThemeData.splashFactory]. + /// + /// See also: + /// + /// * [radius], the (maximum) size of the ink splash. + /// * [splashColor], the color of the splash. + /// * [highlightColor], the color of the highlight. + /// * [InkSplash.splashFactory], which defines the default splash. + /// * [InkRipple.splashFactory], which defines a splash that spreads out + /// more aggressively than the default. + final InteractiveInkFeatureFactory? splashFactory; + + /// Whether detected gestures should provide acoustic and/or haptic feedback. + /// + /// For example, on Android a tap will produce a clicking sound and a + /// long-press will produce a short vibration, when feedback is enabled. + /// + /// See also: + /// + /// * [Feedback] for providing platform-specific feedback to certain actions. + final bool enableFeedback; + + /// Whether to exclude the gestures introduced by this widget from the + /// semantics tree. + /// + /// For example, a long-press gesture for showing a tooltip is usually + /// excluded because the tooltip itself is included in the semantics + /// tree directly and so having a gesture to show it would result in + /// duplication of information. + final bool excludeFromSemantics; + + /// {@template flutter.material.inkwell.onFocusChange} + /// Handler called when the focus changes. + /// + /// Called with true if this widget's node gains focus, and false if it loses + /// focus. + /// {@endtemplate} + final ValueChanged<bool>? onFocusChange; + + /// {@macro flutter.widgets.Focus.autofocus} + final bool autofocus; + + /// {@macro flutter.widgets.Focus.focusNode} + final FocusNode? focusNode; + + /// {@macro flutter.widgets.Focus.canRequestFocus} + final bool canRequestFocus; + + /// The rectangle to use for the highlight effect and for clipping + /// the splash effects if [containedInkWell] is true. + /// + /// This method is intended to be overridden by descendants that + /// specialize [InkResponse] for unusual cases. For example, + /// [TableRowInkWell] implements this method to return the rectangle + /// corresponding to the row that the widget is in. + /// + /// The default behavior returns null, which is equivalent to + /// returning the referenceBox argument's bounding box (though + /// slightly more efficient). + RectCallback? getRectCallback(RenderBox referenceBox) => null; + + /// {@template flutter.material.inkwell.statesController} + /// Represents the interactive "state" of this widget in terms of + /// a set of [WidgetState]s, like [WidgetState.pressed] and + /// [WidgetState.focused]. + /// + /// Classes based on this one can provide their own + /// [WidgetStatesController] to which they've added listeners. + /// They can also update the controller's [WidgetStatesController.value] + /// however, this may only be done when it's safe to call + /// [State.setState], like in an event handler. + /// {@endtemplate} + final WidgetStatesController? statesController; + + /// The duration of the animation that animates the hover effect. + /// + /// The default is 50ms. + final Duration? hoverDuration; + + final Duration longPressTimeout; + + @override + Widget build(BuildContext context) { + final _ParentInkResponseState? parentState = _ParentInkResponseProvider.maybeOf(context); + return _InkResponseStateWidget( + onTap: onTap, + onTapDown: onTapDown, + onTapUp: onTapUp, + onTapCancel: onTapCancel, + onDoubleTap: onDoubleTap, + onLongPress: onLongPress, + onSecondaryTap: onSecondaryTap, + onSecondaryTapUp: onSecondaryTapUp, + onSecondaryTapDown: onSecondaryTapDown, + onSecondaryTapCancel: onSecondaryTapCancel, + onHighlightChanged: onHighlightChanged, + onHover: onHover, + mouseCursor: mouseCursor, + containedInkWell: containedInkWell, + highlightShape: highlightShape, + radius: radius, + borderRadius: borderRadius, + customBorder: customBorder, + focusColor: focusColor, + hoverColor: hoverColor, + highlightColor: highlightColor, + overlayColor: overlayColor, + splashColor: splashColor, + splashFactory: splashFactory, + enableFeedback: enableFeedback, + excludeFromSemantics: excludeFromSemantics, + focusNode: focusNode, + canRequestFocus: canRequestFocus, + onFocusChange: onFocusChange, + autofocus: autofocus, + parentState: parentState, + getRectCallback: getRectCallback, + debugCheckContext: debugCheckContext, + statesController: statesController, + hoverDuration: hoverDuration, + longPressTimeout: longPressTimeout, + child: child, + ); + } + + /// Asserts that the given context satisfies the prerequisites for + /// this class. + /// + /// This method is intended to be overridden by descendants that + /// specialize [InkResponse] for unusual cases. For example, + /// [TableRowInkWell] implements this method to verify that the widget is + /// in a table. + @mustCallSuper + bool debugCheckContext(BuildContext context) { + assert(debugCheckHasMaterial(context)); + assert(debugCheckHasDirectionality(context)); + return true; + } +} + +abstract class _ParentInkResponseState { + void markChildInkResponsePressed(_ParentInkResponseState childState, bool value); +} + +class _ParentInkResponseProvider extends InheritedWidget { + const _ParentInkResponseProvider({ + required this.state, + required super.child, + }); + + final _ParentInkResponseState state; + + @override + bool updateShouldNotify(_ParentInkResponseProvider oldWidget) => state != oldWidget.state; + + static _ParentInkResponseState? maybeOf(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType<_ParentInkResponseProvider>()?.state; + } +} + +typedef _GetRectCallback = RectCallback? Function(RenderBox referenceBox); +typedef _CheckContext = bool Function(BuildContext context); + +class _InkResponseStateWidget extends StatefulWidget { + const _InkResponseStateWidget({ + this.child, + this.onTap, + this.onTapDown, + this.onTapUp, + this.onTapCancel, + this.onDoubleTap, + this.onLongPress, + this.onSecondaryTap, + this.onSecondaryTapUp, + this.onSecondaryTapDown, + this.onSecondaryTapCancel, + this.onHighlightChanged, + this.onHover, + this.mouseCursor, + this.containedInkWell = false, + this.highlightShape = BoxShape.circle, + this.radius, + this.borderRadius, + this.customBorder, + this.focusColor, + this.hoverColor, + this.highlightColor, + this.overlayColor, + this.splashColor, + this.splashFactory, + this.enableFeedback = true, + this.excludeFromSemantics = false, + this.focusNode, + this.canRequestFocus = true, + this.onFocusChange, + this.autofocus = false, + this.parentState, + this.getRectCallback, + required this.debugCheckContext, + this.statesController, + this.hoverDuration, + required this.longPressTimeout, + }); + + final Widget? child; + final GestureTapCallback? onTap; + final GestureTapDownCallback? onTapDown; + final GestureTapUpCallback? onTapUp; + final GestureTapCallback? onTapCancel; + final GestureTapCallback? onDoubleTap; + final GestureLongPressCallback? onLongPress; + final GestureTapCallback? onSecondaryTap; + final GestureTapUpCallback? onSecondaryTapUp; + final GestureTapDownCallback? onSecondaryTapDown; + final GestureTapCallback? onSecondaryTapCancel; + final ValueChanged<bool>? onHighlightChanged; + final ValueChanged<bool>? onHover; + final MouseCursor? mouseCursor; + final bool containedInkWell; + final BoxShape highlightShape; + final double? radius; + final BorderRadius? borderRadius; + final ShapeBorder? customBorder; + final Color? focusColor; + final Color? hoverColor; + final Color? highlightColor; + final WidgetStateProperty<Color?>? overlayColor; + final Color? splashColor; + final InteractiveInkFeatureFactory? splashFactory; + final bool enableFeedback; + final bool excludeFromSemantics; + final ValueChanged<bool>? onFocusChange; + final bool autofocus; + final FocusNode? focusNode; + final bool canRequestFocus; + final _ParentInkResponseState? parentState; + final _GetRectCallback? getRectCallback; + final _CheckContext debugCheckContext; + final WidgetStatesController? statesController; + final Duration? hoverDuration; + final Duration longPressTimeout; + + @override + _InkResponseState createState() => _InkResponseState(); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + final List<String> gestures = <String>[ + if (onTap != null) 'tap', + if (onDoubleTap != null) 'double tap', + if (onLongPress != null) 'long press', + if (onTapDown != null) 'tap down', + if (onTapUp != null) 'tap up', + if (onTapCancel != null) 'tap cancel', + if (onSecondaryTap != null) 'secondary tap', + if (onSecondaryTapUp != null) 'secondary tap up', + if (onSecondaryTapDown != null) 'secondary tap down', + if (onSecondaryTapCancel != null) 'secondary tap cancel', + ]; + properties.add(IterableProperty<String>('gestures', gestures, ifEmpty: '<none>')); + properties.add(DiagnosticsProperty<MouseCursor>('mouseCursor', mouseCursor)); + properties.add(DiagnosticsProperty<bool>('containedInkWell', containedInkWell, level: DiagnosticLevel.fine)); + properties.add(DiagnosticsProperty<BoxShape>( + 'highlightShape', + highlightShape, + description: '${containedInkWell ? "clipped to " : ""}$highlightShape', + showName: false, + )); + } +} + +/// Used to index the allocated highlights for the different types of highlights +/// in [_InkResponseState]. +enum _HighlightType { + pressed, + hover, + focus, +} + +class _InkResponseState extends State<_InkResponseStateWidget> with AutomaticKeepAliveClientMixin<_InkResponseStateWidget> implements _ParentInkResponseState { + Set<InteractiveInkFeature>? _splashes; + InteractiveInkFeature? _currentSplash; + bool _hovering = false; + final Map<_HighlightType, InkHighlight?> _highlights = <_HighlightType, InkHighlight?>{}; + late final Map<Type, Action<Intent>> _actionMap = <Type, Action<Intent>>{ + ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: activateOnIntent), + ButtonActivateIntent: CallbackAction<ButtonActivateIntent>(onInvoke: activateOnIntent), + }; + WidgetStatesController? internalStatesController; + + bool get highlightsExist => _highlights.values.where((highlight) => highlight != null).isNotEmpty; + + final ObserverList<_ParentInkResponseState> _activeChildren = ObserverList<_ParentInkResponseState>(); + + static const Duration _activationDuration = Duration(milliseconds: 100); + Timer? _activationTimer; + + @override + void markChildInkResponsePressed(_ParentInkResponseState childState, bool value) { + final bool lastAnyPressed = _anyChildInkResponsePressed; + if (value) { + _activeChildren.add(childState); + } else { + _activeChildren.remove(childState); + } + final bool nowAnyPressed = _anyChildInkResponsePressed; + if (nowAnyPressed != lastAnyPressed) { + widget.parentState?.markChildInkResponsePressed(this, nowAnyPressed); + } + } + + bool get _anyChildInkResponsePressed => _activeChildren.isNotEmpty; + + void activateOnIntent(Intent? intent) { + _activationTimer?.cancel(); + _activationTimer = null; + _startNewSplash(context: context); + _currentSplash?.confirm(); + _currentSplash = null; + if (widget.onTap != null) { + if (widget.enableFeedback) { + Feedback.forTap(context); + } + widget.onTap?.call(); + } + // Delay the call to `updateHighlight` to simulate a pressed delay + // and give MaterialStatesController listeners a chance to react. + _activationTimer = Timer(_activationDuration, () { + updateHighlight(_HighlightType.pressed, value: false); + }); + } + + void simulateTap([Intent? intent]) { + _startNewSplash(context: context); + handleTap(); + } + + void simulateLongPress() { + _startNewSplash(context: context); + handleLongPress(); + } + + void handleStatesControllerChange() { + // Force a rebuild to resolve widget.overlayColor, widget.mouseCursor + setState(() {}); + } + + WidgetStatesController get statesController => widget.statesController ?? internalStatesController!; + + void initStatesController() { + if (widget.statesController == null) { + internalStatesController = WidgetStatesController(); + } + statesController.update(WidgetState.disabled, !enabled); + statesController.addListener(handleStatesControllerChange); + } + + @override + void initState() { + super.initState(); + initStatesController(); + FocusManager.instance.addHighlightModeListener(handleFocusHighlightModeChange); + } + + @override + void didUpdateWidget(_InkResponseStateWidget oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.statesController != oldWidget.statesController) { + oldWidget.statesController?.removeListener(handleStatesControllerChange); + if (widget.statesController != null) { + internalStatesController?.dispose(); + internalStatesController = null; + } + initStatesController(); + } + if (widget.radius != oldWidget.radius || widget.highlightShape != oldWidget.highlightShape || widget.borderRadius != oldWidget.borderRadius) { + final InkHighlight? hoverHighlight = _highlights[_HighlightType.hover]; + if (hoverHighlight != null) { + hoverHighlight.dispose(); + updateHighlight(_HighlightType.hover, value: _hovering, callOnHover: false); + } + final InkHighlight? focusHighlight = _highlights[_HighlightType.focus]; + if (focusHighlight != null) { + focusHighlight.dispose(); + // Do not call updateFocusHighlights() here because it is called below + } + } + if (widget.customBorder != oldWidget.customBorder) { + _updateHighlightsAndSplashes(); + } + if (enabled != isWidgetEnabled(oldWidget)) { + statesController.update(WidgetState.disabled, !enabled); + if (!enabled) { + statesController.update(WidgetState.pressed, false); + // Remove the existing hover highlight immediately when enabled is false. + // Do not rely on updateHighlight or InkHighlight.deactivate to not break + // the expected lifecycle which is updating _hovering when the mouse exit. + // Manually updating _hovering here or calling InkHighlight.deactivate + // will lead to onHover not being called or call when it is not allowed. + final InkHighlight? hoverHighlight = _highlights[_HighlightType.hover]; + hoverHighlight?.dispose(); + } + // Don't call widget.onHover because many widgets, including the button + // widgets, apply setState to an ancestor context from onHover. + updateHighlight(_HighlightType.hover, value: _hovering, callOnHover: false); + } + updateFocusHighlights(); + } + + @override + void dispose() { + FocusManager.instance.removeHighlightModeListener(handleFocusHighlightModeChange); + statesController.removeListener(handleStatesControllerChange); + internalStatesController?.dispose(); + _activationTimer?.cancel(); + _activationTimer = null; + super.dispose(); + } + + @override + bool get wantKeepAlive => highlightsExist || (_splashes != null && _splashes!.isNotEmpty); + + Duration getFadeDurationForType(_HighlightType type) { + switch (type) { + case _HighlightType.pressed: + return const Duration(milliseconds: 200); + case _HighlightType.hover: + case _HighlightType.focus: + return widget.hoverDuration ?? const Duration(milliseconds: 50); + } + } + + void updateHighlight(_HighlightType type, {required bool value, bool callOnHover = true}) { + final InkHighlight? highlight = _highlights[type]; + void handleInkRemoval() { + assert(_highlights[type] != null); + _highlights[type] = null; + updateKeepAlive(); + } + + switch (type) { + case _HighlightType.pressed: + statesController.update(WidgetState.pressed, value); + case _HighlightType.hover: + if (callOnHover) { + statesController.update(WidgetState.hovered, value); + } + case _HighlightType.focus: + // see handleFocusUpdate() + break; + } + + if (type == _HighlightType.pressed) { + widget.parentState?.markChildInkResponsePressed(this, value); + } + if (value == (highlight != null && highlight.active)) { + return; + } + + if (value) { + if (highlight == null) { + final Color resolvedOverlayColor = widget.overlayColor?.resolve(statesController.value) ?? + switch (type) { + // Use the backwards compatible defaults + _HighlightType.pressed => widget.highlightColor ?? Theme.of(context).highlightColor, + _HighlightType.focus => widget.focusColor ?? Theme.of(context).focusColor, + _HighlightType.hover => widget.hoverColor ?? Theme.of(context).hoverColor, + }; + final RenderBox referenceBox = context.findRenderObject()! as RenderBox; + _highlights[type] = InkHighlight( + controller: Material.of(context), + referenceBox: referenceBox, + color: enabled ? resolvedOverlayColor : resolvedOverlayColor.withAlpha(0), + shape: widget.highlightShape, + radius: widget.radius, + borderRadius: widget.borderRadius, + customBorder: widget.customBorder, + rectCallback: widget.getRectCallback!(referenceBox), + onRemoved: handleInkRemoval, + textDirection: Directionality.of(context), + fadeDuration: getFadeDurationForType(type), + ); + updateKeepAlive(); + } else { + highlight.activate(); + } + } else { + highlight!.deactivate(); + } + assert(value == (_highlights[type] != null && _highlights[type]!.active)); + + switch (type) { + case _HighlightType.pressed: + widget.onHighlightChanged?.call(value); + case _HighlightType.hover: + if (callOnHover) { + widget.onHover?.call(value); + } + case _HighlightType.focus: + break; + } + } + + void _updateHighlightsAndSplashes() { + for (final InkHighlight? highlight in _highlights.values) { + highlight?.customBorder = widget.customBorder; + } + _currentSplash?.customBorder = widget.customBorder; + + if (_splashes != null && _splashes!.isNotEmpty) { + for (final InteractiveInkFeature inkFeature in _splashes!) { + inkFeature.customBorder = widget.customBorder; + } + } + } + + InteractiveInkFeature _createSplash(Offset globalPosition) { + final MaterialInkController inkController = Material.of(context); + final RenderBox referenceBox = context.findRenderObject()! as RenderBox; + final Offset position = referenceBox.globalToLocal(globalPosition); + final Color color = widget.overlayColor?.resolve(statesController.value) ?? widget.splashColor ?? Theme.of(context).splashColor; + final RectCallback? rectCallback = widget.containedInkWell ? widget.getRectCallback!(referenceBox) : null; + final BorderRadius? borderRadius = widget.borderRadius; + final ShapeBorder? customBorder = widget.customBorder; + + InteractiveInkFeature? splash; + void onRemoved() { + if (_splashes != null) { + assert(_splashes!.contains(splash)); + _splashes!.remove(splash); + if (_currentSplash == splash) { + _currentSplash = null; + } + updateKeepAlive(); + } // else we're probably in deactivate() + } + + splash = (widget.splashFactory ?? Theme.of(context).splashFactory).create( + controller: inkController, + referenceBox: referenceBox, + position: position, + color: color, + containedInkWell: widget.containedInkWell, + rectCallback: rectCallback, + radius: widget.radius, + borderRadius: borderRadius, + customBorder: customBorder, + onRemoved: onRemoved, + textDirection: Directionality.of(context), + ); + + return splash; + } + + void handleFocusHighlightModeChange(FocusHighlightMode mode) { + if (!mounted) { + return; + } + setState(updateFocusHighlights); + } + + bool get _shouldShowFocus { + return switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => enabled && _hasFocus, + NavigationMode.directional => _hasFocus, + }; + } + + void updateFocusHighlights() { + final bool showFocus = switch (FocusManager.instance.highlightMode) { + FocusHighlightMode.touch => false, + FocusHighlightMode.traditional => _shouldShowFocus, + }; + updateHighlight(_HighlightType.focus, value: showFocus); + } + + bool _hasFocus = false; + + void handleFocusUpdate(bool hasFocus) { + _hasFocus = hasFocus; + // Set here rather than updateHighlight because this widget's + // (MaterialState) states include MaterialState.focused if + // the InkWell _has_ the focus, rather than if it's showing + // the focus per FocusManager.instance.highlightMode. + statesController.update(WidgetState.focused, hasFocus); + updateFocusHighlights(); + widget.onFocusChange?.call(hasFocus); + } + + void handleAnyTapDown(TapDownDetails details) { + if (_anyChildInkResponsePressed) { + return; + } + _startNewSplash(details: details); + } + + void handleTapDown(TapDownDetails details) { + handleAnyTapDown(details); + widget.onTapDown?.call(details); + } + + void handleTapUp(TapUpDetails details) { + widget.onTapUp?.call(details); + } + + void handleSecondaryTapDown(TapDownDetails details) { + handleAnyTapDown(details); + widget.onSecondaryTapDown?.call(details); + } + + void handleSecondaryTapUp(TapUpDetails details) { + widget.onSecondaryTapUp?.call(details); + } + + void _startNewSplash({TapDownDetails? details, BuildContext? context}) { + assert(details != null || context != null); + + final Offset globalPosition; + if (context != null) { + final RenderBox referenceBox = context.findRenderObject()! as RenderBox; + assert(referenceBox.hasSize, 'InkResponse must be done with layout before starting a splash.'); + globalPosition = referenceBox.localToGlobal(referenceBox.paintBounds.center); + } else { + globalPosition = details!.globalPosition; + } + statesController.update(WidgetState.pressed, true); // ... before creating the splash + final InteractiveInkFeature splash = _createSplash(globalPosition); + _splashes ??= HashSet<InteractiveInkFeature>(); + _splashes!.add(splash); + _currentSplash?.cancel(); + _currentSplash = splash; + updateKeepAlive(); + updateHighlight(_HighlightType.pressed, value: true); + } + + void handleTap() { + _currentSplash?.confirm(); + _currentSplash = null; + updateHighlight(_HighlightType.pressed, value: false); + if (widget.onTap != null) { + if (widget.enableFeedback) { + Feedback.forTap(context); + } + widget.onTap?.call(); + } + } + + void handleTapCancel() { + _currentSplash?.cancel(); + _currentSplash = null; + widget.onTapCancel?.call(); + updateHighlight(_HighlightType.pressed, value: false); + } + + void handleDoubleTap() { + _currentSplash?.confirm(); + _currentSplash = null; + updateHighlight(_HighlightType.pressed, value: false); + widget.onDoubleTap?.call(); + } + + void handleLongPress() { + _currentSplash?.confirm(); + _currentSplash = null; + if (widget.onLongPress != null) { + if (widget.enableFeedback) { + Feedback.forLongPress(context); + } + widget.onLongPress!(); + } + } + + void handleSecondaryTap() { + _currentSplash?.confirm(); + _currentSplash = null; + updateHighlight(_HighlightType.pressed, value: false); + widget.onSecondaryTap?.call(); + } + + void handleSecondaryTapCancel() { + _currentSplash?.cancel(); + _currentSplash = null; + widget.onSecondaryTapCancel?.call(); + updateHighlight(_HighlightType.pressed, value: false); + } + + @override + void deactivate() { + if (_splashes != null) { + final Set<InteractiveInkFeature> splashes = _splashes!; + _splashes = null; + for (final InteractiveInkFeature splash in splashes) { + splash.dispose(); + } + _currentSplash = null; + } + assert(_currentSplash == null); + for (final _HighlightType highlight in _highlights.keys) { + _highlights[highlight]?.dispose(); + _highlights[highlight] = null; + } + widget.parentState?.markChildInkResponsePressed(this, false); + super.deactivate(); + } + + bool isWidgetEnabled(_InkResponseStateWidget widget) { + return _primaryButtonEnabled(widget) || _secondaryButtonEnabled(widget); + } + + bool _primaryButtonEnabled(_InkResponseStateWidget widget) { + return widget.onTap != null || widget.onDoubleTap != null || widget.onLongPress != null || widget.onTapUp != null || widget.onTapDown != null; + } + + bool _secondaryButtonEnabled(_InkResponseStateWidget widget) { + return widget.onSecondaryTap != null || widget.onSecondaryTapUp != null || widget.onSecondaryTapDown != null; + } + + bool get enabled => isWidgetEnabled(widget); + + bool get _primaryEnabled => _primaryButtonEnabled(widget); + + bool get _secondaryEnabled => _secondaryButtonEnabled(widget); + + void handleMouseEnter(PointerEnterEvent event) { + _hovering = true; + if (enabled) { + handleHoverChange(); + } + } + + void handleMouseExit(PointerExitEvent event) { + _hovering = false; + // If the exit occurs after we've been disabled, we still + // want to take down the highlights and run widget.onHover. + handleHoverChange(); + } + + void handleHoverChange() { + updateHighlight(_HighlightType.hover, value: _hovering); + } + + bool get _canRequestFocus { + return switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => enabled && widget.canRequestFocus, + NavigationMode.directional => true, + }; + } + + @override + Widget build(BuildContext context) { + assert(widget.debugCheckContext(context)); + super.build(context); // See AutomaticKeepAliveClientMixin. + + Color getHighlightColorForType(_HighlightType type) { + const Set<WidgetState> pressed = <WidgetState>{WidgetState.pressed}; + const Set<WidgetState> focused = <WidgetState>{WidgetState.focused}; + const Set<WidgetState> hovered = <WidgetState>{WidgetState.hovered}; + + final ThemeData theme = Theme.of(context); + return switch (type) { + // The pressed state triggers a ripple (ink splash), per the current + // Material Design spec. A separate highlight is no longer used. + // See https://material.io/design/interaction/states.html#pressed + _HighlightType.pressed => widget.overlayColor?.resolve(pressed) ?? widget.highlightColor ?? theme.highlightColor, + _HighlightType.focus => widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor, + _HighlightType.hover => widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor, + }; + } + + for (final _HighlightType type in _highlights.keys) { + _highlights[type]?.color = getHighlightColorForType(type); + } + + _currentSplash?.color = widget.overlayColor?.resolve(statesController.value) ?? widget.splashColor ?? Theme.of(context).splashColor; + + final MouseCursor effectiveMouseCursor = WidgetStateProperty.resolveAs<MouseCursor>( + widget.mouseCursor ?? WidgetStateMouseCursor.clickable, + statesController.value, + ); + + return _ParentInkResponseProvider( + state: this, + child: Actions( + actions: _actionMap, + child: Focus( + focusNode: widget.focusNode, + canRequestFocus: _canRequestFocus, + onFocusChange: handleFocusUpdate, + autofocus: widget.autofocus, + child: MouseRegion( + cursor: effectiveMouseCursor, + onEnter: handleMouseEnter, + onExit: handleMouseExit, + child: DefaultSelectionStyle.merge( + mouseCursor: effectiveMouseCursor, + child: Semantics( + onTap: widget.excludeFromSemantics || widget.onTap == null ? null : simulateTap, + onLongPress: widget.excludeFromSemantics || widget.onLongPress == null ? null : simulateLongPress, + child: AGestureDetector( + onTapDown: _primaryEnabled ? handleTapDown : null, + onTapUp: _primaryEnabled ? handleTapUp : null, + onTap: _primaryEnabled ? handleTap : null, + onTapCancel: _primaryEnabled ? handleTapCancel : null, + onDoubleTap: widget.onDoubleTap != null ? handleDoubleTap : null, + onLongPress: widget.onLongPress != null ? handleLongPress : null, + onSecondaryTapDown: _secondaryEnabled ? handleSecondaryTapDown : null, + onSecondaryTapUp: _secondaryEnabled ? handleSecondaryTapUp : null, + onSecondaryTap: _secondaryEnabled ? handleSecondaryTap : null, + onSecondaryTapCancel: _secondaryEnabled ? handleSecondaryTapCancel : null, + behavior: HitTestBehavior.opaque, + excludeFromSemantics: true, + longPressTimeout: widget.longPressTimeout, + child: widget.child, + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/insets.dart b/lib/widgets/common/basic/insets.dart new file mode 100644 index 0000000..1e083a3 --- /dev/null +++ b/lib/widgets/common/basic/insets.dart @@ -0,0 +1,225 @@ +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +// This widget should be added on top of Scaffolds with: +// - `resizeToAvoidBottomInset` set to false, +// - a vertically scrollable body. +// It will prevent the body from scrolling when a user swipe from bottom to use Android 10 style navigation gestures. +class BottomGestureAreaProtector extends StatelessWidget { + const BottomGestureAreaProtector({super.key}); + + @override + Widget build(BuildContext context) { + return Positioned( + left: 0, + right: 0, + bottom: 0, + height: MediaQuery.systemGestureInsetsOf(context).bottom, + child: GestureDetector( + // absorb vertical gestures only + onVerticalDragDown: (details) {}, + behavior: HitTestBehavior.translucent, + ), + ); + } +} + +// It will prevent the body from scrolling when a user swipe from top to show the status bar when system UI is hidden. +class TopGestureAreaProtector extends StatelessWidget { + const TopGestureAreaProtector({super.key}); + + @override + Widget build(BuildContext context) { + return Positioned( + left: 0, + top: 0, + right: 0, + height: MediaQuery.systemGestureInsetsOf(context).top, + child: GestureDetector( + // absorb vertical gestures only + onVerticalDragDown: (details) {}, + behavior: HitTestBehavior.translucent, + ), + ); + } +} + +// It will prevent the body from scrolling when a user swipe from edges to use Android 10 style navigation gestures. +class SideGestureAreaProtector extends StatelessWidget { + const SideGestureAreaProtector({super.key}); + + @override + Widget build(BuildContext context) { + return Positioned.fill( + child: Row( + // `systemGestureInsets` are not directional + textDirection: TextDirection.ltr, + children: [ + SizedBox( + width: MediaQuery.systemGestureInsetsOf(context).left, + child: GestureDetector( + // absorb horizontal gestures only + onHorizontalDragDown: (details) {}, + behavior: HitTestBehavior.translucent, + ), + ), + const Spacer(), + SizedBox( + width: MediaQuery.systemGestureInsetsOf(context).right, + child: GestureDetector( + // absorb horizontal gestures only + onHorizontalDragDown: (details) {}, + behavior: HitTestBehavior.translucent, + ), + ), + ], + ), + ); + } +} + +class GestureAreaProtectorStack extends StatelessWidget { + final Widget child; + + const GestureAreaProtectorStack({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + child, + const BottomGestureAreaProtector(), + ], + ); + } +} + +class BottomPaddingSliver extends StatelessWidget { + const BottomPaddingSliver({super.key}); + + @override + Widget build(BuildContext context) { + return SliverToBoxAdapter( + child: Selector<MediaQueryData, double>( + selector: (context, mq) => mq.effectiveBottomPadding, + builder: (context, mqPaddingBottom, child) { + return SizedBox(height: mqPaddingBottom); + }, + ), + ); + } +} + +class TvTileGridBottomPaddingSliver extends StatelessWidget { + const TvTileGridBottomPaddingSliver({super.key}); + + @override + Widget build(BuildContext context) { + return SliverToBoxAdapter( + child: SizedBox( + height: settings.useTvLayout ? context.select<TileExtentController, double>((controller) => controller.spacing) : 0, + ), + ); + } +} + +// `MediaQuery.padding` matches cutout areas but also includes other system UI like the status bar +// so we cannot use `SafeArea` along `MediaQuery.removePadding()` to remove cutout areas +class SafeCutoutArea extends StatelessWidget { + final Animation<double>? animation; + final Widget child; + + const SafeCutoutArea({ + super.key, + this.animation, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<EdgeInsets>( + valueListenable: AvesApp.cutoutInsetsNotifier, + builder: (context, cutoutInsets, child) { + return NullableValueListenableBuilder<double>( + valueListenable: animation, + builder: (context, value, child) { + final double factor = value ?? 1.0; + final effectiveInsets = cutoutInsets * factor; + return Padding( + padding: effectiveInsets, + child: MediaQueryDataProvider( + value: MediaQuery.of(context).removeCutoutInsets(effectiveInsets), + child: child!, + ), + ); + }, + child: child, + ); + }, + child: child, + ); + } +} + +extension ExtraMediaQueryData on MediaQueryData { + MediaQueryData removeCutoutInsets(EdgeInsets cutoutInsets) { + return copyWith( + padding: EdgeInsets.only( + left: max(0.0, padding.left - cutoutInsets.left), + top: max(0.0, padding.top - cutoutInsets.top), + right: max(0.0, padding.right - cutoutInsets.right), + bottom: max(0.0, padding.bottom - cutoutInsets.bottom), + ), + viewPadding: EdgeInsets.only( + left: max(0.0, viewPadding.left - cutoutInsets.left), + top: max(0.0, viewPadding.top - cutoutInsets.top), + right: max(0.0, viewPadding.right - cutoutInsets.right), + bottom: max(0.0, viewPadding.bottom - cutoutInsets.bottom), + ), + ); + } +} + +class DirectionalSafeArea extends StatelessWidget { + final bool start, top, end, bottom; + final EdgeInsets minimum; + final bool maintainBottomViewPadding; + final Widget child; + + const DirectionalSafeArea({ + super.key, + this.start = true, + this.top = true, + this.end = true, + this.bottom = true, + this.minimum = EdgeInsets.zero, + this.maintainBottomViewPadding = false, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final isRtl = context.isRtl; + return SafeArea( + left: isRtl ? end : start, + top: top, + right: isRtl ? start : end, + bottom: bottom, + minimum: minimum, + maintainBottomViewPadding: maintainBottomViewPadding, + child: child, + ); + } +} diff --git a/lib/widgets/common/basic/labeled_checkbox.dart b/lib/widgets/common/basic/labeled_checkbox.dart new file mode 100644 index 0000000..c106e07 --- /dev/null +++ b/lib/widgets/common/basic/labeled_checkbox.dart @@ -0,0 +1,55 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +class LabeledCheckbox extends StatefulWidget { + final bool value; + final ValueChanged<bool?> onChanged; + final String text; + + const LabeledCheckbox({ + super.key, + required this.value, + required this.onChanged, + required this.text, + }); + + @override + State<LabeledCheckbox> createState() => _LabeledCheckboxState(); +} + +class _LabeledCheckboxState extends State<LabeledCheckbox> { + late TapGestureRecognizer _tapRecognizer; + + @override + void initState() { + super.initState(); + _tapRecognizer = TapGestureRecognizer()..onTap = () => widget.onChanged(!widget.value); + } + + @override + void dispose() { + _tapRecognizer.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Text.rich( + TextSpan( + children: [ + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Checkbox( + value: widget.value, + onChanged: widget.onChanged, + ), + ), + TextSpan( + text: widget.text, + recognizer: _tapRecognizer, + ), + ], + ), + ); + } +} diff --git a/lib/widgets/common/basic/link_chip.dart b/lib/widgets/common/basic/link_chip.dart new file mode 100644 index 0000000..53ddc65 --- /dev/null +++ b/lib/widgets/common/basic/link_chip.dart @@ -0,0 +1,63 @@ +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:flutter/material.dart'; + +class LinkChip extends StatelessWidget { + final Widget? leading; + final String text; + final String? urlString; + final Color? color; + final TextStyle? textStyle; + final VoidCallback? onTap; + + static const borderRadius = BorderRadius.all(Radius.circular(8)); + + const LinkChip({ + super.key, + this.leading, + required this.text, + this.urlString, + this.color, + this.textStyle, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + return DefaultTextStyle.merge( + style: (textStyle ?? const TextStyle()).copyWith(color: color), + child: InkWell( + borderRadius: borderRadius, + onTap: onTap ?? () => AvesApp.launchUrl(urlString), + child: Padding( + padding: const EdgeInsets.all(8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (leading != null) ...[ + leading!, + const SizedBox(width: 8), + ], + Flexible( + child: Text( + text, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ), + const SizedBox(width: 8), + Builder( + builder: (context) => Icon( + AIcons.openOutside, + size: DefaultTextStyle.of(context).style.fontSize, + color: color, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/list_tiles/color.dart b/lib/widgets/common/basic/list_tiles/color.dart new file mode 100644 index 0000000..93d2e2a --- /dev/null +++ b/lib/widgets/common/basic/list_tiles/color.dart @@ -0,0 +1,99 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/basic/color_indicator.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flex_color_picker/flex_color_picker.dart' show ColorPicker, ColorPickerType; +import 'package:flutter/material.dart'; + +class ColorListTile extends StatelessWidget { + final String title; + final Color value; + final ValueSetter<Color> onChanged; + + const ColorListTile({ + super.key, + required this.title, + required this.value, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + title: Text(title), + trailing: ColorIndicator( + value: value, + ), + contentPadding: const EdgeInsetsDirectional.only(start: 16, end: 36 - ColorIndicator.radius), + onTap: () async { + final color = await showDialog<Color>( + context: context, + builder: (context) => ColorPickerDialog( + initialValue: value, + ), + routeSettings: const RouteSettings(name: ColorPickerDialog.routeName), + ); + if (color != null) { + onChanged(color); + } + }, + ); + } +} + +class ColorPickerDialog extends StatefulWidget { + static const routeName = '/dialog/pick_color'; + + final Color initialValue; + + const ColorPickerDialog({ + super.key, + required this.initialValue, + }); + + @override + State<ColorPickerDialog> createState() => _ColorPickerDialogState(); +} + +class _ColorPickerDialogState extends State<ColorPickerDialog> { + late Color color; + + @override + void initState() { + super.initState(); + color = widget.initialValue; + } + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + return AvesDialog( + scrollableContent: [ + ColorPicker( + color: color, + onColorChanged: (v) => color = v, + pickersEnabled: useTvLayout + ? const { + ColorPickerType.primary: true, + ColorPickerType.accent: false, + } + : const { + ColorPickerType.primary: false, + ColorPickerType.accent: false, + ColorPickerType.wheel: true, + }, + hasBorder: true, + borderRadius: 20, + subheading: useTvLayout ? const SizedBox(height: 16) : null, + ) + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(color), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } +} diff --git a/lib/widgets/common/basic/list_tiles/reselectable_radio.dart b/lib/widgets/common/basic/list_tiles/reselectable_radio.dart new file mode 100644 index 0000000..1f937da --- /dev/null +++ b/lib/widgets/common/basic/list_tiles/reselectable_radio.dart @@ -0,0 +1,89 @@ +import 'package:flutter/material.dart'; + +// `RadioListTile` that can trigger `onChanged` on tap when already selected, if `reselectable` is true +class ReselectableRadioListTile<T> extends StatelessWidget { + final T value; + final T groupValue; + final ValueChanged<T?>? onChanged; + final bool toggleable; + final bool reselectable; + final Color? activeColor; + final Widget? title; + final Widget? subtitle; + final Widget? secondary; + final bool isThreeLine; + final bool? dense; + final bool selected; + final ListTileControlAffinity controlAffinity; + final bool autofocus; + + bool get checked => value == groupValue; + + const ReselectableRadioListTile({ + super.key, + required this.value, + required this.groupValue, + required this.onChanged, + this.toggleable = false, + this.reselectable = false, + this.activeColor, + this.title, + this.subtitle, + this.isThreeLine = false, + this.dense, + this.secondary, + this.selected = false, + this.controlAffinity = ListTileControlAffinity.platform, + this.autofocus = false, + }) : assert(!isThreeLine || subtitle != null); + + @override + Widget build(BuildContext context) { + final Widget control = Radio<T>( + value: value, + groupValue: groupValue, + onChanged: onChanged, + toggleable: toggleable, + activeColor: activeColor, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + autofocus: autofocus, + ); + Widget? leading, trailing; + switch (controlAffinity) { + case ListTileControlAffinity.leading: + case ListTileControlAffinity.platform: + leading = control; + trailing = secondary; + case ListTileControlAffinity.trailing: + leading = secondary; + trailing = control; + } + return MergeSemantics( + child: ListTileTheme.merge( + selectedColor: activeColor ?? Theme.of(context).colorScheme.primary, + child: ListTile( + leading: leading, + title: title, + subtitle: subtitle, + trailing: trailing, + isThreeLine: isThreeLine, + dense: dense, + enabled: onChanged != null, + onTap: onChanged != null + ? () { + if (toggleable && checked) { + onChanged!(null); + return; + } + if (reselectable || !checked) { + onChanged!(value); + } + } + : null, + selected: selected, + autofocus: autofocus, + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/list_tiles/slider.dart b/lib/widgets/common/basic/list_tiles/slider.dart new file mode 100644 index 0000000..1a95a2e --- /dev/null +++ b/lib/widgets/common/basic/list_tiles/slider.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; + +class SliderListTile extends StatelessWidget { + final String title; + final double value; + final ValueChanged<double>? onChanged; + final double min; + final double max; + final int? divisions; + final EdgeInsetsGeometry titlePadding; + final Widget Function(BuildContext context, double value)? titleTrailing; + + const SliderListTile({ + super.key, + required this.title, + required this.value, + required this.onChanged, + this.min = 0.0, + this.max = 1.0, + this.divisions, + this.titlePadding = const EdgeInsetsDirectional.only(start: 16), + this.titleTrailing, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final listTileTitleTextStyle = ListTileTheme.of(context).titleTextStyle ?? theme.textTheme.bodyLarge!.copyWith(color: theme.colorScheme.onSurface); + return SliderTheme( + data: SliderTheme.of(context).copyWith( + overlayShape: const RoundSliderOverlayShape( + // align `Slider`s on `Switch`es by matching their overlay/reaction radius + // `kRadialReactionRadius` is used when `SwitchThemeData.splashRadius` is undefined + overlayRadius: kRadialReactionRadius, + ), + ), + child: Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: titlePadding, + child: Row( + children: [ + Text( + title, + style: listTileTitleTextStyle, + ), + const Spacer(), + if (titleTrailing != null) titleTrailing!(context, value), + ], + ), + ), + Padding( + // match `SwitchListTile.contentPadding` + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Slider( + value: value, + onChanged: onChanged, + min: min, + max: max, + divisions: divisions, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/markdown_container.dart b/lib/widgets/common/basic/markdown_container.dart new file mode 100644 index 0000000..391b34a --- /dev/null +++ b/lib/widgets/common/basic/markdown_container.dart @@ -0,0 +1,71 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; + +class MarkdownContainer extends StatelessWidget { + final String data; + final TextDirection? textDirection; + final ScrollController? scrollController; + + const MarkdownContainer({ + super.key, + required this.data, + this.textDirection, + this.scrollController, + }); + + static const double mobileMaxWidth = 460; + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + + Widget child = Directionality( + textDirection: textDirection ?? Directionality.of(context), + child: Markdown( + data: data, + selectable: true, + onTapLink: (text, href, title) => AvesApp.launchUrl(href), + controller: scrollController, + shrinkWrap: true, + ), + ); + + if (!useTvLayout) { + child = Theme( + data: Theme.of(context).copyWith( + scrollbarTheme: ScrollbarThemeData( + thumbVisibility: WidgetStateProperty.all(true), + radius: const Radius.circular(16), + crossAxisMargin: 6, + mainAxisMargin: 16, + interactive: true, + ), + ), + child: Scrollbar( + child: child, + ), + ); + } + + return Container( + margin: const EdgeInsets.symmetric(horizontal: 8), + decoration: BoxDecoration( + color: Themes.secondLayerColor(context), + border: Border.all( + color: Theme.of(context).dividerColor, + width: AvesBorder.curvedBorderWidth(context), + ), + borderRadius: const BorderRadius.all(Radius.circular(16)), + ), + constraints: BoxConstraints(maxWidth: useTvLayout ? double.infinity : mobileMaxWidth), + child: ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(16)), + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/basic/multi_cross_fader.dart b/lib/widgets/common/basic/multi_cross_fader.dart new file mode 100644 index 0000000..df65a57 --- /dev/null +++ b/lib/widgets/common/basic/multi_cross_fader.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; + +class MultiCrossFader extends StatefulWidget { + final Duration duration; + final Curve fadeCurve, sizeCurve; + final AlignmentGeometry alignment; + final AnimatedCrossFadeBuilder layoutBuilder; + final Widget child; + + const MultiCrossFader({ + super.key, + required this.duration, + this.fadeCurve = Curves.linear, + this.sizeCurve = Curves.linear, + this.alignment = Alignment.topCenter, + this.layoutBuilder = AnimatedCrossFade.defaultLayoutBuilder, + required this.child, + }); + + @override + State<MultiCrossFader> createState() => _MultiCrossFaderState(); +} + +class _MultiCrossFaderState extends State<MultiCrossFader> { + late Widget _first, _second; + CrossFadeState _fadeState = CrossFadeState.showFirst; + + @override + void initState() { + super.initState(); + _first = widget.child; + _second = const SizedBox(); + } + + @override + void didUpdateWidget(covariant MultiCrossFader oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.child == _first) { + _second = widget.child; + _fadeState = CrossFadeState.showSecond; + } else { + _first = widget.child; + _fadeState = CrossFadeState.showFirst; + } + } + + @override + Widget build(BuildContext context) { + return AnimatedCrossFade( + firstChild: _first, + secondChild: _second, + firstCurve: widget.fadeCurve, + secondCurve: widget.fadeCurve, + sizeCurve: widget.sizeCurve, + alignment: widget.alignment, + crossFadeState: _fadeState, + duration: widget.duration, + reverseDuration: widget.duration, + layoutBuilder: widget.layoutBuilder, + ); + } +} diff --git a/lib/widgets/common/basic/popup/container.dart b/lib/widgets/common/basic/popup/container.dart new file mode 100644 index 0000000..30a0323 --- /dev/null +++ b/lib/widgets/common/basic/popup/container.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; + +class PopupMenuItemContainer<T> extends PopupMenuEntry<T> { + final Widget child; + + const PopupMenuItemContainer({ + super.key, + this.height = kMinInteractiveDimension, + required this.child, + }); + + @override + final double height; + + @override + bool represents(void value) => false; + + @override + State<PopupMenuItemContainer> createState() => _PopupMenuItemContainerState(); +} + +class _PopupMenuItemContainerState extends State<PopupMenuItemContainer> { + @override + Widget build(BuildContext context) { + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: widget.child, + ), + ); + } +} diff --git a/lib/widgets/common/basic/popup/expansion_panel.dart b/lib/widgets/common/basic/popup/expansion_panel.dart new file mode 100644 index 0000000..63bc94e --- /dev/null +++ b/lib/widgets/common/basic/popup/expansion_panel.dart @@ -0,0 +1,105 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class PopupMenuExpansionPanel<T> extends PopupMenuEntry<T> { + final bool enabled; + final String value; + final ValueNotifier<String?>? expandedNotifier; + final IconData icon; + final String title; + final List<PopupMenuEntry<T>> items; + + const PopupMenuExpansionPanel({ + super.key, + this.enabled = true, + this.height = kMinInteractiveDimension, + required this.value, + this.expandedNotifier, + required this.icon, + required this.title, + required this.items, + }); + + @override + final double height; + + @override + bool represents(void value) => false; + + @override + State<PopupMenuExpansionPanel<T>> createState() => _PopupMenuExpansionPanelState<T>(); +} + +class _PopupMenuExpansionPanelState<T> extends State<PopupMenuExpansionPanel<T>> { + final ValueNotifier<String?> _internalExpandedNotifier = ValueNotifier(null); + + ValueNotifier<String?> get expandedNotifier => widget.expandedNotifier ?? _internalExpandedNotifier; + + @override + void dispose() { + _internalExpandedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final style = PopupMenuTheme.of(context).labelTextStyle!.resolve( + <WidgetState>{ + if (!widget.enabled) WidgetState.disabled, + }, + )!; + final animationDuration = context.select<DurationsData, Duration>((v) => v.expansionTileAnimation); + + Widget child = ValueListenableBuilder<String?>( + valueListenable: expandedNotifier, + builder: (context, expandedValue, child) { + return ExpansionPanelList( + expansionCallback: (index, isExpanded) { + expandedNotifier.value = isExpanded ? widget.value : null; + }, + animationDuration: animationDuration, + expandedHeaderPadding: EdgeInsets.zero, + elevation: 0, + children: [ + ExpansionPanel( + headerBuilder: (context, isExpanded) { + return DefaultTextStyle( + style: style, + child: IconTheme.merge( + data: IconThemeData( + color: widget.enabled ? null : Theme.of(context).disabledColor, + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: MenuRow( + text: widget.title, + icon: Icon(widget.icon), + ), + ), + ), + ); + }, + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const PopupMenuDivider(height: 0), + ...widget.items, + const PopupMenuDivider(height: 0), + ], + ), + isExpanded: expandedValue == widget.value, + canTapOnHeader: true, + backgroundColor: Colors.transparent, + ), + ], + ); + }, + ); + if (!widget.enabled) { + child = IgnorePointer(child: child); + } + return child; + } +} diff --git a/lib/widgets/common/basic/popup/menu_row.dart b/lib/widgets/common/basic/popup/menu_row.dart new file mode 100644 index 0000000..23f77b4 --- /dev/null +++ b/lib/widgets/common/basic/popup/menu_row.dart @@ -0,0 +1,36 @@ +import 'package:flutter/material.dart'; + +class MenuRow extends StatelessWidget { + final String text; + final Widget? icon; + + const MenuRow({ + super.key, + required this.text, + this.icon, + }); + + static const leadingPadding = EdgeInsetsDirectional.only(end: 12); + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) + Padding( + padding: leadingPadding, + child: IconTheme.merge( + data: IconThemeData( + color: ListTileTheme.of(context).iconColor, + ), + child: icon!, + ), + ), + Flexible( + child: Text(text), + ), + ], + ); + } +} diff --git a/lib/widgets/common/basic/query_bar.dart b/lib/widgets/common/basic/query_bar.dart new file mode 100644 index 0000000..e2ddb31 --- /dev/null +++ b/lib/widgets/common/basic/query_bar.dart @@ -0,0 +1,112 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class QueryBar extends StatefulWidget { + final ValueNotifier<String> queryNotifier; + final FocusNode? focusNode; + final EdgeInsetsGeometry? leadingPadding; + final IconData? icon; + final String? hintText; + final bool editable; + + const QueryBar({ + super.key, + required this.queryNotifier, + this.focusNode, + this.leadingPadding, + this.icon, + this.hintText, + this.editable = true, + }); + + @override + State<QueryBar> createState() => _QueryBarState(); + + static double getPreferredHeight(TextScaler textScaler) => textScaler.scale(kToolbarHeight); +} + +class _QueryBarState extends State<QueryBar> { + final Debouncer _debouncer = Debouncer(delay: ADurations.searchDebounceDelay); + late TextEditingController _controller; + + ValueNotifier<String> get queryNotifier => widget.queryNotifier; + + @override + void initState() { + super.initState(); + _controller = TextEditingController(text: queryNotifier.value); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final clearButton = IconButton( + icon: const Icon(AIcons.clear), + onPressed: widget.editable + ? () { + _controller.clear(); + queryNotifier.value = ''; + } + : null, + tooltip: context.l10n.clearTooltip, + ); + + return DefaultTextStyle( + style: Theme.of(context).textTheme.bodyMedium!, + child: FontSizeIconTheme( + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: TextField( + controller: _controller, + focusNode: widget.focusNode, + decoration: InputDecoration( + icon: Padding( + padding: widget.leadingPadding ?? const EdgeInsetsDirectional.only(start: 16), + // set theme at this level because `InputDecoration` defines its own `IconTheme` with a fixed size + child: FontSizeIconTheme( + child: Icon(widget.icon ?? AIcons.filter), + ), + ), + hintText: widget.hintText ?? MaterialLocalizations.of(context).searchFieldLabel, + hintStyle: Theme.of(context).inputDecorationTheme.hintStyle, + ), + textInputAction: TextInputAction.search, + onChanged: (s) => _debouncer(() => queryNotifier.value = s.trim()), + enabled: widget.editable, + ), + ), + ConstrainedBox( + constraints: const BoxConstraints(minWidth: 16), + child: ValueListenableBuilder<TextEditingValue>( + valueListenable: _controller, + builder: (context, value, child) => AnimatedSwitcher( + duration: ADurations.appBarActionChangeAnimation, + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: SizeTransition( + axis: Axis.horizontal, + sizeFactor: animation, + child: child, + ), + ), + child: value.text.isNotEmpty ? clearButton : const SizedBox(), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/scaffold.dart b/lib/widgets/common/basic/scaffold.dart new file mode 100644 index 0000000..81058a6 --- /dev/null +++ b/lib/widgets/common/basic/scaffold.dart @@ -0,0 +1,42 @@ +import 'package:flutter/material.dart'; + +class AvesScaffold extends StatelessWidget { + final PreferredSizeWidget? appBar; + final Widget? body; + final Widget? floatingActionButton; + final Widget? drawer; + final Widget? bottomNavigationBar; + final Color? backgroundColor; + final bool? resizeToAvoidBottomInset; + final bool extendBody; + + const AvesScaffold({ + super.key, + this.appBar, + this.body, + this.floatingActionButton, + this.drawer, + this.bottomNavigationBar, + this.backgroundColor, + this.resizeToAvoidBottomInset, + this.extendBody = false, + }); + + @override + Widget build(BuildContext context) { + // prevent conflict between drawer drag gesture and Android navigation gestures + final drawerEnableOpenDragGesture = MediaQuery.systemGestureInsetsOf(context).horizontal == 0; + + return Scaffold( + appBar: appBar, + body: body, + floatingActionButton: floatingActionButton, + drawer: drawer, + bottomNavigationBar: bottomNavigationBar, + backgroundColor: backgroundColor, + resizeToAvoidBottomInset: resizeToAvoidBottomInset, + extendBody: extendBody, + drawerEnableOpenDragGesture: drawerEnableOpenDragGesture, + ); + } +} diff --git a/lib/widgets/common/basic/text/animated_diff.dart b/lib/widgets/common/basic/text/animated_diff.dart new file mode 100644 index 0000000..fe37d42 --- /dev/null +++ b/lib/widgets/common/basic/text/animated_diff.dart @@ -0,0 +1,179 @@ +import 'dart:math'; + +import 'package:aves/utils/diff_match.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +class AnimatedDiffText extends StatefulWidget { + final String text; + final TextStyle? textStyle; + final StrutStyle? strutStyle; + final Curve curve; + final Duration duration; + + const AnimatedDiffText( + this.text, { + super.key, + this.textStyle, + this.strutStyle, + this.curve = Curves.easeInOutCubic, + required this.duration, + }); + + @override + State<AnimatedDiffText> createState() => _AnimatedDiffTextState(); +} + +class _AnimatedDiffTextState extends State<AnimatedDiffText> with SingleTickerProviderStateMixin { + late final AnimationController _controller; + late final CurvedAnimation _animation; + final List<_TextDiff> _diffs = []; + + TextStyle get _textStyle { + final style = widget.textStyle ?? const TextStyle(); + // specify `height` for accurate paragraph height measurement + return style.copyWith(height: style.height ?? DefaultTextStyle.of(context).style.height); + } + + StrutStyle? get _strutStyle => widget.strutStyle; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + duration: widget.duration, + vsync: this, + ); + _animation = CurvedAnimation(parent: _controller, curve: widget.curve); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _computeDiff(widget.text, widget.text); + } + + @override + void didUpdateWidget(covariant AnimatedDiffText oldWidget) { + super.didUpdateWidget(oldWidget); + final oldText = oldWidget.text; + final newText = widget.text; + if (oldText != newText) { + _computeDiff(oldText, newText); + _controller.forward(from: 0); + } + } + + @override + void dispose() { + _animation.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: _animation, + builder: (context, child) { + return Text.rich( + TextSpan( + children: _diffs.map((diff) { + final (oldText, newText, oldSize, newSize) = diff; + final text = (_animation.value == 0 ? oldText : newText) ?? ''; + return WidgetSpan( + child: AnimatedSize( + key: ValueKey(diff), + curve: widget.curve, + duration: widget.duration, + child: AnimatedSwitcher( + duration: widget.duration, + switchInCurve: widget.curve, + switchOutCurve: widget.curve, + layoutBuilder: (currentChild, previousChildren) { + return Stack( + alignment: Alignment.center, + children: [ + ...previousChildren.map( + (child) => ConstrainedBox( + constraints: BoxConstraints.tight(Size( + min(oldSize.width, newSize.width), + min(oldSize.height, newSize.height), + )), + child: child, + ), + ), + if (currentChild != null) currentChild, + ], + ); + }, + child: Text( + text, + key: Key(text), + style: _textStyle, + ), + ), + ), + ); + }).toList(), + ), + strutStyle: _strutStyle, + ); + }, + ); + } + + Size _textSize(String text) { + final paragraph = RenderParagraph( + TextSpan(text: text, style: _textStyle), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + strutStyle: _strutStyle, + )..layout(const BoxConstraints(), parentUsesSize: true); + final width = paragraph.getMaxIntrinsicWidth(double.infinity); + final height = paragraph.getMaxIntrinsicHeight(double.infinity); + paragraph.dispose(); + return Size(width, height); + } + + // use an adaptation of Google's `Diff Match and Patch` + // as package `diffutil_dart` (as of v3.0.0) is unreliable + void _computeDiff(String oldText, String newText) { + final oldCharacters = oldText.characters.join(); + final newCharacters = newText.characters.join(); + + final dmp = DiffMatchPatch(); + final d = dmp.diff_main(oldCharacters, newCharacters); + dmp.diff_cleanupSemantic(d); + + _diffs + ..clear() + ..addAll(d.map((diff) { + final text = diff.text; + final size = _textSize(text); + return switch (diff.operation) { + Operation.delete => (text, null, size, Size.zero), + Operation.insert => (null, text, Size.zero, size), + Operation.equal || _ => (text, text, size, size), + }; + }).fold<List<_TextDiff>>([], (prev, v) { + if (prev.isNotEmpty) { + final last = prev.last; + final prevNewText = last.$2; + if (prevNewText == null) { + // previous diff is a deletion + final thisOldText = v.$1; + if (thisOldText == null) { + // this diff is an insertion + // merge deletion and insertion as a change operation + final change = (last.$1, v.$2, last.$3, v.$4); + return [...prev.take(prev.length - 1), change]; + } + } + } + return [...prev, v]; + })); + } +} + +typedef _TextDiff = (String?, String?, Size, Size); diff --git a/lib/widgets/common/basic/text/background_painter.dart b/lib/widgets/common/basic/text/background_painter.dart new file mode 100644 index 0000000..e3757c1 --- /dev/null +++ b/lib/widgets/common/basic/text/background_painter.dart @@ -0,0 +1,77 @@ +import 'dart:ui' as ui; + +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +// as of Flutter v3.3.7, text style background does not have consistent height +// when rendering multi-script text, so we paint the background behind via a stack instead +class TextBackgroundPainter extends StatelessWidget { + final List<TextSpan> spans; + final TextStyle style; + final TextAlign textAlign; + final Widget child; + + const TextBackgroundPainter({ + super.key, + required this.spans, + required this.style, + required this.textAlign, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final backgroundColor = style.backgroundColor; + if (backgroundColor == null || backgroundColor.a == 0) { + return child; + } + + return LayoutBuilder( + builder: (context, constraints) { + final paragraph = RenderParagraph( + TextSpan( + children: spans, + style: style, + ), + textAlign: textAlign, + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + )..layout(constraints, parentUsesSize: true); + + final textLength = spans.map((v) => v.text?.length ?? 0).sum; + final allBoxes = paragraph.getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: textLength), + boxHeightStyle: ui.BoxHeightStyle.max, + ); + paragraph.dispose(); + + // merge boxes to avoid artifacts at box edges, from anti-aliasing and rounding hacks + final lineRects = groupBy<TextBox, double>(allBoxes, (v) => v.top).entries.map((kv) { + final top = kv.key; + final lineBoxes = kv.value; + return Rect.fromLTRB( + lineBoxes.map((v) => v.left).min, + top, + lineBoxes.map((v) => v.right).max, + lineBoxes.first.bottom, + ); + }); + + return Stack( + children: [ + ...lineRects.map((rect) { + return Positioned.fromRect( + rect: rect, + child: ColoredBox( + color: backgroundColor, + ), + ); + }), + child, + ], + ); + }, + ); + } +} diff --git a/lib/widgets/common/basic/text/change_highlight.dart b/lib/widgets/common/basic/text/change_highlight.dart new file mode 100644 index 0000000..cea4737 --- /dev/null +++ b/lib/widgets/common/basic/text/change_highlight.dart @@ -0,0 +1,89 @@ +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class ChangeHighlightText extends StatefulWidget { + final String data; + final TextStyle style, changedStyle; + final Curve curve; + final Duration duration; + + const ChangeHighlightText( + this.data, { + super.key, + required this.style, + required this.changedStyle, + this.curve = Curves.linear, + required this.duration, + }); + + @override + State<ChangeHighlightText> createState() => _ChangeHighlightTextState(); +} + +class _ChangeHighlightTextState extends State<ChangeHighlightText> with SingleTickerProviderStateMixin { + late final AnimationController _controller; + late final CurvedAnimation _animation; + late final Animation<TextStyle> _style; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + duration: widget.duration, + vsync: this, + ) + ..value = 1 + ..addListener(() => setState(() {})); + _animation = CurvedAnimation( + parent: _controller, + curve: widget.curve, + ); + _style = ShadowedTextStyleTween(begin: widget.changedStyle, end: widget.style).animate(_animation); + } + + @override + void didUpdateWidget(ChangeHighlightText oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.data != widget.data) { + _controller + ..value = 0 + ..forward(); + } + } + + @override + void dispose() { + _animation.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Text( + widget.data, + style: _style.value, + ); + } +} + +class ShadowedTextStyleTween extends Tween<TextStyle> { + ShadowedTextStyleTween({super.begin, super.end}); + + @override + TextStyle lerp(double t) { + final textStyle = TextStyle.lerp(begin, end, t)!; + final beginShadows = begin!.shadows; + final endShadows = end!.shadows; + if (beginShadows != null && endShadows != null && beginShadows.length == endShadows.length) { + return textStyle.copyWith( + shadows: beginShadows.mapIndexed((i, a) { + final b = endShadows[i]; + return Shadow.lerp(a, b, t)!; + }).toList(), + ); + } else { + return textStyle; + } + } +} diff --git a/lib/widgets/common/basic/text/outlined.dart b/lib/widgets/common/basic/text/outlined.dart new file mode 100644 index 0000000..3ccf145 --- /dev/null +++ b/lib/widgets/common/basic/text/outlined.dart @@ -0,0 +1,102 @@ +import 'dart:ui'; + +import 'package:flutter/material.dart'; + +class OutlinedText extends StatelessWidget { + final List<TextSpan> textSpans; + final double outlineWidth; + final Color outlineColor; + final double outlineBlurSigma; + final TextAlign? textAlign; + final bool? softWrap; + final TextOverflow? overflow; + final int? maxLines; + + static const widgetSpanAlignment = PlaceholderAlignment.middle; + + const OutlinedText({ + super.key, + required this.textSpans, + double? outlineWidth, + Color? outlineColor, + double? outlineBlurSigma, + this.textAlign, + this.softWrap, + this.overflow, + this.maxLines, + }) : outlineWidth = outlineWidth ?? 1, + outlineColor = outlineColor ?? Colors.black, + outlineBlurSigma = outlineBlurSigma ?? 0; + + @override + Widget build(BuildContext context) { + // TODO TLAD [subtitles] fix background area for mixed alphabetic-ideographic text + // as of Flutter v3.10.0, the area computed for `backgroundColor` has inconsistent height + // in case of mixed alphabetic-ideographic text. The painted boxes depend on the script. + // Possible workarounds would be to use metrics from: + // - `TextPainter.getBoxesForSelection` + // - `Paragraph.getBoxesForRange` + // and paint the background at the bottom of the `Stack` + + final hasOutline = outlineWidth > 0; + + Widget? outline; + if (hasOutline) { + outline = Text.rich( + TextSpan( + children: textSpans.map(_toStrokeSpan).toList(), + ), + textAlign: textAlign, + softWrap: softWrap, + overflow: overflow, + maxLines: maxLines, + ); + if (outlineBlurSigma > 0) { + outline = ImageFiltered( + imageFilter: ImageFilter.blur( + sigmaX: outlineBlurSigma, + sigmaY: outlineBlurSigma, + ), + child: outline, + ); + } + } + + final fill = Text.rich( + TextSpan( + children: hasOutline ? textSpans.map(_toFillSpan).toList() : textSpans, + ), + textAlign: textAlign, + softWrap: softWrap, + overflow: overflow, + maxLines: maxLines, + ); + + return Stack( + children: [ + if (outline != null) outline, + fill, + ], + ); + } + + TextSpan _toStrokeSpan(TextSpan span) => TextSpan( + text: span.text, + children: span.children, + style: (span.style ?? const TextStyle()).copyWith( + foreground: Paint() + ..style = PaintingStyle.stroke + ..color = outlineColor + ..strokeWidth = outlineWidth, + ), + ); + + TextSpan _toFillSpan(TextSpan span) => TextSpan( + text: span.text, + children: span.children, + style: (span.style ?? const TextStyle()).copyWith( + backgroundColor: Colors.transparent, + shadows: [], + ), + ); +} diff --git a/lib/widgets/common/basic/text_dropdown_button.dart b/lib/widgets/common/basic/text_dropdown_button.dart new file mode 100644 index 0000000..e282446 --- /dev/null +++ b/lib/widgets/common/basic/text_dropdown_button.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; + +class TextDropdownButton<T> extends StatefulWidget { + final List<T> values; + final String Function(T value) valueText; + final IconData Function(T value)? valueIcon; + final T? value; + final Widget? underline; + final bool isExpanded; + final double? itemHeight; + final Color? dropdownColor; + final ValueChanged<T?>? onChanged; + + const TextDropdownButton({ + super.key, + required this.values, + required this.valueText, + this.valueIcon, + this.value, + this.underline, + this.isExpanded = false, + this.itemHeight = kMinInteractiveDimension, + this.dropdownColor, + required this.onChanged, + }); + + @override + State<TextDropdownButton<T>> createState() => _TextDropdownButtonState<T>(); +} + +class _TextDropdownButtonState<T> extends State<TextDropdownButton<T>> { + @override + Widget build(BuildContext context) { + return DropdownButton( + items: widget.values + .map((v) => DropdownMenuItem<T>( + value: v, + child: _buildItem(widget.valueText(v), widget.valueIcon?.call(v), selected: false), + )) + .toList(), + selectedItemBuilder: (context) => widget.values + .map((v) => DropdownMenuItem<T>( + value: v, + child: _buildItem(widget.valueText(v), widget.valueIcon?.call(v), selected: true), + )) + .toList(), + value: widget.value, + style: Theme.of(context).textTheme.titleMedium!.copyWith(fontWeight: FontWeight.normal), + underline: widget.underline, + isExpanded: widget.isExpanded, + itemHeight: widget.itemHeight, + dropdownColor: widget.dropdownColor, + onChanged: widget.onChanged, + ); + } + + static Widget _buildItem<T>(String text, IconData? icon, {required bool selected}) { + final softWrap = selected ? false : null; + final overflow = selected ? TextOverflow.fade : null; + + Widget child = icon != null + ? Text.rich( + TextSpan( + children: [ + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: 8, bottom: 2), + child: Icon(icon), + ), + ), + TextSpan(text: text), + ], + ), + softWrap: softWrap, + overflow: overflow, + ) + : Text( + text, + softWrap: softWrap, + overflow: overflow, + ); + + if (selected) { + child = Align( + alignment: AlignmentDirectional.centerStart, + child: child, + ); + } + + return child; + } +} diff --git a/lib/widgets/common/basic/time_shift_selector.dart b/lib/widgets/common/basic/time_shift_selector.dart new file mode 100644 index 0000000..da0aafc --- /dev/null +++ b/lib/widgets/common/basic/time_shift_selector.dart @@ -0,0 +1,152 @@ +import 'package:aves/ref/locales.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/common/basic/wheel.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class TimeShiftSelector extends StatefulWidget { + final TimeShiftController controller; + + const TimeShiftSelector({ + super.key, + required this.controller, + }); + + @override + State<TimeShiftSelector> createState() => _TimeShiftSelectorState(); +} + +class _TimeShiftSelectorState extends State<TimeShiftSelector> { + late ValueNotifier<int> _shiftHour, _shiftMinute, _shiftSecond; + late ValueNotifier<String> _shiftSign; + + static const _positiveSign = '+'; + static const _negativeSign = '-'; + + @override + void initState() { + super.initState(); + + var initialValue = widget.controller.initialValue; + final sign = initialValue.isNegative ? _negativeSign : _positiveSign; + initialValue = initialValue.abs(); + final hours = initialValue.inHours; + initialValue -= Duration(hours: hours); + final minutes = initialValue.inMinutes; + initialValue -= Duration(minutes: minutes); + final seconds = initialValue.inSeconds; + + _shiftSign = ValueNotifier(sign); + _shiftHour = ValueNotifier(hours); + _shiftMinute = ValueNotifier(minutes); + _shiftSecond = ValueNotifier(seconds); + + _shiftSign.addListener(_updateValue); + _shiftHour.addListener(_updateValue); + _shiftMinute.addListener(_updateValue); + _shiftSecond.addListener(_updateValue); + } + + @override + void dispose() { + _shiftSign.dispose(); + _shiftHour.dispose(); + _shiftMinute.dispose(); + _shiftSecond.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final timeComponentFormatter = NumberFormat('0', context.locale); + + const textStyle = TextStyle(fontSize: 34); + const digitsAlign = TextAlign.right; + + return Center( + child: Table( + textDirection: timeComponentsDirection, + children: [ + TableRow( + children: [ + const SizedBox(), + Center(child: Text(l10n.durationDialogHours)), + const SizedBox(width: 16), + Center(child: Text(l10n.durationDialogMinutes)), + const SizedBox(width: 16), + Center(child: Text(l10n.durationDialogSeconds)), + ], + ), + TableRow( + children: [ + WheelSelector( + valueNotifier: _shiftSign, + values: const [_positiveSign, _negativeSign], + textStyle: textStyle, + textAlign: TextAlign.center, + format: (v) => v, + ), + Align( + alignment: Alignment.centerRight, + child: WheelSelector( + valueNotifier: _shiftHour, + values: List.generate(hoursInDay, (i) => i), + textStyle: textStyle, + textAlign: digitsAlign, + format: timeComponentFormatter.format, + ), + ), + const Text( + ':', + style: textStyle, + ), + Align( + alignment: Alignment.centerLeft, + child: WheelSelector( + valueNotifier: _shiftMinute, + values: List.generate(minutesInHour, (i) => i), + textStyle: textStyle, + textAlign: digitsAlign, + format: timeComponentFormatter.format, + ), + ), + const Text( + ':', + style: textStyle, + ), + Align( + alignment: Alignment.centerLeft, + child: WheelSelector( + valueNotifier: _shiftSecond, + values: List.generate(secondsInMinute, (i) => i), + textStyle: textStyle, + textAlign: digitsAlign, + format: timeComponentFormatter.format, + ), + ), + ], + ) + ], + defaultColumnWidth: const IntrinsicColumnWidth(), + defaultVerticalAlignment: TableCellVerticalAlignment.middle, + ), + ); + } + + void _updateValue() { + final sign = _shiftSign.value == _positiveSign ? 1 : -1; + final hours = _shiftHour.value; + final minutes = _shiftMinute.value; + final seconds = _shiftSecond.value; + widget.controller.value = Duration(hours: hours, minutes: minutes, seconds: seconds) * sign; + } +} + +class TimeShiftController { + final Duration initialValue; + Duration value; + + TimeShiftController({required this.initialValue}) : value = initialValue; +} diff --git a/lib/widgets/common/basic/tv_edge_focus.dart b/lib/widgets/common/basic/tv_edge_focus.dart new file mode 100644 index 0000000..190d047 --- /dev/null +++ b/lib/widgets/common/basic/tv_edge_focus.dart @@ -0,0 +1,25 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +// to be placed at the edges of lists and grids, +// so that TV can reach them with D-pad +class TvEdgeFocus extends StatelessWidget { + final FocusNode? focusNode; + + const TvEdgeFocus({ + super.key, + this.focusNode, + }); + + @override + Widget build(BuildContext context) { + final useTvLayout = context.select<Settings, bool>((v) => v.useTvLayout); + return useTvLayout + ? Focus( + focusNode: focusNode, + child: const SizedBox(), + ) + : const SizedBox(); + } +} diff --git a/lib/widgets/common/basic/wheel.dart b/lib/widgets/common/basic/wheel.dart new file mode 100644 index 0000000..a5c6dff --- /dev/null +++ b/lib/widgets/common/basic/wheel.dart @@ -0,0 +1,172 @@ +import 'package:aves/theme/durations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +class WheelSelector<T> extends StatefulWidget { + final ValueNotifier<T> valueNotifier; + final List<T> values; + final TextStyle textStyle; + final TextAlign textAlign; + final String Function(T v) format; + + const WheelSelector({ + super.key, + required this.valueNotifier, + required this.values, + required this.textStyle, + required this.textAlign, + required this.format, + }); + + @override + State<WheelSelector<T>> createState() => _WheelSelectorState<T>(); +} + +class _WheelSelectorState<T> extends State<WheelSelector<T>> { + late final FixedExtentScrollController _controller; + final ValueNotifier<bool> _focusedNotifier = ValueNotifier(false); + + ValueNotifier<T> get valueNotifier => widget.valueNotifier; + + List<T> get values => widget.values; + + @override + void initState() { + super.initState(); + _controller = FixedExtentScrollController( + initialItem: values.indexOf(valueNotifier.value), + ); + } + + @override + void dispose() { + _controller.dispose(); + _focusedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + const background = Colors.transparent; + final foreground = DefaultTextStyle.of(context).style.color!; + final transitionDuration = context.select<DurationsData, Duration>((v) => v.formTransition); + final itemSize = Size.square(textScaler.scale(40)); + + return FocusableActionDetector( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowUp): _AdjustValueIntent.up(), + SingleActivator(LogicalKeyboardKey.arrowDown): _AdjustValueIntent.down(), + }, + actions: { + _AdjustValueIntent: CallbackAction<_AdjustValueIntent>(onInvoke: _onAdjustValueIntent), + }, + onShowFocusHighlight: (v) => _focusedNotifier.value = v, + child: NotificationListener<ScrollNotification>( + // cancel notification bubbling so that the dialog scroll bar + // does not misinterpret wheel scrolling for dialog content scrolling + onNotification: (notification) => true, + child: Padding( + padding: const EdgeInsets.all(8), + child: Stack( + children: [ + Positioned.fill( + child: Center( + child: ValueListenableBuilder<bool>( + valueListenable: _focusedNotifier, + builder: (context, focused, child) { + return AnimatedContainer( + width: itemSize.width, + height: itemSize.height, + duration: transitionDuration, + decoration: BoxDecoration( + color: foreground.withValues(alpha: focused ? .2 : 0), + borderRadius: const BorderRadius.all(Radius.circular(8)), + ), + ); + }), + ), + ), + SizedBox( + width: itemSize.width, + height: itemSize.height * 3, + child: ShaderMask( + shaderCallback: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + background, + foreground, + foreground, + background, + ], + ).createShader, + child: Theme( + data: Theme.of(context).copyWith( + scrollbarTheme: ScrollbarThemeData( + thumbVisibility: WidgetStateProperty.all(false), + ), + ), + child: ListWheelScrollView( + controller: _controller, + physics: const FixedExtentScrollPhysics(parent: BouncingScrollPhysics()), + diameterRatio: 1.2, + itemExtent: itemSize.height, + squeeze: 1.3, + onSelectedItemChanged: (i) => valueNotifier.value = values[i], + children: values + .map((i) => SizedBox.fromSize( + size: itemSize, + child: Text( + widget.format(i), + textAlign: widget.textAlign, + style: widget.textStyle, + ), + )) + .toList(), + ), + ), + ), + ), + ], + ), + ), + ), + ); + } + + void _onAdjustValueIntent(_AdjustValueIntent intent) { + late int delta; + switch (intent.type) { + case _ValueAdjustmentType.up: + delta = -1; + case _ValueAdjustmentType.down: + delta = 1; + } + final targetItem = _controller.selectedItem + delta; + final duration = context.read<DurationsData>().formTransition; + if (duration > Duration.zero) { + _controller.animateToItem(targetItem, duration: duration, curve: Curves.easeInOutCubic); + } else { + _controller.jumpToItem(targetItem); + } + } +} + +class _AdjustValueIntent extends Intent { + const _AdjustValueIntent({ + required this.type, + }); + + const _AdjustValueIntent.up() : type = _ValueAdjustmentType.up; + + const _AdjustValueIntent.down() : type = _ValueAdjustmentType.down; + + final _ValueAdjustmentType type; +} + +enum _ValueAdjustmentType { + up, + down, +} diff --git a/lib/widgets/common/behaviour/eager_scale_gesture_recognizer.dart b/lib/widgets/common/behaviour/eager_scale_gesture_recognizer.dart new file mode 100644 index 0000000..aeba82b --- /dev/null +++ b/lib/widgets/common/behaviour/eager_scale_gesture_recognizer.dart @@ -0,0 +1,580 @@ +// ignore_for_file: depend_on_referenced_packages +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; + +// adapted from Flutter `ScaleGestureRecognizer` in `/gestures/scale.dart` +// ignore_for_file: avoid_types_on_closure_parameters, unnecessary_null_comparison + +/// The possible states of a [ScaleGestureRecognizer]. +enum _ScaleState { + /// The recognizer is ready to start recognizing a gesture. + ready, + + /// The sequence of pointer events seen thus far is consistent with a scale + /// gesture but the gesture has not been accepted definitively. + possible, + + /// The sequence of pointer events seen thus far has been accepted + /// definitively as a scale gesture. + accepted, + + /// The sequence of pointer events seen thus far has been accepted + /// definitively as a scale gesture and the pointers established a focal point + /// and initial scale. + started, +} + +class _PointerPanZoomData { + _PointerPanZoomData.fromStartEvent(this.parent, PointerPanZoomStartEvent event) + : _position = event.position, + _pan = Offset.zero, + _scale = 1, + _rotation = 0; + + _PointerPanZoomData.fromUpdateEvent(this.parent, PointerPanZoomUpdateEvent event) + : _position = event.position, + _pan = event.pan, + _scale = event.scale, + _rotation = event.rotation; + + final EagerScaleGestureRecognizer parent; + final Offset _position; + final Offset _pan; + final double _scale; + final double _rotation; + + Offset get focalPoint { + if (parent.trackpadScrollCausesScale) { + return _position; + } + return _position + _pan; + } + + double get scale { + if (parent.trackpadScrollCausesScale) { + return _scale * math.exp((_pan.dx * parent.trackpadScrollToScaleFactor.dx) + (_pan.dy * parent.trackpadScrollToScaleFactor.dy)); + } + return _scale; + } + + double get rotation => _rotation; + + @override + String toString() => '_PointerPanZoomData(parent: $parent, _position: $_position, _pan: $_pan, _scale: $_scale, _rotation: $_rotation)'; +} + +//////////////////////////////////////////////////////////////////////////////// + +bool _isFlingGesture(Velocity velocity) { + final double speedSquared = velocity.pixelsPerSecond.distanceSquared; + return speedSquared > kMinFlingVelocity * kMinFlingVelocity; +} + +/// Defines a line between two pointers on screen. +/// +/// [_LineBetweenPointers] is an abstraction of a line between two pointers in +/// contact with the screen. Used to track the rotation of a scale gesture. +class _LineBetweenPointers { + /// Creates a [_LineBetweenPointers]. None of the [pointerStartLocation], [pointerStartId] + /// [pointerEndLocation] and [pointerEndId] must be null. [pointerStartId] and [pointerEndId] + /// should be different. + _LineBetweenPointers({ + this.pointerStartLocation = Offset.zero, + this.pointerStartId = 0, + this.pointerEndLocation = Offset.zero, + this.pointerEndId = 1, + }) : assert(pointerStartId != pointerEndId); + + // The location and the id of the pointer that marks the start of the line. + final Offset pointerStartLocation; + final int pointerStartId; + + // The location and the id of the pointer that marks the end of the line. + final Offset pointerEndLocation; + final int pointerEndId; +} + +/// Recognizes a scale gesture. +/// +/// [ScaleGestureRecognizer] tracks the pointers in contact with the screen and +/// calculates their focal point, indicated scale, and rotation. When a focal +/// point is established, the recognizer calls [onStart]. As the focal point, +/// scale, and rotation change, the recognizer calls [onUpdate]. When the +/// pointers are no longer in contact with the screen, the recognizer calls +/// [onEnd]. +class EagerScaleGestureRecognizer extends OneSequenceGestureRecognizer { + /// Create a gesture recognizer for interactions intended for scaling content. + /// + /// {@macro flutter.gestures.GestureRecognizer.supportedDevices} + EagerScaleGestureRecognizer({ + super.debugOwner, + super.supportedDevices, + super.allowedButtonsFilter, + this.dragStartBehavior = DragStartBehavior.down, + this.trackpadScrollCausesScale = false, + this.trackpadScrollToScaleFactor = kDefaultTrackpadScrollToScaleFactor, + }); + + /// Determines what point is used as the starting point in all calculations + /// involving this gesture. + /// + /// When set to [DragStartBehavior.down], the scale is calculated starting + /// from the position where the pointer first contacted the screen. + /// + /// When set to [DragStartBehavior.start], the scale is calculated starting + /// from the position where the scale gesture began. The scale gesture may + /// begin after the time that the pointer first contacted the screen if there + /// are multiple listeners competing for the gesture. In that case, the + /// gesture arena waits to determine whether or not the gesture is a scale + /// gesture before giving the gesture to this GestureRecognizer. This happens + /// in the case of nested GestureDetectors, for example. + /// + /// Defaults to [DragStartBehavior.down]. + /// + /// See also: + /// + /// * https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation, + /// which provides more information about the gesture arena. + DragStartBehavior dragStartBehavior; + + /// The pointers in contact with the screen have established a focal point and + /// initial scale of 1.0. + /// + /// This won't be called until the gesture arena has determined that this + /// GestureRecognizer has won the gesture. + /// + /// See also: + /// + /// * https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation, + /// which provides more information about the gesture arena. + GestureScaleStartCallback? onStart; + + /// The pointers in contact with the screen have indicated a new focal point + /// and/or scale. + GestureScaleUpdateCallback? onUpdate; + + /// The pointers are no longer in contact with the screen. + GestureScaleEndCallback? onEnd; + + _ScaleState _state = _ScaleState.ready; + + Matrix4? _lastTransform; + + /// {@template flutter.gestures.scale.trackpadScrollCausesScale} + /// Whether scrolling up/down on a trackpad should cause scaling instead of + /// panning. + /// + /// Defaults to false. + /// {@endtemplate} + bool trackpadScrollCausesScale; + + /// {@template flutter.gestures.scale.trackpadScrollToScaleFactor} + /// A factor to control the direction and magnitude of scale when converting + /// trackpad scrolling. + /// + /// Incoming trackpad pan offsets will be divided by this factor to get scale + /// values. Increasing this offset will reduce the amount of scaling caused by + /// a fixed amount of trackpad scrolling. + /// + /// Defaults to [kDefaultTrackpadScrollToScaleFactor]. + /// {@endtemplate} + Offset trackpadScrollToScaleFactor; + + /// The number of pointers being tracked by the gesture recognizer. + /// + /// Typically this is the number of fingers being used to pan the widget using the gesture + /// recognizer. + int get pointerCount { + return _pointerPanZooms.length + _pointerQueue.length; + } + + late Offset _initialFocalPoint; + Offset? _currentFocalPoint; + late double _initialSpan; + late double _currentSpan; + late double _initialHorizontalSpan; + late double _currentHorizontalSpan; + late double _initialVerticalSpan; + late double _currentVerticalSpan; + late Offset _localFocalPoint; + _LineBetweenPointers? _initialLine; + _LineBetweenPointers? _currentLine; + final Map<int, Offset> _pointerLocations = <int, Offset>{}; + final List<int> _pointerQueue = <int>[]; // A queue to sort pointers in order of entrance + final Map<int, VelocityTracker> _velocityTrackers = <int, VelocityTracker>{}; + VelocityTracker? _scaleVelocityTracker; + late Offset _delta; + final Map<int, _PointerPanZoomData> _pointerPanZooms = <int, _PointerPanZoomData>{}; + double _initialPanZoomScaleFactor = 1; + double _initialPanZoomRotationFactor = 0; + + double get _pointerScaleFactor => _initialSpan > 0.0 ? _currentSpan / _initialSpan : 1.0; + + double get _pointerHorizontalScaleFactor => _initialHorizontalSpan > 0.0 ? _currentHorizontalSpan / _initialHorizontalSpan : 1.0; + + double get _pointerVerticalScaleFactor => _initialVerticalSpan > 0.0 ? _currentVerticalSpan / _initialVerticalSpan : 1.0; + + double get _scaleFactor { + double scale = _pointerScaleFactor; + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + scale *= p.scale / _initialPanZoomScaleFactor; + } + return scale; + } + + double get _horizontalScaleFactor { + double scale = _pointerHorizontalScaleFactor; + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + scale *= p.scale / _initialPanZoomScaleFactor; + } + return scale; + } + + double get _verticalScaleFactor { + double scale = _pointerVerticalScaleFactor; + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + scale *= p.scale / _initialPanZoomScaleFactor; + } + return scale; + } + + double _computeRotationFactor() { + double factor = 0.0; + if (_initialLine != null && _currentLine != null) { + final double fx = _initialLine!.pointerStartLocation.dx; + final double fy = _initialLine!.pointerStartLocation.dy; + final double sx = _initialLine!.pointerEndLocation.dx; + final double sy = _initialLine!.pointerEndLocation.dy; + + final double nfx = _currentLine!.pointerStartLocation.dx; + final double nfy = _currentLine!.pointerStartLocation.dy; + final double nsx = _currentLine!.pointerEndLocation.dx; + final double nsy = _currentLine!.pointerEndLocation.dy; + + final double angle1 = math.atan2(fy - sy, fx - sx); + final double angle2 = math.atan2(nfy - nsy, nfx - nsx); + + factor = angle2 - angle1; + } + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + factor += p.rotation; + } + factor -= _initialPanZoomRotationFactor; + return factor; + } + + @override + void addAllowedPointer(PointerDownEvent event) { + super.addAllowedPointer(event); + _velocityTrackers[event.pointer] = VelocityTracker.withKind(event.kind); + if (_state == _ScaleState.ready) { + _state = _ScaleState.possible; + _initialSpan = 0.0; + _currentSpan = 0.0; + _initialHorizontalSpan = 0.0; + _currentHorizontalSpan = 0.0; + _initialVerticalSpan = 0.0; + _currentVerticalSpan = 0.0; + } + } + + @override + bool isPointerPanZoomAllowed(PointerPanZoomStartEvent event) => true; + + @override + void addAllowedPointerPanZoom(PointerPanZoomStartEvent event) { + super.addAllowedPointerPanZoom(event); + startTrackingPointer(event.pointer, event.transform); + _velocityTrackers[event.pointer] = VelocityTracker.withKind(event.kind); + if (_state == _ScaleState.ready) { + _state = _ScaleState.possible; + _initialPanZoomScaleFactor = 1.0; + _initialPanZoomRotationFactor = 0.0; + } + } + + @override + void handleEvent(PointerEvent event) { + assert(_state != _ScaleState.ready); + bool didChangeConfiguration = false; + bool shouldStartIfAccepted = false; + if (event is PointerMoveEvent) { + final VelocityTracker tracker = _velocityTrackers[event.pointer]!; + if (!event.synthesized) { + tracker.addPosition(event.timeStamp, event.position); + } + _pointerLocations[event.pointer] = event.position; + shouldStartIfAccepted = true; + _lastTransform = event.transform; + } else if (event is PointerDownEvent) { + _pointerLocations[event.pointer] = event.position; + _pointerQueue.add(event.pointer); + didChangeConfiguration = true; + shouldStartIfAccepted = true; + _lastTransform = event.transform; + } else if (event is PointerUpEvent || event is PointerCancelEvent) { + _pointerLocations.remove(event.pointer); + _pointerQueue.remove(event.pointer); + didChangeConfiguration = true; + _lastTransform = event.transform; + } else if (event is PointerPanZoomStartEvent) { + assert(_pointerPanZooms[event.pointer] == null); + _pointerPanZooms[event.pointer] = _PointerPanZoomData.fromStartEvent(this, event); + didChangeConfiguration = true; + shouldStartIfAccepted = true; + _lastTransform = event.transform; + } else if (event is PointerPanZoomUpdateEvent) { + assert(_pointerPanZooms[event.pointer] != null); + if (!event.synthesized && !trackpadScrollCausesScale) { + _velocityTrackers[event.pointer]!.addPosition(event.timeStamp, event.pan); + } + _pointerPanZooms[event.pointer] = _PointerPanZoomData.fromUpdateEvent(this, event); + _lastTransform = event.transform; + shouldStartIfAccepted = true; + } else if (event is PointerPanZoomEndEvent) { + assert(_pointerPanZooms[event.pointer] != null); + _pointerPanZooms.remove(event.pointer); + didChangeConfiguration = true; + } + + _updateLines(); + _update(); + + if (!didChangeConfiguration || _reconfigure(event.pointer)) { + _advanceStateMachine(shouldStartIfAccepted, event); + } + stopTrackingIfPointerNoLongerDown(event); + } + + void _update() { + final Offset? previousFocalPoint = _currentFocalPoint; + + // Compute the focal point + Offset focalPoint = Offset.zero; + for (final int pointer in _pointerLocations.keys) { + focalPoint += _pointerLocations[pointer]!; + } + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + focalPoint += p.focalPoint; + } + _currentFocalPoint = pointerCount > 0 ? focalPoint / pointerCount.toDouble() : Offset.zero; + + if (previousFocalPoint == null) { + _localFocalPoint = PointerEvent.transformPosition( + _lastTransform, + _currentFocalPoint!, + ); + _delta = Offset.zero; + } else { + final Offset localPreviousFocalPoint = _localFocalPoint; + _localFocalPoint = PointerEvent.transformPosition( + _lastTransform, + _currentFocalPoint!, + ); + _delta = _localFocalPoint - localPreviousFocalPoint; + } + + final int count = _pointerLocations.keys.length; + + Offset pointerFocalPoint = Offset.zero; + for (final int pointer in _pointerLocations.keys) { + pointerFocalPoint += _pointerLocations[pointer]!; + } + if (count > 0) { + pointerFocalPoint = pointerFocalPoint / count.toDouble(); + } + + // Span is the average deviation from focal point. Horizontal and vertical + // spans are the average deviations from the focal point's horizontal and + // vertical coordinates, respectively. + double totalDeviation = 0.0; + double totalHorizontalDeviation = 0.0; + double totalVerticalDeviation = 0.0; + for (final int pointer in _pointerLocations.keys) { + totalDeviation += (pointerFocalPoint - _pointerLocations[pointer]!).distance; + totalHorizontalDeviation += (pointerFocalPoint.dx - _pointerLocations[pointer]!.dx).abs(); + totalVerticalDeviation += (pointerFocalPoint.dy - _pointerLocations[pointer]!.dy).abs(); + } + _currentSpan = count > 0 ? totalDeviation / count : 0.0; + _currentHorizontalSpan = count > 0 ? totalHorizontalDeviation / count : 0.0; + _currentVerticalSpan = count > 0 ? totalVerticalDeviation / count : 0.0; + } + + /// Updates [_initialLine] and [_currentLine] accordingly to the situation of + /// the registered pointers. + void _updateLines() { + final int count = _pointerLocations.keys.length; + assert(_pointerQueue.length >= count); + + /// In case of just one pointer registered, reconfigure [_initialLine] + if (count < 2) { + _initialLine = _currentLine; + } else if (_initialLine != null && _initialLine!.pointerStartId == _pointerQueue[0] && _initialLine!.pointerEndId == _pointerQueue[1]) { + /// Rotation updated, set the [_currentLine] + _currentLine = _LineBetweenPointers( + pointerStartId: _pointerQueue[0], + pointerStartLocation: _pointerLocations[_pointerQueue[0]]!, + pointerEndId: _pointerQueue[1], + pointerEndLocation: _pointerLocations[_pointerQueue[1]]!, + ); + } else { + /// A new rotation process is on the way, set the [_initialLine] + _initialLine = _LineBetweenPointers( + pointerStartId: _pointerQueue[0], + pointerStartLocation: _pointerLocations[_pointerQueue[0]]!, + pointerEndId: _pointerQueue[1], + pointerEndLocation: _pointerLocations[_pointerQueue[1]]!, + ); + _currentLine = _initialLine; + } + } + + bool _reconfigure(int pointer) { + _initialFocalPoint = _currentFocalPoint!; + _initialSpan = _currentSpan; + _initialLine = _currentLine; + _initialHorizontalSpan = _currentHorizontalSpan; + _initialVerticalSpan = _currentVerticalSpan; + if (_pointerPanZooms.isEmpty) { + _initialPanZoomScaleFactor = 1.0; + _initialPanZoomRotationFactor = 0.0; + } else { + _initialPanZoomScaleFactor = _scaleFactor / _pointerScaleFactor; + _initialPanZoomRotationFactor = _pointerPanZooms.values.map((_PointerPanZoomData x) => x.rotation).reduce((double a, double b) => a + b); + } + if (_state == _ScaleState.started) { + if (onEnd != null) { + final VelocityTracker tracker = _velocityTrackers[pointer]!; + + Velocity velocity = tracker.getVelocity(); + if (_isFlingGesture(velocity)) { + final Offset pixelsPerSecond = velocity.pixelsPerSecond; + if (pixelsPerSecond.distanceSquared > kMaxFlingVelocity * kMaxFlingVelocity) { + velocity = Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * kMaxFlingVelocity); + } + invokeCallback<void>('onEnd', () => onEnd!(ScaleEndDetails(velocity: velocity, scaleVelocity: _scaleVelocityTracker?.getVelocity().pixelsPerSecond.dx ?? -1, pointerCount: pointerCount))); + } else { + invokeCallback<void>('onEnd', () => onEnd!(ScaleEndDetails(scaleVelocity: _scaleVelocityTracker?.getVelocity().pixelsPerSecond.dx ?? -1, pointerCount: pointerCount))); + } + } + _state = _ScaleState.accepted; + _scaleVelocityTracker = VelocityTracker.withKind(PointerDeviceKind.touch); // arbitrary PointerDeviceKind + return false; + } + _scaleVelocityTracker = VelocityTracker.withKind(PointerDeviceKind.touch); // arbitrary PointerDeviceKind + return true; + } + + void _advanceStateMachine(bool shouldStartIfAccepted, PointerEvent event) { + if (_state == _ScaleState.ready) { + _state = _ScaleState.possible; + } + + // TLAD insert start + if (_pointerQueue.length == 2) { + resolve(GestureDisposition.accepted); + } + // TLAD insert end + + if (_state == _ScaleState.possible) { + final double spanDelta = (_currentSpan - _initialSpan).abs(); + final double focalPointDelta = (_currentFocalPoint! - _initialFocalPoint).distance; + if (spanDelta > computeScaleSlop(event.kind) || focalPointDelta > computePanSlop(event.kind, gestureSettings) || math.max(_scaleFactor / _pointerScaleFactor, _pointerScaleFactor / _scaleFactor) > 1.05) { + resolve(GestureDisposition.accepted); + } + } else if (_state.index >= _ScaleState.accepted.index) { + resolve(GestureDisposition.accepted); + } + + if (_state == _ScaleState.accepted && shouldStartIfAccepted) { + _state = _ScaleState.started; + _dispatchOnStartCallbackIfNeeded(); + } + + if (_state == _ScaleState.started) { + _scaleVelocityTracker?.addPosition(event.timeStamp, Offset(_scaleFactor, 0)); + if (onUpdate != null) { + invokeCallback<void>('onUpdate', () { + onUpdate!(ScaleUpdateDetails( + scale: _scaleFactor, + horizontalScale: _horizontalScaleFactor, + verticalScale: _verticalScaleFactor, + focalPoint: _currentFocalPoint!, + localFocalPoint: _localFocalPoint, + rotation: _computeRotationFactor(), + pointerCount: pointerCount, + focalPointDelta: _delta, + )); + }); + } + } + } + + void _dispatchOnStartCallbackIfNeeded() { + assert(_state == _ScaleState.started); + if (onStart != null) { + invokeCallback<void>('onStart', () { + onStart!(ScaleStartDetails( + focalPoint: _currentFocalPoint!, + localFocalPoint: _localFocalPoint, + pointerCount: pointerCount, + )); + }); + } + } + + @override + void acceptGesture(int pointer) { + if (_state == _ScaleState.possible) { + _state = _ScaleState.started; + _dispatchOnStartCallbackIfNeeded(); + if (dragStartBehavior == DragStartBehavior.start) { + _initialFocalPoint = _currentFocalPoint!; + _initialSpan = _currentSpan; + _initialLine = _currentLine; + _initialHorizontalSpan = _currentHorizontalSpan; + _initialVerticalSpan = _currentVerticalSpan; + if (_pointerPanZooms.isEmpty) { + _initialPanZoomScaleFactor = 1.0; + _initialPanZoomRotationFactor = 0.0; + } else { + _initialPanZoomScaleFactor = _scaleFactor / _pointerScaleFactor; + _initialPanZoomRotationFactor = _pointerPanZooms.values.map((_PointerPanZoomData x) => x.rotation).reduce((double a, double b) => a + b); + } + } + } + } + + @override + void rejectGesture(int pointer) { + _pointerPanZooms.remove(pointer); + _pointerLocations.remove(pointer); + _pointerQueue.remove(pointer); + stopTrackingPointer(pointer); + } + + @override + void didStopTrackingLastPointer(int pointer) { + switch (_state) { + case _ScaleState.possible: + resolve(GestureDisposition.rejected); + case _ScaleState.ready: + assert(false); // We should have not seen a pointer yet + case _ScaleState.accepted: + break; + case _ScaleState.started: + assert(false); // We should be in the accepted state when user is done + } + _state = _ScaleState.ready; + } + + @override + void dispose() { + _velocityTrackers.clear(); + super.dispose(); + } + + @override + String get debugDescription => 'scale'; +} diff --git a/lib/widgets/common/behaviour/intents.dart b/lib/widgets/common/behaviour/intents.dart new file mode 100644 index 0000000..98dcfd7 --- /dev/null +++ b/lib/widgets/common/behaviour/intents.dart @@ -0,0 +1,27 @@ +import 'package:flutter/widgets.dart'; + +class ScrollControllerAction extends CallbackAction<ScrollIntent> { + ScrollControllerAction({ + required ScrollController scrollController, + }) : super(onInvoke: (intent) => _onScrollIntent(intent, scrollController)); + + static void _onScrollIntent( + ScrollIntent intent, + ScrollController scrollController, + ) { + late int factor; + switch (intent.direction) { + case AxisDirection.up: + case AxisDirection.left: + factor = -1; + case AxisDirection.down: + case AxisDirection.right: + factor = 1; + } + scrollController.animateTo( + scrollController.offset + factor * 150, + duration: const Duration(milliseconds: 500), + curve: Curves.easeOutCubic, + ); + } +} diff --git a/lib/widgets/common/behaviour/known_extent_scroll_physics.dart b/lib/widgets/common/behaviour/known_extent_scroll_physics.dart new file mode 100644 index 0000000..018a049 --- /dev/null +++ b/lib/widgets/common/behaviour/known_extent_scroll_physics.dart @@ -0,0 +1,83 @@ +import 'package:flutter/physics.dart'; +import 'package:flutter/widgets.dart'; + +// adapted from Flutter `FixedExtentScrollPhysics` in `/widgets/list_wheel_scroll_view.dart` +class KnownExtentScrollPhysics extends ScrollPhysics { + final double Function(int index) indexToScrollOffset; + final int Function(double offset) scrollOffsetToIndex; + + const KnownExtentScrollPhysics({ + required this.indexToScrollOffset, + required this.scrollOffsetToIndex, + super.parent, + }); + + @override + KnownExtentScrollPhysics applyTo(ScrollPhysics? ancestor) { + return KnownExtentScrollPhysics( + indexToScrollOffset: indexToScrollOffset, + scrollOffsetToIndex: scrollOffsetToIndex, + parent: buildParent(ancestor), + ); + } + + @override + Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { + final ScrollMetrics metrics = position; + + // Scenario 1: + // If we're out of range and not headed back in range, defer to the parent + // ballistics, which should put us back in range at the scrollable's boundary. + if ((velocity <= 0.0 && metrics.pixels <= metrics.minScrollExtent) || (velocity >= 0.0 && metrics.pixels >= metrics.maxScrollExtent)) { + return super.createBallisticSimulation(metrics, velocity); + } + + // Create a test simulation to see where it would have ballistically fallen + // naturally without settling onto items. + final Simulation? testFrictionSimulation = super.createBallisticSimulation(metrics, velocity); + + // Scenario 2: + // If it was going to end up past the scroll extent, defer back to the + // parent physics' ballistics again which should put us on the scrollable's + // boundary. + if (testFrictionSimulation != null && (testFrictionSimulation.x(double.infinity) == metrics.minScrollExtent || testFrictionSimulation.x(double.infinity) == metrics.maxScrollExtent)) { + return super.createBallisticSimulation(metrics, velocity); + } + + // From the natural final position, find the nearest item it should have + // settled to. + final offset = (testFrictionSimulation?.x(double.infinity) ?? metrics.pixels).clamp(metrics.minScrollExtent, metrics.maxScrollExtent); + final int settlingItemIndex = scrollOffsetToIndex(offset); + final double settlingPixels = indexToScrollOffset(settlingItemIndex); + + // Scenario 3: + // If there's no velocity and we're already at where we intend to land, + // do nothing. + if (velocity.abs() < toleranceFor(position).velocity && (settlingPixels - metrics.pixels).abs() < toleranceFor(position).distance) { + return null; + } + + // Scenario 4: + // If we're going to end back at the same item because initial velocity + // is too low to break past it, use a spring simulation to get back. + if (settlingItemIndex == scrollOffsetToIndex(metrics.pixels)) { + return SpringSimulation( + spring, + metrics.pixels, + settlingPixels, + velocity, + tolerance: toleranceFor(position), + ); + } + + // Scenario 5: + // Create a new friction simulation except the drag will be tweaked to land + // exactly on the item closest to the natural stopping point. + return FrictionSimulation.through( + metrics.pixels, + settlingPixels, + velocity, + toleranceFor(position).velocity * velocity.sign, + ); + } +} diff --git a/lib/widgets/common/behaviour/pop/double_back.dart b/lib/widgets/common/behaviour/pop/double_back.dart new file mode 100644 index 0000000..d73aa56 --- /dev/null +++ b/lib/widgets/common/behaviour/pop/double_back.dart @@ -0,0 +1,49 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:overlay_support/overlay_support.dart'; +import 'package:provider/provider.dart'; + +final DoubleBackPopHandler doubleBackPopHandler = DoubleBackPopHandler._private(); + +class DoubleBackPopHandler extends PopHandler { + bool _backOnce = false; + Timer? _backTimer; + + DoubleBackPopHandler._private(); + + @override + bool canPop(BuildContext context) { + if (context.select<Settings, bool>((v) => !v.mustBackTwiceToExit)) return true; + if (Navigator.canPop(context)) return true; + return false; + } + + @override + void onPopBlocked(BuildContext context) { + if (_backOnce) { + if (Navigator.canPop(context)) { + Navigator.maybeOf(context)?.pop(); + } else { + // exit + reportService.log('Exit by pop'); + PopExitNotification().dispatch(context); + SystemNavigator.pop(); + } + } else { + _backOnce = true; + _backTimer?.cancel(); + _backTimer = Timer(ADurations.doubleBackTimerDelay, () => _backOnce = false); + toast( + context.l10n.doubleBackExitMessage, + duration: ADurations.doubleBackTimerDelay, + ); + } + } +} diff --git a/lib/widgets/common/behaviour/pop/scope.dart b/lib/widgets/common/behaviour/pop/scope.dart new file mode 100644 index 0000000..ff750b9 --- /dev/null +++ b/lib/widgets/common/behaviour/pop/scope.dart @@ -0,0 +1,54 @@ +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; + +// this widget combines multiple pop handlers with a guaranteed order +class AvesPopScope extends StatelessWidget { + final List<PopHandler> handlers; + final Widget child; + + const AvesPopScope({ + super.key, + required this.handlers, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final blocker = handlers.firstWhereOrNull((v) => !v.canPop(context)); + return PopScope( + canPop: blocker == null, + onPopInvokedWithResult: (didPop, result) { + if (!didPop) { + blocker?.onPopBlocked(context); + } + }, + child: child, + ); + } +} + +abstract class PopHandler { + bool canPop(BuildContext context); + + void onPopBlocked(BuildContext context); +} + +class APopHandler implements PopHandler { + final bool Function(BuildContext context) _canPop; + final void Function(BuildContext context) _onPopBlocked; + + APopHandler({ + required bool Function(BuildContext context) canPop, + required void Function(BuildContext context) onPopBlocked, + }) : _canPop = canPop, + _onPopBlocked = onPopBlocked; + + @override + bool canPop(BuildContext context) => _canPop(context); + + @override + void onPopBlocked(BuildContext context) => _onPopBlocked(context); +} + +@immutable +class PopExitNotification extends Notification {} diff --git a/lib/widgets/common/behaviour/pop/tv_navigation.dart b/lib/widgets/common/behaviour/pop/tv_navigation.dart new file mode 100644 index 0000000..4935907 --- /dev/null +++ b/lib/widgets/common/behaviour/pop/tv_navigation.dart @@ -0,0 +1,43 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +final TvNavigationPopHandler tvNavigationPopHandler = TvNavigationPopHandler._private(); + +// address `TV-DB` requirement from https://developer.android.com/docs/quality-guidelines/tv-app-quality +class TvNavigationPopHandler implements PopHandler { + TvNavigationPopHandler._private(); + + @override + bool canPop(BuildContext context) { + if (context.select<Settings, bool>((v) => !v.useTvLayout)) return true; + if (_isHome(context)) return true; + return false; + } + + @override + void onPopBlocked(BuildContext context) { + Navigator.maybeOf(context)?.pushAndRemoveUntil( + settings.homeNavItem.routeBuilder(context, topLevel: true), + (route) => false, + ); + } + + static bool _isHome(BuildContext context) { + final home = settings.homeNavItem; + final currentRoute = context.currentRouteName; + + if (currentRoute != home.route) return false; + + switch (home.route) { + case CollectionPage.routeName: + return context.read<CollectionLens>().filters.isEmpty; + default: + return true; + } + } +} diff --git a/lib/widgets/common/behaviour/route_tracker.dart b/lib/widgets/common/behaviour/route_tracker.dart new file mode 100644 index 0000000..274e08a --- /dev/null +++ b/lib/widgets/common/behaviour/route_tracker.dart @@ -0,0 +1,18 @@ +import 'package:aves/services/common/services.dart'; +import 'package:flutter/material.dart'; + +class ReportingRouteTracker extends NavigatorObserver { + @override + void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) => reportService.log('Nav push to ${_name(route)}'); + + @override + void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) => reportService.log('Nav pop to ${_name(previousRoute)}'); + + @override + void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) => reportService.log('Nav remove to ${_name(previousRoute)}'); + + @override + void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) => reportService.log('Nav replace to ${_name(newRoute)}'); + + String _name(Route<dynamic>? route) => route?.settings.name ?? 'unnamed ${route?.runtimeType}'; +} diff --git a/lib/widgets/common/behaviour/routes.dart b/lib/widgets/common/behaviour/routes.dart new file mode 100644 index 0000000..e9a42d8 --- /dev/null +++ b/lib/widgets/common/behaviour/routes.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +class DirectPageTransitionsTheme extends PageTransitionsTheme { + const DirectPageTransitionsTheme(); + + @override + Widget buildTransitions<T>( + PageRoute<T> route, + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + Widget child, + ) => + child; +} + +class DirectMaterialPageRoute<T> extends PageRouteBuilder<T> { + DirectMaterialPageRoute({ + super.settings, + required WidgetBuilder builder, + }) : super( + transitionDuration: Duration.zero, + pageBuilder: (context, a, sa) => builder(context), + ); + + @override + Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { + return child; + } +} + +class TransparentMaterialPageRoute<T> extends PageRouteBuilder<T> { + TransparentMaterialPageRoute({ + super.settings, + required super.pageBuilder, + }); + + @override + bool get opaque => false; + + @override + Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { + final theme = Theme.of(context).pageTransitionsTheme; + return theme.buildTransitions<T>(this, context, animation, secondaryAnimation, child); + } +} diff --git a/lib/widgets/common/behaviour/sloppy_scroll_physics.dart b/lib/widgets/common/behaviour/sloppy_scroll_physics.dart new file mode 100644 index 0000000..f850795 --- /dev/null +++ b/lib/widgets/common/behaviour/sloppy_scroll_physics.dart @@ -0,0 +1,30 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; + +// TODO TLAD merge with `MagnifierScrollerPhysics` +class SloppyScrollPhysics extends ScrollPhysics { + final DeviceGestureSettings? gestureSettings; + + // in [0, 1] + // 0: most reactive but will not let Magnifier recognizers accept gestures + // 1: less reactive but gives the most leeway to Magnifier recognizers + final double touchSlopFactor; + + const SloppyScrollPhysics({ + required this.gestureSettings, + this.touchSlopFactor = 1, + super.parent, + }); + + @override + SloppyScrollPhysics applyTo(ScrollPhysics? ancestor) { + return SloppyScrollPhysics( + gestureSettings: gestureSettings, + touchSlopFactor: touchSlopFactor, + parent: buildParent(ancestor), + ); + } + + @override + double get dragStartDistanceMotionThreshold => (gestureSettings?.touchSlop ?? kTouchSlop) * touchSlopFactor; +} diff --git a/lib/widgets/common/behaviour/springy_scroll_physics.dart b/lib/widgets/common/behaviour/springy_scroll_physics.dart new file mode 100644 index 0000000..51b887c --- /dev/null +++ b/lib/widgets/common/behaviour/springy_scroll_physics.dart @@ -0,0 +1,19 @@ +import 'package:flutter/widgets.dart'; + +class SpringyScrollPhysics extends ScrollPhysics { + @override + final SpringDescription spring; + + const SpringyScrollPhysics({ + required this.spring, + super.parent, + }); + + @override + SpringyScrollPhysics applyTo(ScrollPhysics? ancestor) { + return SpringyScrollPhysics( + spring: spring, + parent: buildParent(ancestor), + ); + } +} diff --git a/lib/widgets/common/expandable_filter_row.dart b/lib/widgets/common/expandable_filter_row.dart new file mode 100644 index 0000000..a69652c --- /dev/null +++ b/lib/widgets/common/expandable_filter_row.dart @@ -0,0 +1,181 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:flutter/material.dart'; + +class TitledExpandableFilterRow extends StatelessWidget { + final String title; + final List<CollectionFilter> filters; + final ValueNotifier<String?> expandedNotifier; + final bool showGenericIcon; + final HeroType Function(CollectionFilter filter)? heroTypeBuilder; + final AFilterCallback onTap; + final OffsetFilterCallback? onLongPress; + + const TitledExpandableFilterRow({ + super.key, + required this.title, + required this.filters, + required this.expandedNotifier, + this.showGenericIcon = true, + this.heroTypeBuilder, + required this.onTap, + required this.onLongPress, + }); + + @override + Widget build(BuildContext context) { + if (filters.isEmpty) return const SizedBox(); + + final isExpanded = expandedNotifier.value == title; + + Widget header = Text( + title, + style: AStyles.knownTitleText, + ); + void toggle() => expandedNotifier.value = isExpanded ? null : title; + if (settings.useTvLayout) { + header = Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: InkWell( + onTap: toggle, + borderRadius: const BorderRadius.all(Radius.circular(123)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + header, + const SizedBox(width: 16), + Icon(isExpanded ? AIcons.collapse : AIcons.expand), + ], + ), + ), + ), + ); + } else { + header = Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + header, + const Spacer(), + IconButton( + icon: Icon(isExpanded ? AIcons.collapse : AIcons.expand), + onPressed: toggle, + tooltip: isExpanded ? MaterialLocalizations.of(context).expandedIconTapHint : MaterialLocalizations.of(context).collapsedIconTapHint, + ), + ], + ), + ); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + header, + ExpandableFilterRow( + filters: filters, + isExpanded: isExpanded, + showGenericIcon: showGenericIcon, + heroTypeBuilder: heroTypeBuilder, + onTap: onTap, + onLongPress: onLongPress, + ), + ], + ); + } +} + +class ExpandableFilterRow extends StatelessWidget { + final List<CollectionFilter> filters; + final bool isExpanded; + final bool showGenericIcon; + final Widget? Function(CollectionFilter)? leadingBuilder; + final HeroType Function(CollectionFilter filter)? heroTypeBuilder; + final AFilterCallback onTap; + final AFilterCallback? onRemove; + final OffsetFilterCallback? onLongPress; + + static const double horizontalPadding = 8; + static const double verticalPadding = 8; + + const ExpandableFilterRow({ + super.key, + required this.filters, + required this.isExpanded, + this.showGenericIcon = true, + this.leadingBuilder, + this.heroTypeBuilder, + required this.onTap, + this.onRemove, + required this.onLongPress, + }); + + @override + Widget build(BuildContext context) { + if (filters.isEmpty) return const SizedBox(); + return AnimatedSwitcher( + duration: ADurations.filterRowExpandAnimation, + layoutBuilder: (currentChild, previousChildren) => Stack( + children: [ + ...previousChildren, + if (currentChild != null) currentChild, + ], + ), + child: isExpanded ? _buildExpanded() : _buildCollapsed(), + ); + } + + Widget _buildExpanded() { + return Container( + key: const Key('wrap'), + padding: const EdgeInsets.symmetric(horizontal: horizontalPadding), + // specify transparent as a workaround to prevent + // chip border clipping when the floating app bar is fading + color: Colors.transparent, + child: Wrap( + spacing: horizontalPadding, + runSpacing: verticalPadding, + children: filters.map(_buildChip).toList(), + ), + ); + } + + Widget _buildCollapsed() { + final list = Container( + key: const Key('list'), + // specify transparent as a workaround to prevent + // chip border clipping when the floating app bar is fading + color: Colors.transparent, + height: AvesFilterChip.minChipHeight, + child: ListView.separated( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: horizontalPadding), + itemBuilder: (context, index) { + return index < filters.length ? _buildChip(filters[index]) : const SizedBox(); + }, + separatorBuilder: (context, index) => const SizedBox(width: 8), + itemCount: filters.length, + ), + ); + return list; + } + + Widget _buildChip(CollectionFilter filter) { + return AvesFilterChip( + // key is expected by test driver + key: Key(filter.key), + filter: filter, + allowGenericIcon: showGenericIcon, + leadingOverride: leadingBuilder?.call(filter), + heroType: heroTypeBuilder?.call(filter) ?? HeroType.onTap, + onTap: onTap, + onRemove: onRemove, + onLongPress: onLongPress, + ); + } +} diff --git a/lib/widgets/common/extensions/build_context.dart b/lib/widgets/common/extensions/build_context.dart new file mode 100644 index 0000000..ba02734 --- /dev/null +++ b/lib/widgets/common/extensions/build_context.dart @@ -0,0 +1,25 @@ +import 'package:aves/l10n/l10n.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +extension ExtraContext on BuildContext { + String? get currentRouteName => ModalRoute.of(this)?.settings.name; + + AppLocalizations get l10n => AppLocalizations.of(this)!; + + String get locale => l10n.localeName; + + bool get isArabic => locale.startsWith('ar'); + + bool get isRtl => Directionality.of(this) == TextDirection.rtl; + + String applyDirectionality(String text) => '$_directionalityMark$text'; + + String get _directionalityMark { + if (isRtl) { + return isArabic ? Unicode.ALM : Unicode.RLM; + } else { + return Unicode.LRM; + } + } +} diff --git a/lib/widgets/common/extensions/geometry.dart b/lib/widgets/common/extensions/geometry.dart new file mode 100644 index 0000000..3979c4a --- /dev/null +++ b/lib/widgets/common/extensions/geometry.dart @@ -0,0 +1,7 @@ +import 'dart:ui'; + +extension ExtraRect on Rect { + bool containsIncludingBottomRight(Offset offset, {double tolerance = 0}) { + return offset.dx >= left - tolerance && offset.dx <= right + tolerance && offset.dy >= top - tolerance && offset.dy <= bottom + tolerance; + } +} diff --git a/lib/widgets/common/extensions/media_query.dart b/lib/widgets/common/extensions/media_query.dart new file mode 100644 index 0000000..f3a1cfc --- /dev/null +++ b/lib/widgets/common/extensions/media_query.dart @@ -0,0 +1,65 @@ +import 'dart:math'; + +import 'package:flutter/widgets.dart'; + +extension ExtraMediaQueryData on MediaQueryData { + /* + examples of MediaQuery props in practice + + -- Flutter v1.22.5 + + S20, Android 11, portrait, notch top, button nav bar bottom + padding EdgeInsets(0.0, 26.0, 0.0, 48.0) + viewPadding EdgeInsets(0.0, 26.0, 0.0, 48.0) + viewInsets EdgeInsets.zero + + S20, Android 11, landscape, notch left, button nav bar right + padding EdgeInsets(26.0, 24.0, 0.0, 0.0) + viewPadding EdgeInsets(26.0, 24.0, 0.0, 0.0) + viewInsets EdgeInsets.zero + + S10e, Android 10, portrait, notch top, button nav bar bottom + padding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewInsets EdgeInsets(0.0, 0.0, 0.0, 48.0) + + S10e, Android 10, portrait, notch top, gesture nav bar bottom + padding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewInsets EdgeInsets(0.0, 0.0, 0.0, 15.0) + + S10e, Android 10, landscape, notch left, button nav bar right + padding EdgeInsets(38.7, 24.0, 0.0, 0.0) + viewPadding EdgeInsets(38.7, 24.0, 0.0, 0.0) + viewInsets EdgeInsets.zero + + S7, portrait/landscape, no notch, no nav bar + padding EdgeInsets(0.0, 24.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 24.0, 0.0, 0.0) + viewInsets EdgeInsets.zero + + -- Flutter v2.2.1 + + S10e, Android 11, portrait, notch top, button nav bar bottom, keyboard off + padding EdgeInsets(0.0, 39.0, 0.0, 48.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 48.0) + viewInsets EdgeInsets.zero + + S10e, Android 11, portrait, notch top, button nav bar bottom, keyboard on + padding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 48.0) + viewInsets EdgeInsets(0.0, 0.0, 0.0, 338.0) + + S10e, Android 11, portrait, notch top, gesture nav bar bottom, keyboard off + padding EdgeInsets(0.0, 39.0, 0.0, 15.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 15.0) + viewInsets EdgeInsets.zero + + S10e, Android 11, portrait, notch top, gesture nav bar bottom, keyboard on + padding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 15.0) + viewInsets EdgeInsets(0.0, 0.0, 0.0, 338.0) + */ + + double get effectiveBottomPadding => max(viewPadding.bottom, viewInsets.bottom); +} diff --git a/lib/widgets/common/extensions/theme.dart b/lib/widgets/common/extensions/theme.dart new file mode 100644 index 0000000..0ad34a6 --- /dev/null +++ b/lib/widgets/common/extensions/theme.dart @@ -0,0 +1,5 @@ +import 'package:flutter/material.dart'; + +extension ExtraThemeData on ThemeData { + bool get isDark => brightness == Brightness.dark; +} diff --git a/lib/widgets/common/fx/blurred.dart b/lib/widgets/common/fx/blurred.dart new file mode 100644 index 0000000..f1e4139 --- /dev/null +++ b/lib/widgets/common/fx/blurred.dart @@ -0,0 +1,94 @@ +import 'dart:ui'; + +import 'package:flutter/material.dart'; + +final _filter = ImageFilter.blur(sigmaX: 4, sigmaY: 4); +// do not use `ColorFilter.matrix` for identity, +// as it yields performance issues when there are other layers on top +final _identity = ImageFilter.matrix(Matrix4.identity().storage); + +class BlurredRect extends StatelessWidget { + final bool enabled; + final Widget child; + + const BlurredRect({ + super.key, + this.enabled = true, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ClipRect( + // TODO TLAD [flutter vNext] use `BackdropFilter.grouped` + child: BackdropFilter( + // do not modify tree when disabling filter + filter: enabled ? _filter : _identity, + child: child, + ), + ); + } +} + +class BlurredRRect extends StatelessWidget { + final bool enabled; + final BorderRadius? borderRadius; + final Widget child; + + const BlurredRRect({ + super.key, + this.enabled = true, + required this.borderRadius, + required this.child, + }); + + factory BlurredRRect.all({ + Key? key, + bool enabled = true, + required double borderRadius, + required Widget child, + }) { + return BlurredRRect( + key: key, + enabled: enabled, + borderRadius: BorderRadius.all(Radius.circular(borderRadius)), + child: child, + ); + } + + @override + Widget build(BuildContext context) { + return ClipRRect( + borderRadius: borderRadius ?? BorderRadius.zero, + // TODO TLAD [flutter vNext] use `BackdropFilter.grouped` + child: BackdropFilter( + // do not modify tree when disabling filter + filter: enabled ? _filter : _identity, + child: child, + ), + ); + } +} + +class BlurredOval extends StatelessWidget { + final bool enabled; + final Widget child; + + const BlurredOval({ + super.key, + this.enabled = true, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ClipOval( + // TODO TLAD [flutter vNext] use `BackdropFilter.grouped` + child: BackdropFilter( + // do not modify tree when disabling filter + filter: enabled ? _filter : _identity, + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/fx/borders.dart b/lib/widgets/common/fx/borders.dart new file mode 100644 index 0000000..ac4cfdc --- /dev/null +++ b/lib/widgets/common/fx/borders.dart @@ -0,0 +1,24 @@ +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:flutter/material.dart'; + +class AvesBorder { + static Color _borderColor(BuildContext context) => Theme.of(context).isDark ? Colors.white30 : Colors.black26; + + // 1 device pixel for straight lines is fine + static double straightBorderWidth(BuildContext context) => 1 / MediaQuery.devicePixelRatioOf(context); + + // 1 device pixel for curves is too thin + static double curvedBorderWidth(BuildContext context) => MediaQuery.devicePixelRatioOf(context) > 2 ? 0.5 : 1.0; + + static BorderSide straightSide(BuildContext context, {double? width}) => BorderSide( + color: _borderColor(context), + width: width ?? straightBorderWidth(context), + ); + + static BorderSide curvedSide(BuildContext context, {double? width}) => BorderSide( + color: _borderColor(context), + width: width ?? curvedBorderWidth(context), + ); + + static Border border(BuildContext context, {double? width}) => Border.fromBorderSide(curvedSide(context, width: width)); +} diff --git a/lib/widgets/common/fx/checkered_decoration.dart b/lib/widgets/common/fx/checkered_decoration.dart new file mode 100644 index 0000000..b7fb249 --- /dev/null +++ b/lib/widgets/common/fx/checkered_decoration.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; + +class CheckeredPainter extends CustomPainter { + final Paint lightPaint, darkPaint; + final double checkSize; + final Offset offset; + + CheckeredPainter({ + Color light = const Color(0xFF999999), + Color dark = const Color(0xFF666666), + this.checkSize = 20, + this.offset = Offset.zero, + }) : lightPaint = Paint()..color = light, + darkPaint = Paint()..color = dark; + + @override + void paint(Canvas canvas, Size size) { + final background = Offset.zero & size; + canvas.drawRect(background, lightPaint); + + final dx = offset.dx % (checkSize * 2); + final dy = offset.dy % (checkSize * 2); + + final xMax = (size.width / checkSize).ceil(); + final yMax = (size.height / checkSize).ceil(); + for (var x = -2; x < xMax; x++) { + for (var y = -2; y < yMax; y++) { + if ((x + y) % 2 == 0) { + final check = Rect.fromLTWH(dx + x * checkSize, dy + y * checkSize, checkSize, checkSize); + if (check.overlaps(background)) { + canvas.drawRect(check.intersect(background), darkPaint); + } + } + } + } + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/lib/widgets/common/fx/colors.dart b/lib/widgets/common/fx/colors.dart new file mode 100644 index 0000000..0b7646f --- /dev/null +++ b/lib/widgets/common/fx/colors.dart @@ -0,0 +1,26 @@ +import 'package:flutter/painting.dart'; + +class MatrixColorFilters { + static const ColorFilter greyscale = ColorFilter.matrix(<double>[ + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + ]); +} diff --git a/lib/widgets/common/fx/dashed_path_painter.dart b/lib/widgets/common/fx/dashed_path_painter.dart new file mode 100644 index 0000000..847ca42 --- /dev/null +++ b/lib/widgets/common/fx/dashed_path_painter.dart @@ -0,0 +1,142 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; + +// from https://stackoverflow.com/a/71099304/786656 +class DashedPathPainter extends CustomPainter { + final Path originalPath; + final Color pathColor; + final double strokeWidth; + final double dashGapLength; + final double dashLength; + late DashedPathProperties _dashedPathProperties; + + DashedPathPainter({ + required this.originalPath, + required this.pathColor, + this.strokeWidth = 3.0, + this.dashGapLength = 5.0, + this.dashLength = 10.0, + }); + + @override + void paint(Canvas canvas, Size size) { + _dashedPathProperties = DashedPathProperties( + path: Path(), + dashLength: dashLength, + dashGapLength: dashGapLength, + ); + final dashedPath = _getDashedPath(originalPath, dashLength, dashGapLength); + canvas.drawPath( + dashedPath, + Paint() + ..style = PaintingStyle.stroke + ..color = pathColor + ..strokeWidth = strokeWidth, + ); + } + + @override + bool shouldRepaint(DashedPathPainter oldDelegate) => oldDelegate.originalPath != originalPath || oldDelegate.pathColor != pathColor || oldDelegate.strokeWidth != strokeWidth || oldDelegate.dashGapLength != dashGapLength || oldDelegate.dashLength != dashLength; + + Path _getDashedPath( + Path originalPath, + double dashLength, + double dashGapLength, + ) { + final metricsIterator = originalPath.computeMetrics().iterator; + while (metricsIterator.moveNext()) { + final metric = metricsIterator.current; + _dashedPathProperties.extractedPathLength = 0.0; + while (_dashedPathProperties.extractedPathLength < metric.length) { + if (_dashedPathProperties.addDashNext) { + _dashedPathProperties.addDash(metric, dashLength); + } else { + _dashedPathProperties.addDashGap(metric, dashGapLength); + } + } + } + return _dashedPathProperties.path; + } +} + +class DashedPathProperties { + double extractedPathLength; + Path path; + + final double _dashLength; + double _remainingDashLength; + double _remainingDashGapLength; + bool _previousWasDash; + + DashedPathProperties({ + required this.path, + required double dashLength, + required double dashGapLength, + }) : assert(dashLength > 0.0, 'dashLength must be > 0.0'), + assert(dashGapLength > 0.0, 'dashGapLength must be > 0.0'), + _dashLength = dashLength, + _remainingDashLength = dashLength, + _remainingDashGapLength = dashGapLength, + _previousWasDash = false, + extractedPathLength = 0.0; + + bool get addDashNext { + if (!_previousWasDash || _remainingDashLength != _dashLength) { + return true; + } + return false; + } + + void addDash(ui.PathMetric metric, double dashLength) { + // Calculate lengths (actual + available) + final end = _calculateLength(metric, _remainingDashLength); + final availableEnd = _calculateLength(metric, dashLength); + // Add path + final pathSegment = metric.extractPath(extractedPathLength, end); + path.addPath(pathSegment, Offset.zero); + // Update + final delta = _remainingDashLength - (end - extractedPathLength); + _remainingDashLength = _updateRemainingLength( + delta: delta, + end: end, + availableEnd: availableEnd, + initialLength: dashLength, + ); + extractedPathLength = end; + _previousWasDash = true; + } + + void addDashGap(ui.PathMetric metric, double dashGapLength) { + // Calculate lengths (actual + available) + final end = _calculateLength(metric, _remainingDashGapLength); + final availableEnd = _calculateLength(metric, dashGapLength); + // Move path's end point + ui.Tangent tangent = metric.getTangentForOffset(end)!; + path.moveTo(tangent.position.dx, tangent.position.dy); + // Update + final delta = end - extractedPathLength; + _remainingDashGapLength = _updateRemainingLength( + delta: delta, + end: end, + availableEnd: availableEnd, + initialLength: dashGapLength, + ); + extractedPathLength = end; + _previousWasDash = false; + } + + double _calculateLength(ui.PathMetric metric, double addedLength) { + return math.min(extractedPathLength + addedLength, metric.length); + } + + double _updateRemainingLength({ + required double delta, + required double end, + required double availableEnd, + required double initialLength, + }) { + return (delta > 0 && availableEnd == end) ? delta : initialLength; + } +} diff --git a/lib/widgets/common/fx/highlight_decoration.dart b/lib/widgets/common/fx/highlight_decoration.dart new file mode 100644 index 0000000..f3a323a --- /dev/null +++ b/lib/widgets/common/fx/highlight_decoration.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; + +class HighlightDecoration extends Decoration { + final Color color; + + const HighlightDecoration({required this.color}); + + @override + BoxPainter createBoxPainter([VoidCallback? onChanged]) { + return _HighlightDecorationPainter(this, onChanged); + } +} + +class _HighlightDecorationPainter extends BoxPainter { + final HighlightDecoration decoration; + + const _HighlightDecorationPainter(this.decoration, VoidCallback? onChanged) : super(onChanged); + + @override + void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { + final size = configuration.size; + if (size == null) return; + + final confHeight = size.height; + final paintHeight = confHeight * .32; + final rect = Rect.fromLTWH(offset.dx, offset.dy + size.height * .58, size.width, paintHeight); + final rrect = RRect.fromRectAndRadius(rect, Radius.circular(paintHeight)); + final paint = Paint()..color = decoration.color; + canvas.drawRRect(rrect, paint); + } +} diff --git a/lib/widgets/common/fx/sweeper.dart b/lib/widgets/common/fx/sweeper.dart new file mode 100644 index 0000000..43e64d2 --- /dev/null +++ b/lib/widgets/common/fx/sweeper.dart @@ -0,0 +1,157 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/theme/durations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +class Sweeper extends StatefulWidget { + final WidgetBuilder builder; + final double startAngle; + final double sweepAngle; + final Curve curve; + final ValueNotifier<bool> toggledNotifier; + final bool centerSweep; + final VoidCallback? onSweepEnd; + + const Sweeper({ + super.key, + required this.builder, + this.startAngle = -pi / 2, + this.sweepAngle = pi / 4, + this.curve = Curves.easeInOutCubic, + required this.toggledNotifier, + this.centerSweep = true, + this.onSweepEnd, + }); + + @override + State<Sweeper> createState() => _SweeperState(); +} + +class _SweeperState extends State<Sweeper> with SingleTickerProviderStateMixin { + late AnimationController _angleAnimationController; + late CurvedAnimation _angleAnimation; + late Animation<double> _angle; + bool _isAppearing = false; + + bool get isToggled => widget.toggledNotifier.value; + + @override + void initState() { + super.initState(); + _angleAnimationController = AnimationController( + duration: ADurations.sweepingAnimation, + vsync: this, + ); + final startAngle = widget.startAngle; + final sweepAngle = widget.sweepAngle; + final centerSweep = widget.centerSweep; + _angleAnimation = CurvedAnimation( + parent: _angleAnimationController, + curve: widget.curve, + ); + _angle = Tween( + begin: startAngle - sweepAngle * (centerSweep ? .5 : 0), + end: startAngle + pi * 2 - sweepAngle * (centerSweep ? .5 : 1), + ).animate(_angleAnimation); + _angleAnimationController.addStatusListener(_onAnimationStatusChanged); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant Sweeper oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _angleAnimation.dispose(); + _angleAnimationController.dispose(); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(Sweeper widget) { + widget.toggledNotifier.addListener(_onToggle); + } + + void _unregisterWidget(Sweeper widget) { + widget.toggledNotifier.removeListener(_onToggle); + } + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: AnimatedOpacity( + opacity: isToggled && (_isAppearing || _angleAnimationController.status == AnimationStatus.forward) ? 1 : 0, + duration: ADurations.sweeperOpacityAnimation, + child: ValueListenableBuilder<double>( + valueListenable: _angleAnimationController, + builder: (context, value, child) { + return ClipPath( + clipper: _SweepClipPath( + startAngle: _angle.value, + sweepAngle: widget.sweepAngle, + ), + child: widget.builder(context), + ); + }), + ), + ); + } + + void _onAnimationStatusChanged(AnimationStatus status) { + setState(() {}); + if (status.isCompleted) { + widget.onSweepEnd?.call(); + } + } + + Future<void> _onToggle() async { + if (isToggled) { + _isAppearing = true; + setState(() {}); + await Future.delayed(ADurations.sweeperOpacityAnimation * timeDilation); + _isAppearing = false; + if (!mounted) return; + _angleAnimationController.reset(); + unawaited(_angleAnimationController.forward()); + } + if (!mounted) return; + setState(() {}); + } +} + +class _SweepClipPath extends CustomClipper<Path> { + final double startAngle; + final double sweepAngle; + + const _SweepClipPath({required this.startAngle, required this.sweepAngle}); + + @override + Path getClip(Size size) { + final width = size.width; + final height = size.height; + final centerX = width / 2; + final centerY = height / 2; + final diagonal = sqrt(width * width + height * height); + return Path() + ..moveTo(centerX, centerY) + ..addArc( + Rect.fromCenter( + center: Offset(centerX, centerY), + width: diagonal, + height: diagonal, + ), + startAngle, + sweepAngle, + ) + ..lineTo(centerX, centerY); + } + + @override + bool shouldReclip(covariant CustomClipper<Path> oldClipper) => true; +} diff --git a/lib/widgets/common/fx/transition_image.dart b/lib/widgets/common/fx/transition_image.dart new file mode 100644 index 0000000..044b708 --- /dev/null +++ b/lib/widgets/common/fx/transition_image.dart @@ -0,0 +1,246 @@ +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +// adapted from Flutter `_ImageState` in `/widgets/image.dart` +// and `DecorationImagePainter` in `/painting/decoration_image.dart` +// to transition between 2 different fits during hero animation: +// - BoxFit.cover at t=0 +// - BoxFit.contain at t=1 + +class TransitionImage extends StatefulWidget { + final ImageProvider image; + final ValueListenable<double> animation; + final BoxFit thumbnailFit, viewerFit; + final Color? background; + + const TransitionImage({ + super.key, + required this.image, + required this.animation, + required this.thumbnailFit, + required this.viewerFit, + this.background, + }); + + @override + State<TransitionImage> createState() => _TransitionImageState(); +} + +class _TransitionImageState extends State<TransitionImage> with WidgetsBindingObserver { + ImageStream? _imageStream; + ImageInfo? _imageInfo; + bool _isListeningToStream = false; + bool _wasSynchronouslyLoaded = false; + late DisposableBuildContext<State<TransitionImage>> _scrollAwareContext; + ImageStreamCompleterHandle? _completerHandle; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _scrollAwareContext = DisposableBuildContext<State<TransitionImage>>(this); + } + + @override + void dispose() { + assert(_imageStream != null); + WidgetsBinding.instance.removeObserver(this); + _stopListeningToStream(); + _completerHandle?.dispose(); + _scrollAwareContext.dispose(); + _replaceImage(info: null); + super.dispose(); + } + + @override + void didChangeDependencies() { + _resolveImage(); + + if (TickerMode.of(context)) { + _listenToStream(); + } else { + _stopListeningToStream(keepStreamAlive: true); + } + + super.didChangeDependencies(); + } + + @override + void didUpdateWidget(TransitionImage oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.image != oldWidget.image) { + _resolveImage(); + } + } + + @override + void reassemble() { + _resolveImage(); // in case the image cache was flushed + super.reassemble(); + } + + void _resolveImage() { + final ScrollAwareImageProvider provider = ScrollAwareImageProvider<Object>( + context: _scrollAwareContext, + imageProvider: widget.image, + ); + final ImageStream newStream = provider.resolve(createLocalImageConfiguration(context)); + _updateSourceStream(newStream); + } + + ImageStreamListener? _imageStreamListener; + + ImageStreamListener _getListener({bool recreateListener = false}) { + if (_imageStreamListener == null || recreateListener) { + _imageStreamListener = ImageStreamListener(_handleImageFrame); + } + return _imageStreamListener!; + } + + void _handleImageFrame(ImageInfo imageInfo, bool synchronousCall) { + setState(() { + _replaceImage(info: imageInfo); + _wasSynchronouslyLoaded = _wasSynchronouslyLoaded | synchronousCall; + }); + } + + void _replaceImage({required ImageInfo? info}) { + final ImageInfo? oldImageInfo = _imageInfo; + SchedulerBinding.instance.addPostFrameCallback((_) => oldImageInfo?.dispose()); + _imageInfo = info; + } + + // Updates _imageStream to newStream, and moves the stream listener + // registration from the old stream to the new stream (if a listener was + // registered). + void _updateSourceStream(ImageStream newStream) { + if (_imageStream?.key == newStream.key) { + return; + } + + if (_isListeningToStream) { + _imageStream!.removeListener(_getListener()); + } + + setState(() { + _replaceImage(info: null); + _wasSynchronouslyLoaded = false; + }); + + _imageStream = newStream; + if (_isListeningToStream) { + _imageStream!.addListener(_getListener()); + } + } + + void _listenToStream() { + if (_isListeningToStream) { + return; + } + + _imageStream!.addListener(_getListener()); + _completerHandle?.dispose(); + _completerHandle = null; + + _isListeningToStream = true; + } + + /// Stops listening to the image stream, if this state object has attached a + /// listener. + /// + /// If the listener from this state is the last listener on the stream, the + /// stream will be disposed. To keep the stream alive, set `keepStreamAlive` + /// to true, which create [ImageStreamCompleterHandle] to keep the completer + /// alive and is compatible with the [TickerMode] being off. + void _stopListeningToStream({bool keepStreamAlive = false}) { + if (!_isListeningToStream) { + return; + } + + if (keepStreamAlive && _completerHandle == null && _imageStream?.completer != null) { + _completerHandle = _imageStream!.completer!.keepAlive(); + } + + _imageStream!.removeListener(_getListener()); + _isListeningToStream = false; + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<double>( + valueListenable: widget.animation, + builder: (context, t, child) => CustomPaint( + painter: _TransitionImagePainter( + image: _imageInfo?.image, + scale: _imageInfo?.scale ?? 1.0, + t: t, + thumbnailFit: widget.thumbnailFit, + viewerFit: widget.viewerFit, + background: widget.background, + ), + ), + ); + } +} + +class _TransitionImagePainter extends CustomPainter { + final ui.Image? image; + final double scale, t; + final Color? background; + final BoxFit thumbnailFit, viewerFit; + + static final _paint = Paint() + ..isAntiAlias = false + ..filterQuality = FilterQuality.low; + static const _alignment = Alignment.center; + + const _TransitionImagePainter({ + required this.image, + required this.scale, + required this.t, + required this.thumbnailFit, + required this.viewerFit, + required this.background, + }); + + @override + void paint(Canvas canvas, Size size) { + final _image = image; + if (_image == null) return; + + if (size.isEmpty) { + return; + } + + final outputSize = size; + final inputSize = Size(_image.width.toDouble(), _image.height.toDouble()); + + final thumbnailSizes = applyBoxFit(thumbnailFit, inputSize / scale, size); + final viewerSizes = applyBoxFit(viewerFit, inputSize / scale, size); + final sourceSize = Size.lerp(thumbnailSizes.source, viewerSizes.source, t)! * scale; + final destinationSize = Size.lerp(thumbnailSizes.destination, viewerSizes.destination, t)!; + + final halfWidthDelta = (outputSize.width - destinationSize.width) / 2.0; + final halfHeightDelta = (outputSize.height - destinationSize.height) / 2.0; + final dx = halfWidthDelta + _alignment.x * halfWidthDelta; + final dy = halfHeightDelta + _alignment.y * halfHeightDelta; + final destinationPosition = Offset(dx, dy); + + final destinationRect = destinationPosition & destinationSize; + final sourceRect = _alignment.inscribe( + sourceSize, + Offset.zero & inputSize, + ); + if (background != null) { + // deflate to avoid background artifact around opaque image + canvas.drawRect(destinationRect.deflate(1), Paint()..color = background!); + } + canvas.drawImageRect(_image, sourceRect, destinationRect, _paint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/fx/transitions.dart b/lib/widgets/common/fx/transitions.dart new file mode 100644 index 0000000..b4b7f16 --- /dev/null +++ b/lib/widgets/common/fx/transitions.dart @@ -0,0 +1,14 @@ +import 'package:flutter/widgets.dart'; + +class AvesTransitions { + static Widget formTransitionBuilder(Widget child, Animation<double> animation) { + return FadeTransition( + opacity: animation, + child: SizeTransition( + sizeFactor: animation, + axisAlignment: -1, + child: child, + ), + ); + } +} 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), + ]; + }; + } +} diff --git a/lib/widgets/common/identity/aves_app_bar.dart b/lib/widgets/common/identity/aves_app_bar.dart new file mode 100644 index 0000000..fc388b9 --- /dev/null +++ b/lib/widgets/common/identity/aves_app_bar.dart @@ -0,0 +1,293 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/gestures/ink_well.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesAppBar extends StatelessWidget { + final double contentHeight; + final bool pinned; + final Widget? leading; + final Widget title; + final List<Widget> Function(BuildContext context, double maxWidth) actions; + final Widget? bottom; + final Object? transitionKey; + + static const leadingHeroTag = 'appbar-leading'; + static const titleHeroTag = 'appbar-title'; + static const double _titleMinWidth = 96; + + const AvesAppBar({ + super.key, + required this.contentHeight, + required this.pinned, + required this.leading, + required this.title, + required this.actions, + this.bottom, + this.transitionKey, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final textScaler = MediaQuery.textScalerOf(context); + final useTvLayout = settings.useTvLayout; + + Widget? _leading = leading; + if (_leading != null) { + _leading = FontSizeIconTheme( + child: _leading, + ); + } + + Widget _title = FontSizeIconTheme( + child: LayoutBuilder( + builder: (context, constraints) { + return Row( + key: ValueKey(transitionKey), + children: [ + Expanded(child: title), + ...(actions(context, max(0, constraints.maxWidth - _titleMinWidth))), + ], + ); + }, + ), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + _title = Hero( + tag: titleHeroTag, + flightShuttleBuilder: _flightShuttleBuilder, + transitionOnUserGestures: true, + child: AnimatedSwitcher( + duration: context.read<DurationsData>().iconAnimation, + child: _title, + ), + ); + + if (_leading != null) { + _leading = Hero( + tag: leadingHeroTag, + flightShuttleBuilder: _flightShuttleBuilder, + transitionOnUserGestures: true, + child: _leading, + ); + } + } + + return SliverPersistentHeader( + floating: !useTvLayout, + pinned: pinned, + delegate: _SliverAppBarDelegate( + height: MediaQuery.paddingOf(context).top + appBarHeightForContentHeight(contentHeight), + child: DirectionalSafeArea( + start: !useTvLayout, + bottom: false, + child: AvesFloatingBar( + builder: (context, backgroundColor, child) => Material( + color: backgroundColor, + child: AInkResponse( + // absorb taps while providing visual feedback + onTap: () {}, + onLongPress: () {}, + containedInkWell: true, + highlightShape: BoxShape.rectangle, + longPressTimeout: settings.longPressTimeout, + child: child, + ), + ), + child: Theme( + data: theme.copyWith( + colorScheme: colorScheme.copyWith( + onSurfaceVariant: colorScheme.onSurface, + ), + ), + child: Column( + children: [ + SizedBox( + height: textScaler.scale(kToolbarHeight), + child: Row( + children: [ + _leading != null + ? Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: _leading, + ) + : const SizedBox(width: 16), + Expanded( + child: DefaultTextStyle( + style: theme.appBarTheme.titleTextStyle!, + child: _title, + ), + ), + ], + ), + ), + if (bottom != null) bottom!, + ], + ), + ), + ), + ), + ), + ); + } + + static Widget _flightShuttleBuilder( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, + ) { + final pushing = flightDirection == HeroFlightDirection.push; + Widget popBuilder(context, child) => Opacity(opacity: 1 - animation.value, child: child); + Widget pushBuilder(context, child) => Opacity(opacity: animation.value, child: child); + return Material( + type: MaterialType.transparency, + child: DefaultTextStyle( + style: DefaultTextStyle.of(toHeroContext).style, + child: Stack( + children: [ + AnimatedBuilder( + animation: animation, + builder: pushing ? popBuilder : pushBuilder, + child: fromHeroContext.widget, + ), + AnimatedBuilder( + animation: animation, + builder: pushing ? pushBuilder : popBuilder, + child: toHeroContext.widget, + ), + ], + ), + ), + ); + } + + static double appBarHeightForContentHeight(double contentHeight) => AvesFloatingBar.margin.vertical + contentHeight; +} + +class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { + final double height; + final Widget child; + + const _SliverAppBarDelegate({ + required this.height, + required this.child, + }); + + @override + double get minExtent => height; + + @override + double get maxExtent => height; + + @override + Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) => child; + + @override + bool shouldRebuild(covariant _SliverAppBarDelegate oldDelegate) => true; +} + +class AvesFloatingBar extends StatefulWidget { + final Widget Function(BuildContext context, Color backgroundColor, Widget? child) builder; + final Widget? child; + + static const margin = EdgeInsets.all(8); + static const borderRadius = BorderRadius.all(Radius.circular(8)); + + const AvesFloatingBar({ + super.key, + required this.builder, + this.child, + }); + + @override + State<AvesFloatingBar> createState() => _AvesFloatingBarState(); +} + +class _AvesFloatingBarState extends State<AvesFloatingBar> with RouteAware { + // prevent expensive blurring when the current page is hidden + final ValueNotifier<bool> _isBlurAllowedNotifier = ValueNotifier(true); + Timer? _blurBlockTimer; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final route = ModalRoute.of(context); + if (route is PageRoute) { + AvesApp.pageRouteObserver.subscribe(this, route); + } + } + + @override + void dispose() { + AvesApp.pageRouteObserver.unsubscribe(this); + _isBlurAllowedNotifier.dispose(); + super.dispose(); + } + + @override + void didPopNext() { + // post to prevent single frame flash during hero + _blurBlockTimer?.cancel(); + _blurBlockTimer = null; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _isBlurAllowedNotifier.value = true; + }); + } + + @override + void didPushNext() { + // delay blur disabling, otherwise visual artifacts appear during page transition with Impeller + _blurBlockTimer?.cancel(); + _blurBlockTimer = Timer(ADurations.pageTransitionLoose, () { + if (mounted) { + _isBlurAllowedNotifier.value = false; + } + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final backgroundColor = theme.appBarTheme.backgroundColor ?? Themes.firstLayerColor(context); + return ValueListenableBuilder<bool>( + valueListenable: _isBlurAllowedNotifier, + builder: (context, isBlurAllowed, child) { + final blurred = isBlurAllowed && context.select<Settings, bool>((v) => v.enableBlurEffect); + return Container( + foregroundDecoration: BoxDecoration( + border: Border.all( + color: theme.dividerColor, + ), + borderRadius: AvesFloatingBar.borderRadius, + ), + margin: AvesFloatingBar.margin, + child: BlurredRRect( + enabled: blurred, + borderRadius: AvesFloatingBar.borderRadius, + child: widget.builder( + context, + blurred ? backgroundColor.withValues(alpha: .85) : backgroundColor, + widget.child, + ), + ), + ); + }, + ); + } +} diff --git a/lib/widgets/common/identity/aves_caption.dart b/lib/widgets/common/identity/aves_caption.dart new file mode 100644 index 0000000..a47c1ae --- /dev/null +++ b/lib/widgets/common/identity/aves_caption.dart @@ -0,0 +1,42 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/basic/text/change_highlight.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesCaption extends StatelessWidget { + final String data; + + const AvesCaption( + this.data, { + super.key, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final subtitleStyle = theme.textTheme.bodySmall!; + final subtitleChangeShadowColor = theme.colorScheme.onSurface; + return ChangeHighlightText( + // provide key to refresh on theme brightness change + key: ValueKey(subtitleChangeShadowColor), + data, + style: subtitleStyle.copyWith( + shadows: [ + Shadow( + color: subtitleChangeShadowColor.withAlpha(0), + blurRadius: 0, + ) + ], + ), + changedStyle: subtitleStyle.copyWith( + shadows: [ + Shadow( + color: subtitleChangeShadowColor, + blurRadius: 3, + ) + ], + ), + duration: context.read<DurationsData>().formTextStyleTransition, + ); + } +} diff --git a/lib/widgets/common/identity/aves_donut.dart b/lib/widgets/common/identity/aves_donut.dart new file mode 100644 index 0000000..3ad6bc7 --- /dev/null +++ b/lib/widgets/common/identity/aves_donut.dart @@ -0,0 +1,201 @@ +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:charts_flutter/flutter.dart' as charts; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +typedef DatumKeyFormatter = String Function(AvesDonutDatum d); +typedef DatumValueFormatter = String Function(int d); +typedef DatumColorizer = Color Function(BuildContext context, AvesDonutDatum d); +typedef DatumCallback = void Function(AvesDonutDatum d); + +class AvesDonut extends StatefulWidget { + final Widget title; + final Map<String, int> byTypes; + final Duration animationDuration; + final DatumKeyFormatter formatKey; + final DatumValueFormatter formatValue; + final DatumColorizer colorize; + final DatumCallback? onTap; + + const AvesDonut({ + super.key, + required this.title, + required this.byTypes, + required this.animationDuration, + required this.formatKey, + required this.formatValue, + required this.colorize, + this.onTap, + }); + + @override + State<AvesDonut> createState() => _AvesDonutState(); +} + +class _AvesDonutState extends State<AvesDonut> with AutomaticKeepAliveClientMixin { + Map<String, int> get byTypes => widget.byTypes; + + DatumKeyFormatter get formatKey => widget.formatKey; + + DatumValueFormatter get formatValue => widget.formatValue; + + DatumColorizer get colorize => widget.colorize; + + static const avesDonutMinWidth = 124.0; + + @override + Widget build(BuildContext context) { + super.build(context); + + if (byTypes.isEmpty) return const SizedBox(); + + final sum = byTypes.values.sum; + + final seriesData = byTypes.entries.map((kv) { + final type = kv.key; + return AvesDonutDatum( + key: type, + value: kv.value, + ); + }).toList(); + seriesData.sort((d1, d2) { + final c = d2.value.compareTo(d1.value); + return c != 0 ? c : compareAsciiUpperCase(formatKey(d1), formatKey(d2)); + }); + + return AvesColorsProvider( + allowMonochrome: false, + child: LayoutBuilder( + builder: (context, constraints) { + final series = [ + charts.Series<AvesDonutDatum, String>( + id: 'type', + colorFn: (d, i) => charts.ColorUtil.fromDartColor(colorize(context, d)), + domainFn: (d, i) => formatKey(d), + measureFn: (d, i) => d.value, + data: seriesData, + labelAccessorFn: (d, _) => '${formatKey(d)}: ${d.value}', + ), + ]; + + final textScaler = MediaQuery.textScalerOf(context); + final minWidth = textScaler.scale(avesDonutMinWidth); + final availableWidth = constraints.maxWidth; + final dim = max(minWidth, availableWidth / (availableWidth > 4 * minWidth ? 4 : (availableWidth > 2 * minWidth ? 2 : 1))); + + final donut = SizedBox( + width: dim, + height: dim, + child: Stack( + alignment: Alignment.center, + children: [ + ClipRRect( + borderRadius: BorderRadius.all(Radius.circular(dim)), + child: Container( + width: dim * .7, + height: dim * .7, + color: Themes.secondLayerColor(context), + ), + ), + charts.PieChart( + series, + animate: context.select<Settings, bool>((v) => v.animate), + animationDuration: widget.animationDuration, + defaultRenderer: charts.ArcRendererConfig<String>( + arcWidth: 16, + ), + ), + Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + widget.title, + Text( + formatValue(sum), + textAlign: TextAlign.center, + ), + ], + ), + ), + ], + ), + ); + final onTap = widget.onTap; + final legend = SizedBox( + width: dim, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: seriesData + .map((d) => InkWell( + onTap: onTap != null ? () => onTap(d) : null, + borderRadius: const BorderRadius.all(Radius.circular(123)), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(AIcons.circle, fill: 1, color: colorize(context, d)), + const SizedBox(width: 8), + Flexible( + child: Text( + formatKey(d), + overflow: TextOverflow.fade, + softWrap: false, + maxLines: 1, + ), + ), + const SizedBox(width: 8), + Text( + formatValue(d.value), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(width: 4), + ], + ), + )) + .toList(), + ), + ); + final children = [ + donut, + legend, + ]; + return availableWidth > minWidth * 2 + ? Row( + mainAxisSize: MainAxisSize.min, + children: children, + ) + : Column( + mainAxisSize: MainAxisSize.min, + children: children, + ); + }, + ), + ); + } + + @override + bool get wantKeepAlive => true; +} + +@immutable +class AvesDonutDatum extends Equatable { + final String key; + final int value; + + @override + List<Object?> get props => [key, value]; + + const AvesDonutDatum({ + required this.key, + required this.value, + }); +} diff --git a/lib/widgets/common/identity/aves_expansion_tile.dart b/lib/widgets/common/identity/aves_expansion_tile.dart new file mode 100644 index 0000000..ad856f6 --- /dev/null +++ b/lib/widgets/common/identity/aves_expansion_tile.dart @@ -0,0 +1,74 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:expansion_tile_card/expansion_tile_card.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesExpansionTile extends StatelessWidget { + final String value; + final Widget? leading; + final String title; + final Color? highlightColor; + final ValueNotifier<String?>? expandedNotifier; + final bool initiallyExpanded, showHighlight; + final List<Widget> children; + + const AvesExpansionTile({ + super.key, + String? value, + this.leading, + required this.title, + this.highlightColor, + this.expandedNotifier, + this.initiallyExpanded = false, + this.showHighlight = true, + required this.children, + }) : value = value ?? title; + + @override + Widget build(BuildContext context) { + final enabled = children.isNotEmpty == true; + Widget titleChild = HighlightTitle( + title: title, + color: highlightColor, + enabled: enabled, + showHighlight: showHighlight, + ); + if (leading != null) { + titleChild = Row( + children: [ + leading!, + const SizedBox(width: 8), + Expanded(child: titleChild), + ], + ); + } + + final animationDuration = context.select<DurationsData, Duration>((v) => v.expansionTileAnimation); + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + return ExpansionTileCard( + // key is expected by test driver + key: Key('tilecard-$value'), + value: value, + expandedNotifier: expandedNotifier, + title: titleChild, + expandable: enabled, + initiallyExpanded: initiallyExpanded, + finalPadding: const EdgeInsets.symmetric(vertical: 6.0), + baseColor: Themes.firstLayerColor(context), + expandedTextColor: colorScheme.onSurface, + duration: animationDuration, + shadowColor: theme.shadowColor, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Divider(thickness: 1, height: 1), + const SizedBox(height: 4), + if (enabled) ...children, + ], + ), + ); + } +} diff --git a/lib/widgets/common/identity/aves_fab.dart b/lib/widgets/common/identity/aves_fab.dart new file mode 100644 index 0000000..2c943ca --- /dev/null +++ b/lib/widgets/common/identity/aves_fab.dart @@ -0,0 +1,27 @@ +import 'package:aves/theme/icons.dart'; +import 'package:flutter/material.dart'; + +class AvesFab extends StatelessWidget { + final String tooltip; + final VoidCallback onPressed; + + const AvesFab({ + super.key, + required this.tooltip, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: FloatingActionButton( + tooltip: tooltip, + onPressed: onPressed, + child: const Icon(AIcons.apply), + ), + ); + } +} diff --git a/lib/widgets/common/identity/aves_filter_chip.dart b/lib/widgets/common/identity/aves_filter_chip.dart new file mode 100644 index 0000000..1bbe9f2 --- /dev/null +++ b/lib/widgets/common/identity/aves_filter_chip.dart @@ -0,0 +1,426 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/covers.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/collection/filter_bar.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/gestures/ink_well.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +typedef AFilterCallback<T extends CollectionFilter> = void Function(T filter); +typedef OffsetFilterCallback<T extends CollectionFilter> = void Function(BuildContext context, T filter, Offset tapPosition); + +enum HeroType { always, onTap, never } + +@immutable +class AvesFilterDecoration { + final Radius radius; + final Widget widget; + + const AvesFilterDecoration({ + required this.radius, + required this.widget, + }); + + BorderRadius get textBorderRadius => BorderRadius.vertical(bottom: radius); + + BorderRadius get chipBorderRadius => BorderRadius.all(radius); +} + +class AvesFilterChip extends StatefulWidget { + final CollectionFilter filter; + final bool showLeading, showText, allowGenericIcon, useFilterColor; + final AvesFilterDecoration? decoration; + final Color? background; + final String? banner; + final Widget? leadingOverride, details; + final double padding; + final double? maxWidth; + final HeroType heroType; + final AFilterCallback? onTap, onRemove; + final OffsetFilterCallback? onLongPress; + + static const double defaultPadding = 6.0; + static const double defaultRadius = 32; + static const double outlineWidth = 2; + static const double minChipHeight = kMinInteractiveDimension; + static const double minChipWidth = kMinInteractiveDimension; + static const double iconSize = 18; + static const double fontSize = 14; + static const double decoratedContentVerticalPadding = 5; + + const AvesFilterChip({ + super.key, + required this.filter, + this.showLeading = true, + this.showText = true, + this.allowGenericIcon = true, + this.useFilterColor = true, + this.decoration, + this.background, + this.banner, + this.leadingOverride, + this.details, + this.padding = defaultPadding, + this.maxWidth, + this.heroType = HeroType.onTap, + this.onTap, + this.onRemove, + this.onLongPress = showDefaultLongPressMenu, + }); + + static double computeMaxWidthForRow( + BuildContext context, { + required int minChipPerRow, + required double chipPadding, + required double rowPadding, + }) { + final mqWidth = MediaQuery.sizeOf(context).width; + final mqHorizontalPadding = MediaQuery.paddingOf(context).horizontal; + return (mqWidth - mqHorizontalPadding - chipPadding * minChipPerRow - rowPadding) / minChipPerRow; + } + + static Future<void> showDefaultLongPressMenu(BuildContext context, CollectionFilter filter, Offset tapPosition) async { + if (context.read<ValueNotifier<AppMode>>().value.canNavigate) { + // remove focus, if any, to prevent the keyboard from showing up + // after the user is done with the popup menu + FocusManager.instance.primaryFocus?.unfocus(); + + final overlay = Overlay.of(context).context.findRenderObject() as RenderBox; + const touchArea = Size(kMinInteractiveDimension, kMinInteractiveDimension); + final actionDelegate = ChipActionDelegate(); + final animations = context.read<Settings>().accessibilityAnimations; + + final selectedAction = await showMenu<ChipAction>( + context: context, + position: RelativeRect.fromRect(tapPosition & touchArea, Offset.zero & overlay.size), + items: [ + PopupMenuItem( + child: Text(filter.getTooltip(context)), + ), + const PopupMenuDivider(), + ...ChipAction.values.where((action) => actionDelegate.isVisible(action, filter: filter)).map((action) { + late String text; + switch (action) { + case ChipAction.reverse: + text = filter.reversed ? context.l10n.chipActionFilterIn : context.l10n.chipActionFilterOut; + case ChipAction.ratingOrGreater: + text = RatingFilter.formatRatingRange(context, (filter as RatingFilter).rating, RatingFilter.opOrGreater); + case ChipAction.ratingOrLower: + text = RatingFilter.formatRatingRange(context, (filter as RatingFilter).rating, RatingFilter.opOrLower); + default: + text = action.getText(context); + } + return PopupMenuItem( + value: action, + child: FontSizeIconTheme( + child: MenuRow(text: text, icon: action.getIcon()), + ), + ); + }), + ], + popUpAnimationStyle: animations.popUpAnimationStyle, + ); + if (selectedAction != null) { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + actionDelegate.onActionSelected(context, filter, selectedAction); + } + } + } + + @override + State<AvesFilterChip> createState() => _AvesFilterChipState(); +} + +class _AvesFilterChipState extends State<AvesFilterChip> { + final Set<StreamSubscription> _subscriptions = {}; + late Future<Color> _colorFuture; + late Color _outlineColor; + late bool _tapped; + Offset? _tapPosition; + + CollectionFilter get filter => widget.filter; + + double get padding => widget.padding; + + @override + void initState() { + super.initState(); + _tapped = false; + _subscriptions.add(covers.packageChangeStream.listen(_onCoverColorChanged)); + _subscriptions.add(covers.colorChangeStream.listen(_onCoverColorChanged)); + _subscriptions.add(settings.updateStream.where((event) => event.key == SettingKeys.themeColorModeKey).listen((_) { + // delay so that contextual colors reflect the new settings + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _onCoverColorChanged(null); + }); + })); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _initColorLoader(); + } + + @override + void didUpdateWidget(covariant AvesFilterChip oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.filter != filter) { + _initColorLoader(); + _tapped = false; + } + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + super.dispose(); + } + + void _initColorLoader() { + // For app albums, `filter.color` yields a regular async `Future` the first time + // but it yields a `SynchronousFuture` when called again on a known album. + // This works fine to avoid a frame with no Future data, for new widgets. + // However, when the user moves away and back to a page with a chip using the async future, + // the existing widget FutureBuilder cycles again from the start, with a frame in `waiting` state and no data. + // So we save the result of the Future to a local variable because of this specific case. + _colorFuture = filter.color(context); + _outlineColor = context.read<AvesColorsData>().neutral; + } + + void _onCoverColorChanged(Set<CollectionFilter>? event) { + if (event == null || event.contains(filter)) { + _initColorLoader(); + setState(() {}); + } + } + + @override + Widget build(BuildContext context) { + final decoration = widget.decoration; + final chipBackground = widget.background ?? Themes.firstLayerColor(context); + + final onTap = widget.onTap != null + ? () { + WidgetsBinding.instance.addPostFrameCallback((_) => widget.onTap?.call(filter)); + setState(() => _tapped = true); + } + : null; + final onRemove = widget.onRemove != null + ? () { + WidgetsBinding.instance.addPostFrameCallback((_) => widget.onRemove?.call(filter)); + setState(() => _tapped = true); + } + : null; + final onLongPress = widget.onLongPress != null + ? Feedback.wrapForLongPress(() { + if (_tapPosition != null) { + widget.onLongPress?.call(context, filter, _tapPosition!); + } + }, context) + : null; + + Widget? content; + final showLeading = widget.showLeading; + final showText = widget.showText; + if (showLeading || showText) { + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = textScaler.scale(AvesFilterChip.iconSize); + final leading = showLeading ? widget.leadingOverride ?? filter.iconBuilder(context, iconSize, allowGenericIcon: widget.allowGenericIcon) : null; + final trailing = onRemove != null + ? Theme( + data: Theme.of(context).copyWith( + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + child: IconButton( + icon: Icon(AIcons.clear, size: iconSize), + padding: EdgeInsets.zero, + splashRadius: IconTheme.of(context).size, + constraints: const BoxConstraints(), + onPressed: onRemove, + ), + ) + : null; + + content = Row( + mainAxisSize: decoration != null ? MainAxisSize.max : MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (leading != null) leading, + if (leading != null && showText) SizedBox(width: padding), + if (showText) + Flexible( + child: Text( + filter.getLabel(context), + style: TextStyle( + fontSize: AvesFilterChip.fontSize, + decoration: filter.reversed ? TextDecoration.lineThrough : null, + decorationThickness: 2, + ), + softWrap: false, + overflow: TextOverflow.fade, + ), + ), + if (trailing != null) ...[ + SizedBox(width: padding), + trailing, + ], + ], + ); + + final details = widget.details; + if (details != null) { + content = Column( + mainAxisSize: MainAxisSize.min, + children: [ + content, + Flexible(child: details), + ], + ); + } + + if (decoration != null) { + content = Align( + alignment: Alignment.bottomCenter, + child: ClipRRect( + borderRadius: decoration.textBorderRadius, + child: Container( + padding: EdgeInsets.symmetric(horizontal: padding * 2, vertical: AvesFilterChip.decoratedContentVerticalPadding), + color: chipBackground, + child: content, + ), + ), + ); + } else { + content = Padding( + padding: EdgeInsets.symmetric(horizontal: padding * 2), + child: content, + ); + } + } + + final borderRadius = decoration?.chipBorderRadius ?? const BorderRadius.all(Radius.circular(AvesFilterChip.defaultRadius)); + final banner = widget.banner; + Widget chip = Container( + constraints: BoxConstraints( + minWidth: AvesFilterChip.minChipWidth, + maxWidth: max( + AvesFilterChip.minChipWidth, + widget.maxWidth ?? + AvesFilterChip.computeMaxWidthForRow( + context, + minChipPerRow: 2, + chipPadding: FilterBar.chipPadding.horizontal, + rowPadding: FilterBar.rowPadding.horizontal, + )), + minHeight: AvesFilterChip.minChipHeight, + ), + child: Stack( + fit: StackFit.passthrough, + children: [ + if (decoration != null) + ClipRRect( + borderRadius: decoration.chipBorderRadius, + child: decoration.widget, + ), + Material( + color: decoration != null ? Colors.transparent : chipBackground, + shape: RoundedRectangleBorder( + borderRadius: borderRadius, + ), + child: AInkResponse( + // as of Flutter v2.8.0, `InkWell` does not have `onLongPressStart` like `GestureDetector`, + // so we get the long press details from the tap instead + onTapDown: onLongPress != null ? (details) => _tapPosition = details.globalPosition : null, + onTap: onTap, + onLongPress: onLongPress, + containedInkWell: true, + highlightShape: BoxShape.rectangle, + borderRadius: borderRadius, + longPressTimeout: settings.longPressTimeout, + child: FutureBuilder<Color>( + future: _colorFuture, + builder: (context, snapshot) { + if (snapshot.hasData) { + _outlineColor = snapshot.data!; + } + return DecoratedBox( + decoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: widget.useFilterColor ? _outlineColor : context.select<AvesColorsData, Color>((v) => v.neutral), + width: AvesFilterChip.outlineWidth, + )), + borderRadius: borderRadius, + ), + position: DecorationPosition.foreground, + child: content, + ); + }, + ), + ), + ), + if (banner != null) + LayoutBuilder( + builder: (context, constraints) { + return ClipRRect( + borderRadius: borderRadius, + child: Align( + // align to corner the scaled down banner in RTL + alignment: AlignmentDirectional.topStart, + child: Transform( + transform: Matrix4.identity().scaled((constraints.maxHeight / 90 - .4).clamp(.45, 1.0)), + child: Banner( + message: banner.toUpperCase(), + location: BannerLocation.topStart, + color: Theme.of(context).colorScheme.primary, + child: const SizedBox(), + ), + ), + ), + ); + }, + ), + ], + ), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + final heroType = widget.heroType; + if (heroType == HeroType.always || (heroType == HeroType.onTap && _tapped)) { + chip = Hero( + tag: filter, + transitionOnUserGestures: true, + child: MediaQueryDataProvider( + child: DefaultTextStyle( + style: const TextStyle(), + child: chip, + ), + ), + ); + } + } + return chip; + } +} diff --git a/lib/widgets/common/identity/aves_icons.dart b/lib/widgets/common/identity/aves_icons.dart new file mode 100644 index 0000000..3f67d63 --- /dev/null +++ b/lib/widgets/common/identity/aves_icons.dart @@ -0,0 +1,363 @@ +import 'package:aves/image_providers/app_icon_image_provider.dart'; +import 'package:aves/model/covers.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class VideoIcon extends StatelessWidget { + final AvesEntry entry; + + const VideoIcon({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + final gridTheme = context.watch<GridThemeData>(); + final showDuration = gridTheme.showVideoDuration; + Widget child = OverlayIcon( + icon: entry.is360 ? AIcons.sphericalVideo : AIcons.videoPlay, + text: showDuration ? entry.durationText : null, + iconScale: entry.is360 && showDuration ? .9 : 1, + ); + if (showDuration) { + child = DefaultTextStyle( + style: TextStyle( + fontSize: gridTheme.fontSize, + ), + child: child, + ); + } + return child; + } +} + +class AnimatedImageIcon extends StatelessWidget { + const AnimatedImageIcon({super.key}); + + static const scale = .8; + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.animated, + iconScale: scale, + ); + } +} + +class GeoTiffIcon extends StatelessWidget { + const GeoTiffIcon({super.key}); + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.geo, + ); + } +} + +class HdrIcon extends StatelessWidget { + const HdrIcon({super.key}); + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.hdr, + ); + } +} + +class PanoramaIcon extends StatelessWidget { + const PanoramaIcon({super.key}); + + static const scale = .85; + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.panorama, + iconScale: scale, + ); + } +} + +class FavouriteIcon extends StatelessWidget { + const FavouriteIcon({super.key}); + + static const scale = .9; + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.favourite, + iconScale: scale, + ); + } +} + +class TagIcon extends StatelessWidget { + final IconData icon; + + const TagIcon._private({required this.icon}); + + factory TagIcon.tagged() => const TagIcon._private(icon: AIcons.tag); + + factory TagIcon.untagged() => TagIcon._private(icon: AIcons.tagUntagged); + + static const scale = .9; + + @override + Widget build(BuildContext context) { + return OverlayIcon( + icon: icon, + iconScale: scale, + relativeOffset: const Offset(.05, .05), + ); + } +} + +class LocationIcon extends StatelessWidget { + final IconData icon; + + const LocationIcon._private({required this.icon}); + + factory LocationIcon.located() => const LocationIcon._private(icon: AIcons.location); + + factory LocationIcon.unlocated() => const LocationIcon._private(icon: AIcons.locationUnlocated); + + @override + Widget build(BuildContext context) { + return OverlayIcon( + icon: icon, + ); + } +} + +class RawIcon extends StatelessWidget { + const RawIcon({super.key}); + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.raw, + ); + } +} + +class MotionPhotoIcon extends StatelessWidget { + const MotionPhotoIcon({super.key}); + + static const scale = .8; + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.motionPhoto, + iconScale: scale, + ); + } +} + +class MultiPageIcon extends StatelessWidget { + final AvesEntry entry; + + static const scale = .8; + + const MultiPageIcon({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + String? text; + if (entry.isStack) { + text = '${entry.stackedEntries?.length}'; + } + final child = OverlayIcon( + icon: AIcons.multiPage, + iconScale: scale, + text: text, + ); + return DefaultTextStyle( + style: TextStyle( + fontSize: context.select<GridThemeData, double>((t) => t.fontSize), + ), + child: child, + ); + } +} + +class RatingIcon extends StatelessWidget { + final AvesEntry entry; + + const RatingIcon({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + return DefaultTextStyle( + style: TextStyle( + fontSize: context.select<GridThemeData, double>((t) => t.fontSize), + ), + child: OverlayIcon( + icon: AIcons.rating, + text: '${entry.rating}', + ), + ); + } +} + +class TrashIcon extends StatelessWidget { + final int? trashDaysLeft; + + const TrashIcon({ + super.key, + required this.trashDaysLeft, + }); + + @override + Widget build(BuildContext context) { + final child = OverlayIcon( + icon: AIcons.bin, + text: trashDaysLeft != null ? context.l10n.timeDays(trashDaysLeft!) : null, + ); + + return DefaultTextStyle( + style: TextStyle( + fontSize: context.select<GridThemeData, double>((t) => t.fontSize), + ), + child: child, + ); + } +} + +class OverlayIcon extends StatelessWidget { + final IconData icon; + final String? text; + final double iconScale; + final EdgeInsetsGeometry margin; + final Offset? relativeOffset; + + static const defaultMargin = EdgeInsets.only(left: 1, right: 1, bottom: 1); + + const OverlayIcon({ + super.key, + required this.icon, + this.iconScale = 1, + this.text, + // default margin for multiple icons in a `Column` + this.margin = defaultMargin, + this.relativeOffset, + }); + + @override + Widget build(BuildContext context) { + final size = context.select<GridThemeData, double>((t) => t.iconSize); + Widget iconChild = Icon( + icon, + size: size, + ); + + if (relativeOffset != null) { + iconChild = FractionalTranslation( + translation: relativeOffset!, + child: iconChild, + ); + } + + if (iconScale != 1) { + // using a transform is better than modifying the icon size to properly center the scaled icon + iconChild = Transform.scale( + scale: iconScale, + child: iconChild, + ); + } + + iconChild = SizedBox( + width: size, + height: size, + child: iconChild, + ); + + return Container( + margin: margin, + padding: text != null ? EdgeInsetsDirectional.only(end: size / 4) : null, + decoration: BoxDecoration( + color: Theme.of(context).isDark ? const Color(0xAA000000) : const Color(0xCCFFFFFF), + borderRadius: BorderRadius.all(Radius.circular(size)), + ), + child: text == null + ? iconChild + : Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + iconChild, + const SizedBox(width: 2), + Flexible( + child: Text( + text!, + // consistent with the color used for the icon next to it + style: TextStyle(color: IconTheme.of(context).color), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ), + ], + ), + ); + } +} + +class IconUtils { + static Widget? getAlbumIcon({ + required BuildContext context, + required String albumPath, + double? size, + }) { + size ??= IconTheme.of(context).size; + Widget buildIcon(IconData icon) => Icon(icon, size: size); + + switch (covers.effectiveAlbumType(albumPath)) { + case AlbumType.camera: + return buildIcon(AIcons.cameraAlbum); + case AlbumType.screenshots: + case AlbumType.videoCaptures: + return buildIcon(AIcons.screenshotAlbum); + case AlbumType.screenRecordings: + return buildIcon(AIcons.recordingAlbum); + case AlbumType.download: + return buildIcon(AIcons.downloadAlbum); + case AlbumType.app: + final package = covers.effectiveAlbumPackage(albumPath); + return package != null + ? Image( + image: AppIconImage( + packageName: package, + size: size!, + ), + width: size, + height: size, + ) + : null; + case AlbumType.vault: + return buildIcon(vaults.isLocked(albumPath) ? AIcons.locked : AIcons.unlocked); + case AlbumType.regular: + return null; + } + } +} diff --git a/lib/widgets/common/identity/aves_logo.dart b/lib/widgets/common/identity/aves_logo.dart new file mode 100644 index 0000000..2c35137 --- /dev/null +++ b/lib/widgets/common/identity/aves_logo.dart @@ -0,0 +1,148 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/common/fx/colors.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesLogo extends StatelessWidget { + final double size; + + const AvesLogo({ + super.key, + required this.size, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + Widget child = CustomPaint( + size: Size(size / 1.4, size / 1.4), + painter: AvesLogoPainter(), + ); + if (context.select<Settings, bool>((v) => v.themeColorMode == AvesThemeColorMode.monochrome)) { + final tint = Color.lerp(theme.colorScheme.primary, Colors.white, .5)!; + child = ColorFiltered( + colorFilter: ColorFilter.mode(tint, BlendMode.modulate), + child: ColorFiltered( + colorFilter: MatrixColorFilters.greyscale, + child: child, + ), + ); + } + + return CircleAvatar( + backgroundColor: theme.dividerColor, + radius: size / 2, + child: CircleAvatar( + backgroundColor: Colors.white, + radius: size / 2 - AvesBorder.curvedBorderWidth(context), + child: child, + ), + ); + } +} + +class AvesLogoPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final dim = size.width / 100; + final strokePaint = Paint() + ..style = PaintingStyle.stroke + ..color = Colors.black + ..strokeWidth = dim * 3.050970 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round; + + final path0 = Path(); + path0.moveTo(31.784 * dim, 63.612 * dim); + path0.lineTo(48.252 * dim, 80.08 * dim); + final radius = Radius.elliptical(2.911 * dim, 2.911 * dim); + path0.arcToPoint(Offset(48.252 * dim, 84.196 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path0.lineTo(40.379000000000005 * dim, 92.069 * dim); + path0.arcToPoint(Offset(19.072000000000006 * dim, 92.069 * dim), radius: Radius.elliptical(15.067 * dim, 15.067 * dim), rotation: 0, largeArc: false, clockwise: true); + path0.lineTo(11.2 * dim, 84.197 * dim); + path0.arcToPoint(Offset(11.2 * dim, 80.08 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path0.lineTo(27.668 * dim, 63.611999999999995 * dim); + path0.arcToPoint(Offset(31.785 * dim, 63.611999999999995 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path0.close(); + + final path1 = Path(); + path1.moveTo(56.368 * dim, 39.026 * dim); + path1.lineTo(72.837 * dim, 55.494 * dim); + final radius2 = Radius.elliptical(2.904 * dim, 2.904 * dim); + path1.arcToPoint(Offset(72.837 * dim, 59.611 * dim), radius: radius2, rotation: 0, largeArc: false, clockwise: true); + path1.lineTo(56.367000000000004 * dim, 76.079 * dim); + path1.arcToPoint(Offset(52.252 * dim, 76.079 * dim), radius: radius2, rotation: 0, largeArc: false, clockwise: true); + path1.lineTo(35.784 * dim, 59.611 * dim); + path1.arcToPoint(Offset(35.784 * dim, 55.495 * dim), radius: radius2, rotation: 0, largeArc: false, clockwise: true); + path1.lineTo(52.251999999999995 * dim, 39.027 * dim); + path1.arcToPoint(Offset(56.367999999999995 * dim, 39.027 * dim), radius: radius2, rotation: 0, largeArc: false, clockwise: true); + path1.close(); + + final path2 = Path(); + path2.moveTo(60.37 * dim, 30.908 * dim); + final radius4 = Radius.elliptical(2.91 * dim, 2.91 * dim); + path2.arcToPoint(Offset(60.37 * dim, 35.025 * dim), radius: radius4, rotation: 0, largeArc: false, clockwise: false); + path2.lineTo(76.838 * dim, 51.492 * dim); + path2.arcToPoint(Offset(80.954 * dim, 51.492 * dim), radius: radius4, rotation: 0, largeArc: false, clockwise: false); + path2.lineTo(97.422 * dim, 35.025 * dim); + path2.arcToPoint(Offset(97.422 * dim, 30.907999999999998 * dim), radius: radius4, rotation: 0, largeArc: false, clockwise: false); + path2.lineTo(89.24799999999999 * dim, 22.733999999999998 * dim); + path2.arcToPoint(Offset(68.54399999999998 * dim, 22.733999999999998 * dim), radius: Radius.elliptical(14.64 * dim, 14.64 * dim), rotation: 0, largeArc: false, clockwise: false); + path2.close(); + path2.moveTo(76.624 * dim, 30.695 * dim); + final radius5 = Radius.elliptical(3.213 * dim, 3.213 * dim); + path2.arcToPoint(Offset(81.167 * dim, 30.695 * dim), radius: radius5, rotation: 0, largeArc: false, clockwise: true); + path2.arcToPoint(Offset(81.167 * dim, 35.237 * dim), radius: radius5, rotation: 0, largeArc: false, clockwise: true); + path2.arcToPoint(Offset(76.624 * dim, 35.237 * dim), radius: radius5, rotation: 0, largeArc: false, clockwise: true); + path2.arcToPoint(Offset(76.624 * dim, 30.694000000000003 * dim), radius: radius5, rotation: 0, largeArc: false, clockwise: true); + path2.close(); + + final path3 = Path(); + path3.moveTo(24.305 * dim, 6.96 * dim); + path3.lineTo(48.35 * dim, 31.004 * dim); + path3.arcToPoint(Offset(48.35 * dim, 35.121 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path3.lineTo(31.882 * dim, 51.588 * dim); + path3.arcToPoint(Offset(27.765 * dim, 51.588 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path3.lineTo(17.084 * dim, 40.907 * dim); + path3.arcToPoint(Offset(17.084 * dim, 8.75 * dim), radius: Radius.elliptical(22.738 * dim, 22.738 * dim), rotation: 0, largeArc: false, clockwise: true); + path3.lineTo(18.874 * dim, 6.96 * dim); + path3.arcToPoint(Offset(24.305 * dim, 6.96 * dim), radius: Radius.elliptical(3.84 * dim, 3.84 * dim), rotation: 0, largeArc: false, clockwise: true); + path3.close(); + + canvas.drawPath( + path0, + Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xffef435a)); + + canvas.drawPath( + path1, + Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xffe0e0e0)); + + canvas.drawPath( + path2, + Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xffffc11f)); + + canvas.drawPath( + path3, + Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xff1cc8eb)); + + // stroke should be painted over fill + canvas.drawPath(path0, strokePaint); + canvas.drawPath(path1, strokePaint); + canvas.drawPath(path2, strokePaint); + canvas.drawPath(path3, strokePaint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/identity/buttons/captioned_button.dart b/lib/widgets/common/identity/buttons/captioned_button.dart new file mode 100644 index 0000000..4d6df92 --- /dev/null +++ b/lib/widgets/common/identity/buttons/captioned_button.dart @@ -0,0 +1,184 @@ +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +typedef CaptionedIconButtonBuilder = Widget Function(BuildContext context, FocusNode focusNode); + +class CaptionedButton extends StatefulWidget { + final Animation<double> scale; + final Widget captionText; + final CaptionedIconButtonBuilder iconButtonBuilder; + final bool autofocus, showCaption; + final VoidCallback? onPressed; + + static const EdgeInsets padding = EdgeInsets.symmetric(horizontal: 8); + static const double iconTextPadding = 8; + + CaptionedButton({ + super.key, + this.scale = kAlwaysCompleteAnimation, + Widget? icon, + CaptionedIconButtonBuilder? iconButtonBuilder, + String? caption, + Widget? captionText, + this.autofocus = false, + this.showCaption = true, + required this.onPressed, + }) : assert(icon != null || iconButtonBuilder != null), + assert(caption != null || captionText != null), + iconButtonBuilder = iconButtonBuilder ?? ((_, focusNode) => IconButton(icon: icon!, onPressed: onPressed, focusNode: focusNode)), + captionText = captionText ?? CaptionedButtonText(text: caption!, enabled: onPressed != null); + + @override + State<CaptionedButton> createState() => _CaptionedButtonState(); + + static double getWidth(BuildContext context) => OverlayButton.getSize(context) + padding.horizontal; + + static Size getSize(BuildContext context, String text, {required bool showCaption}) { + final width = getWidth(context); + var height = width; + if (showCaption) { + final paragraph = RenderParagraph( + TextSpan(text: text, style: CaptionedButtonText._textStyle(context)), + textDirection: TextDirection.ltr, + textScaler: MediaQuery.textScalerOf(context), + maxLines: CaptionedButtonText.maxLines, + )..layout(const BoxConstraints(), parentUsesSize: true); + height += paragraph.getMaxIntrinsicHeight(width) + padding.vertical; + paragraph.dispose(); + } + return Size(width, height); + } + + static double getTelevisionButtonHeight(BuildContext context) { + final text = 'whatever' * 42; + return CaptionedButton.getSize(context, text, showCaption: true).height; + } +} + +class _CaptionedButtonState extends State<CaptionedButton> { + final FocusNode _focusNode = FocusNode(); + final ValueNotifier<bool> _focusedNotifier = ValueNotifier(false); + bool _didAutofocus = false; + + @override + void initState() { + super.initState(); + _updateTraversal(); + _focusNode.addListener(_onFocusChanged); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _handleAutofocus(); + } + + @override + void didUpdateWidget(covariant CaptionedButton oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.onPressed != widget.onPressed) { + _updateTraversal(); + } + if (oldWidget.autofocus != widget.autofocus) { + _handleAutofocus(); + } + } + + @override + void dispose() { + _focusNode.dispose(); + _focusedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SizedBox( + width: CaptionedButton.getWidth(context), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: CaptionedButton.padding.top), + OverlayButton( + scale: widget.scale, + focusNode: _focusNode, + child: widget.iconButtonBuilder(context, _focusNode), + ), + if (widget.showCaption) ...[ + const SizedBox(height: CaptionedButton.iconTextPadding), + ScaleTransition( + scale: widget.scale, + child: ValueListenableBuilder<bool>( + valueListenable: _focusedNotifier, + builder: (context, focused, child) { + final style = CaptionedButtonText._textStyle(context); + return AnimatedDefaultTextStyle( + style: focused + ? style.copyWith( + color: Theme.of(context).colorScheme.primary, + ) + : style, + duration: const Duration(milliseconds: 200), + child: widget.captionText, + ); + }, + ), + ), + ], + SizedBox(height: CaptionedButton.padding.bottom), + ], + ), + ); + } + + void _handleAutofocus() { + if (!_didAutofocus && widget.autofocus) { + FocusScope.of(context).autofocus(_focusNode); + _didAutofocus = true; + } + } + + void _onFocusChanged() => _focusedNotifier.value = _focusNode.hasFocus; + + void _updateTraversal() { + final enabled = widget.onPressed != null; + _focusNode.skipTraversal = !enabled; + _focusNode.canRequestFocus = enabled; + } +} + +class CaptionedButtonText extends StatelessWidget { + final String text; + final bool enabled; + + static const int maxLines = 2; + + const CaptionedButtonText({ + super.key, + required this.text, + required this.enabled, + }); + + @override + Widget build(BuildContext context) { + var style = DefaultTextStyle.of(context).style; + if (!enabled) { + style = style.copyWith(color: style.color!.withValues(alpha: .2)); + } + + return Text( + text, + style: style, + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + maxLines: maxLines, + ); + } + + static TextStyle _textStyle(BuildContext context) { + // specify `height` for accurate paragraph height measurement + final defaultTextHeight = DefaultTextStyle.of(context).style.height; + return Theme.of(context).textTheme.bodySmall!.copyWith(height: defaultTextHeight); + } +} diff --git a/lib/widgets/common/identity/buttons/outlined_button.dart b/lib/widgets/common/identity/buttons/outlined_button.dart new file mode 100644 index 0000000..851ef93 --- /dev/null +++ b/lib/widgets/common/identity/buttons/outlined_button.dart @@ -0,0 +1,43 @@ +import 'package:flutter/material.dart'; + +class AvesOutlinedButton extends StatelessWidget { + final Widget? icon; + final String label; + final VoidCallback? onPressed; + + const AvesOutlinedButton({ + super.key, + this.icon, + required this.label, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final foreground = WidgetStateProperty.resolveWith<Color>((states) { + return states.contains(WidgetState.disabled) ? theme.disabledColor : theme.colorScheme.onSurface; + }); + final style = ButtonStyle( + foregroundColor: foreground, + iconColor: foreground, + side: WidgetStateProperty.resolveWith<BorderSide>((states) { + return BorderSide( + color: states.contains(WidgetState.disabled) ? theme.disabledColor : theme.colorScheme.primary, + ); + }), + ); + return icon != null + ? OutlinedButton.icon( + onPressed: onPressed, + style: style, + icon: icon!, + label: Text(label), + ) + : OutlinedButton( + onPressed: onPressed, + style: style, + child: Text(label), + ); + } +} diff --git a/lib/widgets/common/identity/buttons/overlay_button.dart b/lib/widgets/common/identity/buttons/overlay_button.dart new file mode 100644 index 0000000..17fdc16 --- /dev/null +++ b/lib/widgets/common/identity/buttons/overlay_button.dart @@ -0,0 +1,191 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:flutter/material.dart'; + +class OverlayButton extends StatefulWidget { + final Animation<double> scale; + final BorderRadius? borderRadius; + final FocusNode? focusNode; + final Widget child; + + const OverlayButton({ + super.key, + this.scale = kAlwaysCompleteAnimation, + this.borderRadius, + this.focusNode, + required this.child, + }); + + @override + State<OverlayButton> createState() => _OverlayButtonState(); + + // icon (24) + icon padding (8) + button padding (16) + static double getSize(BuildContext context) => 48; +} + +class _OverlayButtonState extends State<OverlayButton> { + final ValueNotifier<bool> _focusedNotifier = ValueNotifier(false); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant OverlayButton oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _focusedNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(OverlayButton widget) { + widget.focusNode?.addListener(_onFocusChanged); + } + + void _unregisterWidget(OverlayButton widget) { + widget.focusNode?.removeListener(_onFocusChanged); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final borderRadius = widget.borderRadius; + + final blurred = settings.enableBlurEffect; + final overlayBackground = Themes.overlayBackgroundColor( + brightness: colorScheme.brightness, + blurred: blurred, + ); + + return Theme( + data: theme.copyWith( + colorScheme: colorScheme.copyWith( + onSurfaceVariant: colorScheme.onSurface, + ), + ), + child: ScaleTransition( + scale: widget.scale, + child: ValueListenableBuilder<bool>( + valueListenable: _focusedNotifier, + builder: (context, focused, child) { + final border = AvesBorder.border( + context, + width: AvesBorder.curvedBorderWidth(context) * (focused ? 3 : 1), + ); + return borderRadius != null + ? BlurredRRect( + enabled: blurred, + borderRadius: borderRadius, + child: Material( + type: MaterialType.button, + borderRadius: borderRadius, + color: overlayBackground, + child: AnimatedContainer( + foregroundDecoration: BoxDecoration( + border: border, + borderRadius: borderRadius, + ), + duration: const Duration(milliseconds: 200), + child: widget.child, + ), + ), + ) + : BlurredOval( + enabled: blurred, + child: Material( + type: MaterialType.circle, + color: overlayBackground, + child: AnimatedContainer( + foregroundDecoration: BoxDecoration( + border: border, + shape: BoxShape.circle, + ), + duration: const Duration(milliseconds: 200), + child: widget.child, + ), + ), + ); + }, + ), + ), + ); + } + + void _onFocusChanged() => _focusedNotifier.value = widget.focusNode?.hasFocus ?? false; +} + +class ScalingOverlayTextButton extends StatelessWidget { + final Animation<double> scale; + final VoidCallback? onPressed; + final Widget child; + + const ScalingOverlayTextButton({ + super.key, + required this.scale, + this.onPressed, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return SizeTransition( + sizeFactor: scale, + child: OverlayTextButton( + onPressed: onPressed, + child: child, + ), + ); + } +} + +class OverlayTextButton extends StatelessWidget { + final VoidCallback? onPressed; + final Widget child; + + const OverlayTextButton({ + super.key, + this.onPressed, + required this.child, + }); + + static const _borderRadius = 123.0; + static final _minSize = WidgetStateProperty.all<Size>(const Size(kMinInteractiveDimension, kMinInteractiveDimension)); + + @override + Widget build(BuildContext context) { + final blurred = settings.enableBlurEffect; + final theme = Theme.of(context); + final foreground = theme.colorScheme.onSurface; + return BlurredRRect.all( + enabled: blurred, + borderRadius: _borderRadius, + child: OutlinedButton( + onPressed: onPressed, + style: ButtonStyle( + backgroundColor: WidgetStateProperty.all<Color>(Themes.overlayBackgroundColor(brightness: theme.brightness, blurred: blurred)), + foregroundColor: WidgetStateProperty.all<Color>(foreground), + overlayColor: theme.isDark ? WidgetStateProperty.all<Color>(Colors.white.withValues(alpha: .12)) : null, + minimumSize: _minSize, + iconColor: WidgetStateProperty.all<Color>(foreground), + side: WidgetStateProperty.all<BorderSide>(AvesBorder.curvedSide(context)), + shape: WidgetStateProperty.all<OutlinedBorder>(const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(_borderRadius)), + )), + ), + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/identity/empty.dart b/lib/widgets/common/identity/empty.dart new file mode 100644 index 0000000..458d7a8 --- /dev/null +++ b/lib/widgets/common/identity/empty.dart @@ -0,0 +1,74 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +class EmptyContent extends StatelessWidget { + final IconData? icon; + final String text; + final Widget? bottom; + final AlignmentGeometry alignment; + final double fontSize; + final bool safeBottom; + + const EmptyContent({ + super.key, + this.icon, + required this.text, + this.bottom, + this.alignment = const FractionalOffset(.5, .35), + this.fontSize = 22, + this.safeBottom = true, + }); + + @override + Widget build(BuildContext context) { + final color = Theme.of(context).colorScheme.primary.withValues(alpha: .5); + final durations = context.watch<DurationsData>(); + return Padding( + padding: safeBottom + ? EdgeInsets.only( + bottom: context.select<MediaQueryData, double>((mq) => mq.effectiveBottomPadding), + ) + : EdgeInsets.zero, + child: Align( + alignment: alignment, + child: Column( + mainAxisSize: MainAxisSize.min, + children: AnimationConfiguration.toStaggeredList( + duration: durations.staggeredAnimation, + delay: durations.staggeredAnimationDelay * timeDilation, + childAnimationBuilder: (child) => SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: child, + ), + ), + children: [ + if (icon != null) ...[ + Icon( + icon, + size: 64, + color: color, + ), + const SizedBox(height: 16) + ], + if (text.isNotEmpty) + Text( + text, + style: TextStyle( + color: color, + fontSize: fontSize, + ), + textAlign: TextAlign.center, + ), + if (bottom != null) bottom!, + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/identity/highlight_title.dart b/lib/widgets/common/identity/highlight_title.dart new file mode 100644 index 0000000..76647e1 --- /dev/null +++ b/lib/widgets/common/identity/highlight_title.dart @@ -0,0 +1,74 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/fx/highlight_decoration.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class HighlightTitle extends StatelessWidget { + final String title; + final Color? color; + final double fontSize; + final bool enabled; + final bool showHighlight; + + const HighlightTitle({ + super.key, + required this.title, + this.color, + this.fontSize = 18, + this.enabled = true, + this.showHighlight = true, + }); + + static const disabledColor = Colors.grey; + + static List<Shadow> shadows(BuildContext context) => [ + Shadow( + color: Theme.of(context).isDark ? Colors.black : Colors.white, + offset: const Offset(0, 1), + blurRadius: 2, + ) + ]; + + @override + Widget build(BuildContext context) { + final style = TextStyle( + shadows: shadows(context), + fontSize: fontSize, + letterSpacing: canHaveLetterSpacing(context.locale) ? 1 : 0, + fontFeatures: const [FontFeature.enable('smcp')], + ); + + final colors = context.watch<AvesColorsData>(); + return Align( + alignment: AlignmentDirectional.centerStart, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 2), + decoration: showHighlight && context.select<Settings, bool>((v) => v.themeColorMode == AvesThemeColorMode.polychrome) + ? HighlightDecoration( + color: enabled ? color ?? colors.fromString(title) : disabledColor, + ) + : null, + margin: const EdgeInsets.symmetric(vertical: 4.0), + child: OutlinedText( + textSpans: [ + TextSpan( + text: title, + style: style, + ), + ], + outlineColor: Themes.firstLayerColor(context), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ), + ); + } +} diff --git a/lib/widgets/common/identity/scroll_thumb.dart b/lib/widgets/common/identity/scroll_thumb.dart new file mode 100644 index 0000000..718abf2 --- /dev/null +++ b/lib/widgets/common/identity/scroll_thumb.dart @@ -0,0 +1,47 @@ +import 'package:aves/widgets/common/basic/draggable_scrollbar/arrow_clipper.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/scrollbar.dart'; +import 'package:flutter/material.dart'; + +const double avesScrollThumbHeight = 48; + +// height and background color do not change +// so we do not rely on the builder props +ScrollThumbBuilder avesScrollThumbBuilder({ + required double height, + required Color backgroundColor, +}) { + final scrollThumb = Container( + decoration: const BoxDecoration( + color: Colors.black26, + borderRadius: BorderRadius.all(Radius.circular(12)), + ), + height: height, + margin: _margin, + padding: _padding, + child: ClipPath( + clipper: ArrowClipper(), + child: Container( + width: _width, + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: const BorderRadius.all(Radius.circular(12)), + ), + ), + ), + ); + return (backgroundColor, thumbAnimation, labelAnimation, height, {labelText}) { + return DraggableScrollbar.buildScrollThumbAndLabel( + scrollThumb: scrollThumb, + backgroundColor: backgroundColor, + thumbAnimation: thumbAnimation, + labelAnimation: labelAnimation, + labelText: labelText, + ); + }; +} + +const _margin = EdgeInsetsDirectional.only(end: 1); +const _padding = EdgeInsets.all(2); +const _width = 20.0; + +double get avesScrollThumbWidth => _width + _padding.horizontal + _margin.horizontal; diff --git a/lib/widgets/common/map/attribution.dart b/lib/widgets/common/map/attribution.dart new file mode 100644 index 0000000..1031779 --- /dev/null +++ b/lib/widgets/common/map/attribution.dart @@ -0,0 +1,67 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; +import 'package:provider/provider.dart'; + +class Attribution extends StatelessWidget { + final EntryMapStyle? style; + + const Attribution({ + super.key, + required this.style, + }); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + if (style == EntryMapStyles.osmLiberty) return _buildOsmAttributionMarkdown(context, l10n.mapAttributionOsmLiberty); + if (style == EntryMapStyles.openTopoMap) return _buildOsmAttributionMarkdown(context, l10n.mapAttributionOpenTopoMap); + if (style == EntryMapStyles.osmHot) return _buildOsmAttributionMarkdown(context, l10n.mapAttributionOsmHot); + if (style == EntryMapStyles.stamenWatercolor) return _buildOsmAttributionMarkdown(context, l10n.mapAttributionStamen); + return const SizedBox(); + } + + Widget _buildOsmAttributionMarkdown(BuildContext context, String data) { + final theme = Theme.of(context); + Widget child = MarkdownBody( + data: '${context.l10n.mapAttributionOsmData}${AText.separator}$data', + selectable: true, + styleSheet: MarkdownStyleSheet( + a: TextStyle(color: theme.colorScheme.primary), + p: theme.textTheme.bodySmall!.merge(const TextStyle(fontSize: InfoRowGroup.fontSize)), + ), + onTapLink: (text, href, title) => AvesApp.launchUrl(href), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + child = Hero( + tag: 'map-attribution', + flightShuttleBuilder: (flightContext, animation, flightDirection, fromHeroContext, toHeroContext) { + return DefaultTextStyle( + style: DefaultTextStyle.of(toHeroContext).style, + child: MediaQuery.removeViewPadding( + context: context, + removeLeft: true, + removeTop: true, + removeRight: true, + removeBottom: true, + child: toHeroContext.widget, + ), + ); + }, + child: child, + ); + } + + return Padding( + padding: const EdgeInsets.only(top: 4), + child: child, + ); + } +} diff --git a/lib/widgets/common/map/buttons/button.dart b/lib/widgets/common/map/buttons/button.dart new file mode 100644 index 0000000..0d3f6da --- /dev/null +++ b/lib/widgets/common/map/buttons/button.dart @@ -0,0 +1,48 @@ +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapOverlayButton extends StatelessWidget { + final ValueWidgetBuilder<VisualDensity> builder; + + const MapOverlayButton({ + super.key, + required this.builder, + }); + + factory MapOverlayButton.icon({ + Key? buttonKey, + required Widget icon, + required String tooltip, + VoidCallback? onPressed, + }) { + return MapOverlayButton( + builder: (context, visualDensity, child) => IconButton( + key: buttonKey, + iconSize: iconSize(visualDensity), + visualDensity: visualDensity, + icon: icon, + onPressed: onPressed, + tooltip: tooltip, + ), + ); + } + + @override + Widget build(BuildContext context) { + return Selector<MapThemeData, Animation<double>>( + selector: (context, v) => v.scale, + builder: (context, scale, child) => OverlayButton( + scale: scale, + child: child!, + ), + child: Selector<MapThemeData, VisualDensity>( + selector: (context, v) => v.visualDensity, + builder: builder, + ), + ); + } + + static double iconSize(VisualDensity visualDensity) => 20 + 1.5 * visualDensity.horizontal; +} diff --git a/lib/widgets/common/map/buttons/coordinate_filter.dart b/lib/widgets/common/map/buttons/coordinate_filter.dart new file mode 100644 index 0000000..80405f3 --- /dev/null +++ b/lib/widgets/common/map/buttons/coordinate_filter.dart @@ -0,0 +1,108 @@ +import 'package:aves/model/filters/coordinate.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class OverlayCoordinateFilterChip extends StatefulWidget { + final ValueNotifier<ZoomedBounds> boundsNotifier; + final double padding; + + const OverlayCoordinateFilterChip({ + super.key, + required this.boundsNotifier, + required this.padding, + }); + + @override + State<OverlayCoordinateFilterChip> createState() => _OverlayCoordinateFilterChipState(); +} + +class _OverlayCoordinateFilterChipState extends State<OverlayCoordinateFilterChip> { + final Debouncer _debouncer = Debouncer(delay: ADurations.mapInfoDebounceDelay); + final ValueNotifier<ZoomedBounds?> _idleBoundsNotifier = ValueNotifier(null); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant OverlayCoordinateFilterChip oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _idleBoundsNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(OverlayCoordinateFilterChip widget) { + widget.boundsNotifier.addListener(_onBoundsChanged); + } + + void _unregisterWidget(OverlayCoordinateFilterChip widget) { + widget.boundsNotifier.removeListener(_onBoundsChanged); + } + + @override + Widget build(BuildContext context) { + final blurred = settings.enableBlurEffect; + final theme = Theme.of(context); + return Align( + alignment: Alignment.topLeft, + child: Selector<MapThemeData, Animation<double>>( + selector: (context, v) => v.scale, + builder: (context, scale, child) => SizeTransition( + sizeFactor: scale, + axisAlignment: 1, + child: FadeTransition( + opacity: scale, + child: child, + ), + ), + child: ValueListenableBuilder<ZoomedBounds?>( + valueListenable: _idleBoundsNotifier, + builder: (context, bounds, child) { + if (bounds == null) return const SizedBox(); + final filter = CoordinateFilter( + bounds.sw, + bounds.ne, + // more stable format when bounds change + minuteSecondPadding: true, + ); + return Padding( + padding: EdgeInsets.all(widget.padding), + child: BlurredRRect.all( + enabled: blurred, + borderRadius: AvesFilterChip.defaultRadius, + child: AvesFilterChip( + filter: filter, + useFilterColor: false, + background: Themes.overlayBackgroundColor(brightness: theme.brightness, blurred: blurred), + maxWidth: double.infinity, + onTap: (filter) => SelectFilterNotification(CoordinateFilter(bounds.sw, bounds.ne)).dispatch(context), + ), + ), + ); + }, + ), + ), + ); + } + + void _onBoundsChanged() { + _debouncer(() => _idleBoundsNotifier.value = widget.boundsNotifier.value); + } +} diff --git a/lib/widgets/common/map/buttons/panel.dart b/lib/widgets/common/map/buttons/panel.dart new file mode 100644 index 0000000..c054194 --- /dev/null +++ b/lib/widgets/common/map/buttons/panel.dart @@ -0,0 +1,264 @@ +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/map/buttons/button.dart'; +import 'package:aves/widgets/common/map/buttons/coordinate_filter.dart'; +import 'package:aves/widgets/common/map/compass.dart'; +import 'package:aves/widgets/common/map/map_action_delegate.dart'; +import 'package:aves/widgets/common/providers/map_theme_provider.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class MapButtonPanel extends StatefulWidget { + final AvesMapController controller; + final ValueNotifier<ZoomedBounds> boundsNotifier; + final void Function(BuildContext context)? openMapPage; + + const MapButtonPanel({ + super.key, + required this.controller, + required this.boundsNotifier, + this.openMapPage, + }); + + @override + State<MapButtonPanel> createState() => _MapButtonPanelState(); +} + +class _MapButtonPanelState extends State<MapButtonPanel> { + late MapActionDelegate _actionDelegate; + + @override + void initState() { + super.initState(); + _updateDelegate(); + } + + @override + void didUpdateWidget(covariant MapButtonPanel oldWidget) { + super.didUpdateWidget(oldWidget); + _updateDelegate(); + } + + void _updateDelegate() => _actionDelegate = MapActionDelegate(widget.controller); + + @override + Widget build(BuildContext context) { + final showCoordinateFilter = context.select<MapThemeData, bool>((v) => v.showCoordinateFilter); + final visualDensity = context.select<MapThemeData, VisualDensity>((v) => v.visualDensity); + final double padding = 8 + visualDensity.horizontal * 2; + + Widget? topLeftButton = _buildNavigationButton(context); + Widget? topRightButton = _buildTopRightButton(context); + + return Positioned.fill( + child: TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: SafeArea( + bottom: false, + child: Stack( + children: [ + Positioned( + left: padding, + right: padding, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.only(top: padding), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (topLeftButton != null) ...[ + topLeftButton, + SizedBox(height: padding), + ], + _buildCompass(context), + ], + ), + ), + showCoordinateFilter + ? Expanded( + child: OverlayCoordinateFilterChip( + boundsNotifier: widget.boundsNotifier, + padding: padding, + ), + ) + : const Spacer(), + Padding( + padding: EdgeInsets.only(top: padding), + // key is expected by test driver + child: Column( + children: [ + if (topRightButton != null) ...[ + topRightButton, + SizedBox(height: padding), + ], + // key is expected by test driver + _buildActionButton(context, MapAction.selectStyle, buttonKey: const Key('map-menu-layers')), + ], + ), + ), + ], + ), + ), + Positioned( + right: padding, + bottom: padding, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _buildActionButton(context, MapAction.zoomIn), + SizedBox(height: padding), + _buildActionButton(context, MapAction.zoomOut), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget? _buildNavigationButton(BuildContext context) { + Widget? child; + switch (context.select<MapThemeData, MapNavigationButton>((v) => v.navigationButton)) { + case MapNavigationButton.back: + if (!settings.useTvLayout) { + child = MapOverlayButton.icon( + icon: const BackButtonIcon(), + onPressed: () => Navigator.maybeOf(context)?.pop(), + tooltip: MaterialLocalizations.of(context).backButtonTooltip, + ); + } + case MapNavigationButton.close: + child = MapOverlayButton.icon( + icon: const CloseButtonIcon(), + onPressed: SystemNavigator.pop, + tooltip: MaterialLocalizations.of(context).closeButtonTooltip, + ); + case MapNavigationButton.map: + final _openMapPage = widget.openMapPage; + if (_openMapPage != null) { + child = MapOverlayButton.icon( + icon: const Icon(AIcons.showFullscreenCorners), + onPressed: () => _openMapPage.call(context), + tooltip: context.l10n.openMapPageTooltip, + ); + } + case MapNavigationButton.none: + break; + } + if (child != null) { + child = _heroify(context, 'top-left', child); + } + return child; + } + + Widget? _buildTopRightButton(BuildContext context) { + const heroTag = 'top-right'; + + final actions = [ + MapAction.openMapApp, + MapAction.addShortcut, + ].where((action) => _actionDelegate.isVisible(context, action)).toList(); + + Widget? child; + if (actions.length == 1) { + child = _buildActionButton(context, actions.first, heroTag: heroTag); + } else if (actions.length > 1) { + child = MapOverlayButton(builder: (context, visualDensity, child) { + final animations = context.read<Settings>().accessibilityAnimations; + return PopupMenuButton<MapAction>( + itemBuilder: (context) => actions + .map((action) => PopupMenuItem( + value: action, + child: MenuRow( + text: action.getText(context), + icon: action.getIcon(), + ), + )) + .toList(), + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + _actionDelegate.onActionSelected(context, action); + }, + iconSize: MapOverlayButton.iconSize(visualDensity), + popUpAnimationStyle: animations.popUpAnimationStyle, + ); + }); + child = _heroify(context, heroTag, child); + } + return child; + } + + Widget _buildCompass(BuildContext context) { + final iconTheme = IconTheme.of(context); + final iconSize = Size.square(iconTheme.size!); + return ValueListenableBuilder<ZoomedBounds>( + valueListenable: widget.boundsNotifier, + builder: (context, bounds, child) { + final degrees = bounds.rotation; + final opacity = degrees == 0 ? .0 : 1.0; + return IgnorePointer( + ignoring: opacity == 0, + child: AnimatedOpacity( + opacity: opacity, + duration: context.select<DurationsData, Duration>((v) => v.viewerOverlayAnimation), + child: MapOverlayButton.icon( + icon: Transform( + origin: iconSize.center(Offset.zero), + transform: Matrix4.rotationZ(degToRadian(degrees)), + child: CustomPaint( + painter: CompassPainter( + color: iconTheme.color!, + ), + size: iconSize, + ), + ), + onPressed: widget.controller.resetRotation, + tooltip: context.l10n.mapPointNorthUpTooltip, + ), + ), + ); + }, + ); + } + + Widget _buildActionButton(BuildContext context, MapAction action, {Key? buttonKey, String? heroTag}) { + final child = MapOverlayButton.icon( + buttonKey: buttonKey, + icon: action.getIcon(), + onPressed: () => _actionDelegate.onActionSelected(context, action), + tooltip: action.getText(context), + ); + return _heroify(context, heroTag ?? action.name, child); + } + + Widget _heroify(BuildContext context, String? tag, Widget child) { + if (tag != null) { + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + return Hero( + tag: 'map-button-$tag', + flightShuttleBuilder: MapTheme.heroFlightShuttleBuilder, + child: child, + ); + } + } + return child; + } +} diff --git a/lib/widgets/common/map/compass.dart b/lib/widgets/common/map/compass.dart new file mode 100644 index 0000000..2563ecf --- /dev/null +++ b/lib/widgets/common/map/compass.dart @@ -0,0 +1,43 @@ +import 'package:flutter/material.dart'; + +class CompassPainter extends CustomPainter { + final Color color; + + const CompassPainter({ + required this.color, + }); + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + final base = size.width * .3; + final height = size.height * .4; + + final northTriangle = Path() + ..moveTo(center.dx - base / 2, center.dy) + ..lineTo(center.dx, center.dy - height) + ..lineTo(center.dx + base / 2, center.dy) + ..close(); + final southTriangle = Path() + ..moveTo(center.dx - base / 2, center.dy) + ..lineTo(center.dx + base / 2, center.dy) + ..lineTo(center.dx, center.dy + height) + ..close(); + + final fillPaint = Paint() + ..style = PaintingStyle.fill + ..color = color.withValues(alpha: .6); + final strokePaint = Paint() + ..style = PaintingStyle.stroke + ..color = color + ..strokeWidth = 1.7 + ..strokeJoin = StrokeJoin.round; + + canvas.drawPath(northTriangle, fillPaint); + canvas.drawPath(northTriangle, strokePaint); + canvas.drawPath(southTriangle, strokePaint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/map/decorator.dart b/lib/widgets/common/map/decorator.dart new file mode 100644 index 0000000..3de7a72 --- /dev/null +++ b/lib/widgets/common/map/decorator.dart @@ -0,0 +1,67 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/common/providers/map_theme_provider.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapDecorator extends StatelessWidget { + final Widget child; + + static const mapBorderRadius = BorderRadius.all(Radius.circular(24)); // to match button circles + static const mapBackground = Color(0xFFDBD5D3); + static const mapLoadingGrid = Color(0xFFC4BEBB); + + const MapDecorator({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + Widget _child = ClipRRect( + borderRadius: mapBorderRadius, + child: Container( + color: mapBackground, + foregroundDecoration: BoxDecoration( + border: AvesBorder.border(context), + borderRadius: mapBorderRadius, + ), + child: Stack( + children: [ + const GridPaper( + color: mapLoadingGrid, + interval: 10, + divisions: 1, + subdivisions: 1, + child: CustomPaint( + size: Size.infinite, + ), + ), + child, + ], + ), + ), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + _child = Hero( + tag: 'map-canvas', + flightShuttleBuilder: MapTheme.heroFlightShuttleBuilder, + child: _child, + ); + } + + final interactive = context.select<MapThemeData, bool>((v) => v.interactive); + return GestureDetector( + onScaleStart: interactive + ? null + : (details) { + // absorb scale gesture here to prevent scrolling + // and triggering by mistake a move to the image page above + }, + child: _child, + ); + } +} diff --git a/lib/widgets/common/map/geo_map.dart b/lib/widgets/common/map/geo_map.dart new file mode 100644 index 0000000..a794c66 --- /dev/null +++ b/lib/widgets/common/map/geo_map.dart @@ -0,0 +1,508 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/entry/sort.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/ref/poi.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/math_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/common/map/attribution.dart'; +import 'package:aves/widgets/common/map/buttons/panel.dart'; +import 'package:aves/widgets/common/map/decorator.dart'; +import 'package:aves/widgets/common/map/leaflet/map.dart'; +import 'package:aves/widgets/common/map/map_action_delegate.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:fluster/fluster.dart'; +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class GeoMap extends StatefulWidget { + final AvesMapController controller; + final CollectionLens? collection; + final List<AvesEntry>? entries; + final Size availableSize; + final LatLng? initialCenter; + final double? initialZoom; + final ValueNotifier<bool> isAnimatingNotifier; + final ValueNotifier<LatLng?>? dotLocationNotifier; + final ValueNotifier<double>? overlayOpacityNotifier; + final MapOverlay? overlayEntry; + final Set<List<LatLng>>? tracks; + final UserZoomChangeCallback? onUserZoomChange; + final MapTapCallback? onMapTap; + final void Function( + LatLng markerLocation, + AvesEntry markerEntry, + )? onMarkerTap; + final void Function( + LatLng markerLocation, + AvesEntry markerEntry, + Set<AvesEntry> clusterEntries, + Offset tapLocalPosition, + WidgetBuilder markerBuilder, + )? onMarkerLongPress; + final void Function(BuildContext context)? openMapPage; + + const GeoMap({ + super.key, + required this.controller, + this.collection, + this.entries, + required this.availableSize, + this.initialCenter, + this.initialZoom, + required this.isAnimatingNotifier, + this.dotLocationNotifier, + this.overlayOpacityNotifier, + this.overlayEntry, + this.tracks, + this.onUserZoomChange, + this.onMapTap, + this.onMarkerTap, + this.onMarkerLongPress, + this.openMapPage, + }) : assert(collection != null || entries != null); + + @override + State<GeoMap> createState() => _GeoMapState(); +} + +class _GeoMapState extends State<GeoMap> { + final Set<StreamSubscription> _subscriptions = {}; + + // as of google_maps_flutter v2.0.6, Google map initialization is blocking + // cf https://github.com/flutter/flutter/issues/28493 + // it is especially severe the first time, but still significant afterwards + // so we prevent loading it while scrolling or animating + bool _heavyMapLoaded = false; + late final ValueNotifier<ZoomedBounds> _boundsNotifier; + Fluster<GeoEntry<AvesEntry>>? _defaultMarkerCluster; + Fluster<GeoEntry<AvesEntry>>? _slowMarkerCluster; + final AChangeNotifier _clusterChangeNotifier = AChangeNotifier(); + + List<AvesEntry> get entries => widget.collection?.sortedEntries ?? widget.entries ?? []; + + // cap initial zoom to avoid a zoom change + // when toggling overlay on Google map initial state + static const double minInitialZoom = 3; + + @override + void initState() { + super.initState(); + _boundsNotifier = ValueNotifier(_initBounds()); + _registerWidget(widget); + _onCollectionChanged(); + } + + @override + void didUpdateWidget(covariant GeoMap oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _clusterChangeNotifier.dispose(); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(GeoMap widget) { + widget.collection?.addListener(_onCollectionChanged); + _subscriptions.add(widget.controller.markerLocationChanges.listen((event) => _onCollectionChanged())); + } + + void _unregisterWidget(GeoMap widget) { + widget.collection?.removeListener(_onCollectionChanged); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + final devicePixelRatio = MediaQuery.devicePixelRatioOf(context); + void onMarkerLongPress(GeoEntry<AvesEntry> geoEntry, LatLng tapLocation) => _onMarkerLongPress( + geoEntry: geoEntry, + tapLocation: tapLocation, + devicePixelRatio: devicePixelRatio, + ); + + return Selector<Settings, EntryMapStyle?>( + selector: (context, s) => s.mapStyle, + builder: (context, mapStyle, child) { + final isHeavy = mapStyle?.isHeavy ?? false; + final locale = context.locale; + Widget _buildMarkerWidget(MarkerKey<AvesEntry> key) => ImageMarker( + key: key, + count: key.count, + locale: locale, + buildThumbnailImage: (extent) => ThumbnailImage( + entry: key.entry, + extent: extent, + devicePixelRatio: devicePixelRatio, + progressive: !isHeavy, + ), + ); + bool _isMarkerImageReady(MarkerKey<AvesEntry> key) => key.entry.isThumbnailReady(extent: MapThemeData.markerImageExtent); + + Widget child = const SizedBox(); + if (mapStyle != null) { + if (mapStyle.needMobileService) { + child = mobileServices.buildMap<AvesEntry>( + controller: widget.controller, + clusterListenable: _clusterChangeNotifier, + boundsNotifier: _boundsNotifier, + style: mapStyle, + decoratorBuilder: _decorateMap, + buttonPanelBuilder: _buildButtonPanel, + markerClusterBuilder: _buildMarkerClusters, + markerWidgetBuilder: _buildMarkerWidget, + markerImageReadyChecker: _isMarkerImageReady, + dotLocationNotifier: widget.dotLocationNotifier, + overlayOpacityNotifier: widget.overlayOpacityNotifier, + overlayEntry: widget.overlayEntry, + tracks: widget.tracks, + onUserZoomChange: widget.onUserZoomChange, + onMapTap: widget.onMapTap, + onMarkerTap: _onMarkerTap, + onMarkerLongPress: onMarkerLongPress, + ); + } else { + child = EntryLeafletMap<AvesEntry>( + controller: widget.controller, + clusterListenable: _clusterChangeNotifier, + boundsNotifier: _boundsNotifier, + minZoom: 2, + maxZoom: 16, + style: mapStyle, + decoratorBuilder: _decorateMap, + buttonPanelBuilder: _buildButtonPanel, + markerClusterBuilder: _buildMarkerClusters, + markerWidgetBuilder: _buildMarkerWidget, + dotLocationNotifier: widget.dotLocationNotifier, + markerSize: Size( + MapThemeData.markerImageExtent + MapThemeData.markerOuterBorderWidth * 2, + MapThemeData.markerImageExtent + MapThemeData.markerOuterBorderWidth * 2 + MapThemeData.markerArrowSize.height, + ), + dotMarkerSize: const Size( + MapThemeData.markerDotDiameter + MapThemeData.markerOuterBorderWidth * 2, + MapThemeData.markerDotDiameter + MapThemeData.markerOuterBorderWidth * 2, + ), + overlayOpacityNotifier: widget.overlayOpacityNotifier, + overlayEntry: widget.overlayEntry, + tracks: widget.tracks, + onUserZoomChange: widget.onUserZoomChange, + onMapTap: widget.onMapTap, + onMarkerTap: _onMarkerTap, + onMarkerLongPress: onMarkerLongPress, + ); + } + } else { + final overlay = Center( + child: OverlayTextButton( + onPressed: () => MapActionDelegate.selectStyle(context), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(AIcons.layers), + const SizedBox(width: 8), + Text(context.l10n.mapStyleTooltip), + ], + ), + ), + ); + child = _decorateMap(context, overlay); + } + + final mapHeight = context.select<MapThemeData, double?>((v) => v.mapHeight); + child = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // TODO TLAD [flutter vNext] wrap into `BackdropGroup` + mapHeight != null + ? SizedBox( + height: mapHeight, + child: child, + ) + : Expanded(child: child), + SafeArea( + top: false, + bottom: false, + child: Padding( + padding: context.select<MapThemeData, EdgeInsets>((v) => v.attributionPadding), + child: Attribution(style: mapStyle), + ), + ), + ], + ); + + return AnimatedSize( + alignment: Alignment.topCenter, + curve: Curves.easeInOutCubic, + duration: ADurations.mapStyleSwitchAnimation, + child: ValueListenableBuilder<bool>( + valueListenable: widget.isAnimatingNotifier, + builder: (context, animating, child) { + if (!animating && isHeavy) { + _heavyMapLoaded = true; + } + Widget replacement = Stack( + children: [ + const MapDecorator( + child: SizedBox(), + ), + _buildButtonPanel(context), + ], + ); + if (mapHeight != null) { + replacement = SizedBox( + height: mapHeight, + child: replacement, + ); + } + return Visibility( + visible: !isHeavy || _heavyMapLoaded, + replacement: replacement, + child: child!, + ); + }, + child: child, + ), + ); + }, + ); + } + + ZoomedBounds _initBounds() { + ZoomedBounds? bounds; + + final overlayEntry = widget.overlayEntry; + if (overlayEntry != null) { + // fit map to overlaid item + final corner1 = overlayEntry.topLeft; + final corner2 = overlayEntry.bottomRight; + if (corner1 != null && corner2 != null) { + bounds = ZoomedBounds.fromPoints( + points: {corner1, corner2}, + ); + } + } + + final initialZoom = widget.initialZoom ?? settings.infoMapZoom; + if (bounds == null) { + LatLng? centerToSave; + final initialCenter = widget.initialCenter; + if (initialCenter != null) { + // fit map for specified center and user zoom + bounds = ZoomedBounds.fromPoints( + points: {initialCenter}, + collocationZoom: initialZoom, + ); + centerToSave = initialCenter; + } else { + // fit map for all located items if possible, falling back to most recent items + bounds = _initBoundsForEntries(entries: entries); + centerToSave = bounds?.projectedCenter; + } + + if (centerToSave != null) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + settings.mapDefaultCenter = centerToSave; + }); + } + } + if (bounds == null) { + // fallback to default center + var center = settings.mapDefaultCenter; + if (center == null) { + center = PointsOfInterest.wonders[Random().nextInt(PointsOfInterest.wonders.length)]; + WidgetsBinding.instance.addPostFrameCallback((_) => settings.mapDefaultCenter = center); + } + bounds = ZoomedBounds.fromPoints( + points: {center}, + collocationZoom: initialZoom, + ); + } + + return bounds.copyWith( + zoom: max(bounds.zoom, minInitialZoom), + ); + } + + ZoomedBounds? _initBoundsForEntries({required List<AvesEntry> entries, int? recentCount}) { + if (recentCount != null) { + entries = List.of(entries)..sort(AvesEntrySort.compareByDate); + entries = entries.take(recentCount).toList(); + } + + if (entries.isEmpty) return null; + + final points = entries.map((v) => v.latLng!).toSet(); + var bounds = ZoomedBounds.fromPoints( + points: points, + collocationZoom: settings.infoMapZoom, + ); + bounds = bounds.copyWith(zoom: max(minInitialZoom, bounds.zoom.floorToDouble())); + + final neededSize = bounds.toDisplaySize(); + final availableSize = widget.availableSize; + if (neededSize.width > availableSize.width || neededSize.height > availableSize.height) { + return _initBoundsForEntries(entries: entries, recentCount: (recentCount ?? 10000) ~/ 10); + } + return bounds; + } + + void _onCollectionChanged() { + _defaultMarkerCluster = _buildFluster(); + _slowMarkerCluster = null; + _clusterChangeNotifier.notify(); + } + + Fluster<GeoEntry<AvesEntry>> _buildFluster({int nodeSize = 64}) { + final markers = entries + .map((entry) { + final latLng = entry.latLng; + return latLng != null + ? GeoEntry<AvesEntry>( + entry: entry, + latitude: latLng.latitude, + longitude: latLng.longitude, + markerId: entry.uri, + ) + : null; + }) + .nonNulls + .toList(); + + return Fluster<GeoEntry<AvesEntry>>( + // we keep clustering on the whole range of zooms (including the maximum) + // to avoid collocated entries overlapping + minZoom: 0, + maxZoom: 22, + // TODO TLAD [map] derive `radius` / `extent`, from device pixel ratio and marker extent? + // (radius=120, extent=2 << 8) is equivalent to (radius=240, extent=2 << 9) + radius: 240, + extent: 2 << 9, + // node size: 64 by default, higher means faster indexing but slower search + nodeSize: nodeSize, + points: markers, + // use lambda instead of tear-off because of runtime exception when using + // `T Function(BaseCluster, double, double)` for `T Function(BaseCluster?, double?, double?)` + // ignore: unnecessary_lambdas + createCluster: (base, lng, lat) => GeoEntry<AvesEntry>.createCluster(base, lng, lat), + ); + } + + Map<MarkerKey<AvesEntry>, GeoEntry<AvesEntry>> _buildMarkerClusters() { + final bounds = _boundsNotifier.value; + final geoEntries = _defaultMarkerCluster?.clusters(bounds.boundingBox, bounds.zoom.round()) ?? []; + return Map.fromEntries(geoEntries.map((v) { + if (v.isCluster!) { + final uri = v.childMarkerId; + final entry = entries.firstWhere((v) => v.uri == uri); + return MapEntry(MarkerKey(entry, v.pointsSize), v); + } + return MapEntry(MarkerKey(v.entry!, null), v); + })); + } + + Set<AvesEntry> _getClusterEntries(GeoEntry<AvesEntry> geoEntry) { + final clusterId = geoEntry.clusterId; + if (clusterId == null) { + return {geoEntry.entry!}; + } + + var points = _defaultMarkerCluster?.points(clusterId) ?? []; + if (points.length != geoEntry.pointsSize) { + // `Fluster.points()` method does not always return all the points contained in a cluster + // the higher `nodeSize` is, the higher the chance to get all the points (i.e. as many as the cluster `pointsSize`) + _slowMarkerCluster ??= _buildFluster(nodeSize: smallestPowerOf2(entries.length).toInt()); + points = _slowMarkerCluster!.points(clusterId); + assert(points.length == geoEntry.pointsSize, 'got ${points.length}/${geoEntry.pointsSize} for geoEntry=$geoEntry'); + } + return points.map((geoEntry) => geoEntry.entry!).toSet(); + } + + void _onMarkerTap(GeoEntry<AvesEntry> geoEntry) { + final onTap = widget.onMarkerTap; + if (onTap == null) return; + + final clusterId = geoEntry.clusterId; + AvesEntry? markerEntry; + if (clusterId != null) { + final uri = geoEntry.childMarkerId; + markerEntry = entries.firstWhereOrNull((v) => v.uri == uri); + } else { + markerEntry = geoEntry.entry; + } + if (markerEntry == null) return; + + final markerLocation = LatLng(geoEntry.latitude!, geoEntry.longitude!); + onTap(markerLocation, markerEntry); + } + + Future<void> _onMarkerLongPress({ + required GeoEntry<AvesEntry> geoEntry, + required LatLng tapLocation, + required double devicePixelRatio, + }) async { + final onMarkerLongPress = widget.onMarkerLongPress; + if (onMarkerLongPress == null) return; + + final clusterEntries = _getClusterEntries(geoEntry); + final tapLocalPosition = _boundsNotifier.value.offset(tapLocation); + + AvesEntry markerEntry; + if (geoEntry.isCluster!) { + final uri = geoEntry.childMarkerId; + markerEntry = entries.firstWhere((v) => v.uri == uri); + } else { + markerEntry = geoEntry.entry!; + } + final locale = context.locale; + final markerLocation = LatLng(geoEntry.latitude!, geoEntry.longitude!); + Widget markerBuilder(BuildContext context) => ImageMarker( + count: geoEntry.pointsSize, + locale: locale, + drawArrow: false, + buildThumbnailImage: (extent) => ThumbnailImage( + entry: markerEntry, + extent: extent, + devicePixelRatio: devicePixelRatio, + ), + ); + onMarkerLongPress( + markerLocation, + markerEntry, + clusterEntries, + tapLocalPosition, + markerBuilder, + ); + } + + Widget _decorateMap(BuildContext context, Widget? child) => MapDecorator(child: child!); + + Widget _buildButtonPanel(BuildContext context) { + if (settings.useTvLayout) return const SizedBox(); + return MapButtonPanel( + controller: widget.controller, + boundsNotifier: _boundsNotifier, + openMapPage: widget.openMapPage, + ); + } +} diff --git a/lib/widgets/common/map/leaflet/latlng_tween.dart b/lib/widgets/common/map/leaflet/latlng_tween.dart new file mode 100644 index 0000000..1593c9c --- /dev/null +++ b/lib/widgets/common/map/leaflet/latlng_tween.dart @@ -0,0 +1,13 @@ +import 'package:aves/widgets/common/map/leaflet/latlng_utils.dart'; +import 'package:flutter/widgets.dart'; +import 'package:latlong2/latlong.dart'; + +class LatLngTween extends Tween<LatLng?> { + LatLngTween({ + required super.begin, + required super.end, + }); + + @override + LatLng? lerp(double t) => LatLngUtils.lerp(begin, end, t); +} diff --git a/lib/widgets/common/map/leaflet/latlng_utils.dart b/lib/widgets/common/map/leaflet/latlng_utils.dart new file mode 100644 index 0000000..adec5d1 --- /dev/null +++ b/lib/widgets/common/map/leaflet/latlng_utils.dart @@ -0,0 +1,14 @@ +import 'package:latlong2/latlong.dart'; + +class LatLngUtils { + static LatLng? lerp(LatLng? a, LatLng? b, double t) { + if (a == null && b == null) return null; + + final _a = a ?? const LatLng(0, 0); + final _b = b ?? const LatLng(0, 0); + return LatLng( + _a.latitude + (_b.latitude - _a.latitude) * t, + _a.longitude + (_b.longitude - _a.longitude) * t, + ); + } +} diff --git a/lib/widgets/common/map/leaflet/map.dart b/lib/widgets/common/map/leaflet/map.dart new file mode 100644 index 0000000..9e645dc --- /dev/null +++ b/lib/widgets/common/map/leaflet/map.dart @@ -0,0 +1,337 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/device.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:aves/widgets/common/map/leaflet/latlng_tween.dart' as llt; +import 'package:aves/widgets/common/map/leaflet/scale_layer.dart'; +import 'package:aves/widgets/common/map/leaflet/tile_layers.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class EntryLeafletMap<T> extends StatefulWidget { + final AvesMapController controller; + final Listenable clusterListenable; + final ValueNotifier<ZoomedBounds> boundsNotifier; + final double minZoom, maxZoom; + final EntryMapStyle style; + final TransitionBuilder decoratorBuilder; + final WidgetBuilder buttonPanelBuilder; + final MarkerClusterBuilder<T> markerClusterBuilder; + final MarkerWidgetBuilder<T> markerWidgetBuilder; + final ValueNotifier<LatLng?>? dotLocationNotifier; + final Size markerSize, dotMarkerSize; + final ValueNotifier<double>? overlayOpacityNotifier; + final MapOverlay? overlayEntry; + final Set<List<LatLng>>? tracks; + final UserZoomChangeCallback? onUserZoomChange; + final MapTapCallback? onMapTap; + final MarkerTapCallback<T>? onMarkerTap; + final MarkerLongPressCallback<T>? onMarkerLongPress; + + const EntryLeafletMap({ + super.key, + required this.controller, + required this.clusterListenable, + required this.boundsNotifier, + this.minZoom = 0, + this.maxZoom = 22, + required this.style, + required this.decoratorBuilder, + required this.buttonPanelBuilder, + required this.markerClusterBuilder, + required this.markerWidgetBuilder, + required this.dotLocationNotifier, + required this.markerSize, + required this.dotMarkerSize, + this.overlayOpacityNotifier, + this.overlayEntry, + this.tracks, + this.onUserZoomChange, + this.onMapTap, + this.onMarkerTap, + this.onMarkerLongPress, + }); + + @override + State<EntryLeafletMap<T>> createState() => _EntryLeafletMapState<T>(); +} + +class _EntryLeafletMapState<T> extends State<EntryLeafletMap<T>> with TickerProviderStateMixin { + final MapController _leafletMapController = MapController(); + final Set<StreamSubscription> _subscriptions = {}; + Map<MarkerKey<T>, GeoEntry<T>> _geoEntryByMarkerKey = {}; + final Debouncer _debouncer = Debouncer(delay: ADurations.mapIdleDebounceDelay); + + ValueNotifier<ZoomedBounds> get boundsNotifier => widget.boundsNotifier; + + ZoomedBounds get bounds => boundsNotifier.value; + + // duration should match the uncustomizable Google map duration + static const _cameraAnimationDuration = Duration(milliseconds: 600); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => _updateVisibleRegion()); + } + + @override + void didUpdateWidget(covariant EntryLeafletMap<T> oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(EntryLeafletMap<T> widget) { + final avesMapController = widget.controller; + _subscriptions.add(avesMapController.moveCommands.listen((event) => _moveTo(event.latLng))); + _subscriptions.add(avesMapController.zoomCommands.listen((event) => _zoomBy(event.delta))); + _subscriptions.add(avesMapController.rotationResetCommands.listen((_) => _resetRotation())); + _subscriptions.add(_leafletMapController.mapEventStream.listen((_) => _updateVisibleRegion())); + widget.clusterListenable.addListener(_updateMarkers); + widget.boundsNotifier.addListener(_onBoundsChanged); + } + + void _unregisterWidget(EntryLeafletMap<T> widget) { + widget.clusterListenable.removeListener(_updateMarkers); + widget.boundsNotifier.removeListener(_onBoundsChanged); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + widget.decoratorBuilder(context, _buildMap()), + widget.buttonPanelBuilder(context), + ], + ); + } + + Widget _buildMap() { + final markerSize = widget.markerSize; + final dotMarkerSize = widget.dotMarkerSize; + + final interactive = context.select<MapThemeData, bool>((v) => v.interactive); + + final markers = _geoEntryByMarkerKey.entries.map((kv) { + final markerKey = kv.key; + final geoEntry = kv.value; + final latLng = LatLng(geoEntry.latitude!, geoEntry.longitude!); + final onMarkerLongPress = widget.onMarkerLongPress; + final onLongPress = onMarkerLongPress != null ? Feedback.wrapForLongPress(() => onMarkerLongPress.call(geoEntry, LatLng(geoEntry.latitude!, geoEntry.longitude!)), context) : null; + return Marker( + point: latLng, + child: AGestureDetector( + onTap: () => widget.onMarkerTap?.call(geoEntry), + // marker tap handling prevents the default handling of focal zoom on double tap, + // so we reimplement the double tap gesture here + onDoubleTap: interactive ? () => _zoomBy(1, focalPoint: latLng) : null, + onLongPress: onLongPress, + // `MapInteractiveViewer` already declares a `LongPressGestureRecognizer` with the default delay (`kLongPressTimeout`), + // so this one should have a shorter delay to win in the gesture arena + longPressTimeout: Duration(milliseconds: min(settings.longPressTimeout.inMilliseconds, kLongPressTimeout.inMilliseconds)), + child: widget.markerWidgetBuilder(markerKey), + ), + width: markerSize.width, + height: markerSize.height, + alignment: Alignment.topCenter, + ); + }).toList(); + + return FlutterMap( + options: MapOptions( + initialCenter: bounds.projectedCenter, + initialZoom: bounds.zoom, + initialRotation: bounds.rotation, + minZoom: widget.minZoom, + maxZoom: widget.maxZoom, + backgroundColor: Colors.transparent, + interactionOptions: InteractionOptions( + // TODO TLAD [map] as of flutter_map v0.14.0, `doubleTapZoom` does not move when zoom is already maximal + // this could be worked around with https://github.com/fleaflet/flutter_map/pull/960 + flags: interactive ? InteractiveFlag.all : InteractiveFlag.none, + // prevent triggering multiple gestures at once (e.g. rotating a bit when mostly zooming) + enableMultiFingerGestureRace: true, + ), + onTap: (tapPosition, point) => widget.onMapTap?.call(point), + ), + mapController: _leafletMapController, + children: [ + _buildMapLayer(), + if (widget.overlayEntry != null) _buildOverlayImageLayer(), + if (widget.tracks != null) _buildTracksLayer(), + MarkerLayer( + markers: markers, + rotate: true, + alignment: Alignment.bottomCenter, + ), + NullableValueListenableBuilder<LatLng?>( + valueListenable: widget.dotLocationNotifier, + builder: (context, dotLocation, child) => MarkerLayer( + markers: [ + if (dotLocation != null) + Marker( + point: dotLocation, + child: const DotMarker(), + width: dotMarkerSize.width, + height: dotMarkerSize.height, + ) + ], + ), + ), + ScaleLayerWidget( + options: ScaleLayerOptions( + unitSystem: settings.unitSystem, + ), + ), + ], + ); + } + + Widget _buildMapLayer() { + final style = widget.style; + if (style == EntryMapStyles.osmLiberty) { + return const OsmLibertyLayer(); + } + + final urlTemplate = style.url; + if (urlTemplate != null) { + final userAgent = style.userAgent; + return TileLayer( + urlTemplate: urlTemplate, + subdomains: style.subdomains, + tileProvider: NetworkTileProvider( + headers: { + if (userAgent != null) 'User-Agent': userAgent, + }, + ), + // similar to `RetinaMode.isHighDensity` from `flutter_map`, but only rebuild for target aspect + retinaMode: MediaQuery.devicePixelRatioOf(context) > 1, + userAgentPackageName: device.userAgent, + ); + } + return const SizedBox(); + } + + Widget _buildOverlayImageLayer() { + final overlayEntry = widget.overlayEntry; + if (overlayEntry == null) return const SizedBox(); + + final corner1 = overlayEntry.topLeft; + final corner2 = overlayEntry.bottomRight; + if (corner1 == null || corner2 == null) return const SizedBox(); + + return NullableValueListenableBuilder<double>( + valueListenable: widget.overlayOpacityNotifier, + builder: (context, value, child) { + final double overlayOpacity = value ?? 1.0; + return OverlayImageLayer( + overlayImages: [ + OverlayImage( + bounds: LatLngBounds(corner1, corner2), + imageProvider: overlayEntry.imageProvider, + opacity: overlayOpacity, + ), + ], + ); + }, + ); + } + + Widget _buildTracksLayer() { + final tracks = widget.tracks; + if (tracks == null) return const SizedBox(); + + final trackColor = Theme.of(context).colorScheme.primary; + return PolylineLayer( + polylines: tracks + .map((v) => Polyline( + points: v, + strokeWidth: MapThemeData.trackWidth.toDouble(), + color: trackColor, + )) + .toList(), + ); + } + + void _onBoundsChanged() => _debouncer(_onIdle); + + void _onIdle() { + if (!mounted) return; + widget.controller.notifyIdle(bounds); + _updateMarkers(); + } + + void _updateMarkers() { + setState(() => _geoEntryByMarkerKey = widget.markerClusterBuilder()); + } + + void _updateVisibleRegion() { + final camera = _leafletMapController.camera; + final bounds = camera.visibleBounds; + boundsNotifier.value = ZoomedBounds( + sw: bounds.southWest, + ne: bounds.northEast, + zoom: camera.zoom, + rotation: camera.rotation, + ); + } + + Future<void> _resetRotation() async { + final rotation = _leafletMapController.camera.rotation; + // prevent multiple turns + final begin = (rotation.abs() % 360) * rotation.sign; + final rotationTween = Tween<double>(begin: begin, end: 0); + await _animateCamera((animation) => _leafletMapController.rotate(rotationTween.evaluate(animation))); + } + + Future<void> _zoomBy(double amount, {LatLng? focalPoint}) async { + final camera = _leafletMapController.camera; + final endZoom = (camera.zoom + amount).clamp(widget.minZoom, widget.maxZoom); + widget.onUserZoomChange?.call(endZoom); + + final center = camera.center; + final centerTween = llt.LatLngTween(begin: center, end: focalPoint ?? center); + + final zoomTween = Tween<double>(begin: camera.zoom, end: endZoom); + await _animateCamera((animation) => _leafletMapController.move(centerTween.evaluate(animation)!, zoomTween.evaluate(animation))); + } + + Future<void> _moveTo(LatLng point) async { + final camera = _leafletMapController.camera; + final centerTween = llt.LatLngTween(begin: camera.center, end: point); + await _animateCamera((animation) => _leafletMapController.move(centerTween.evaluate(animation)!, camera.zoom)); + } + + Future<void> _animateCamera(void Function(Animation<double> animation) animate) async { + final controller = AnimationController(duration: _cameraAnimationDuration, vsync: this); + final animation = CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn); + controller.addListener(() => animate(animation)); + animation.addStatusListener((status) { + if (!status.isAnimating) { + animation.dispose(); + controller.dispose(); + } + }); + await controller.forward(); + } +} diff --git a/lib/widgets/common/map/leaflet/scale_layer.dart b/lib/widgets/common/map/leaflet/scale_layer.dart new file mode 100644 index 0000000..03454b9 --- /dev/null +++ b/lib/widgets/common/map/leaflet/scale_layer.dart @@ -0,0 +1,163 @@ +import 'dart:math'; + +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; + +class ScaleLayerOptions { + final UnitSystem unitSystem; + final Widget Function(double width, String distance) builder; + + ScaleLayerOptions({ + this.unitSystem = UnitSystem.metric, + this.builder = defaultBuilder, + }); + + static Widget defaultBuilder(double width, String distance) { + return ScaleBar( + distance: distance, + width: width, + ); + } +} + +class ScaleLayerWidget extends StatelessWidget { + final ScaleLayerOptions options; + + final Distance _distanceCalculator = const Distance(); + + const ScaleLayerWidget({ + super.key, + required this.options, + }); + + static const List<double> scaleMeters = [ + 25000000, + 15000000, + 8000000, + 4000000, + 2000000, + 1000000, + 500000, + 250000, + 100000, + 50000, + 25000, + 15000, + 8000, + 4000, + 2000, + 1000, + 500, + 250, + 100, + 50, + 25, + 10, + 5, + ]; + + static const double metersInAKilometer = 1000; + static const double metersInAMile = 1609.344; + static const double metersInAFoot = 0.3048; + + @override + Widget build(BuildContext context) { + final map = MapCamera.of(context); + final center = map.center; + final latitude = center.latitude.abs(); + final level = map.zoom.round() + + (latitude > 80 + ? 4 + : latitude > 60 + ? 3 + : 2); + final scaleLevel = level.clamp(0, 20); + late final double distanceMeters; + late final String displayDistance; + switch (options.unitSystem) { + case UnitSystem.metric: + // meters + distanceMeters = scaleMeters[scaleLevel]; + displayDistance = distanceMeters >= metersInAKilometer ? '${(distanceMeters / metersInAKilometer).toStringAsFixed(0)} km' : '${distanceMeters.toStringAsFixed(0)} m'; + case UnitSystem.imperial: + if (scaleLevel < 15) { + // miles + final distanceMiles = scaleMeters[scaleLevel + 1] / 1000; + distanceMeters = distanceMiles * metersInAMile; + displayDistance = '${distanceMiles.toStringAsFixed(0)} mi'; + } else { + // feet + final distanceFeet = scaleMeters[scaleLevel - 1]; + distanceMeters = distanceFeet * metersInAFoot; + displayDistance = '${distanceFeet.toStringAsFixed(0)} ft'; + } + } + + final start = map.projectAtZoom(center); + final targetPoint = _distanceCalculator.offset(center, distanceMeters, 90); + final end = map.projectAtZoom(targetPoint); + final width = max(0, end.dx - start.dx).toDouble(); + + return options.builder(width, displayDistance); + } +} + +class ScaleBar extends StatelessWidget { + final String distance; + final double width; + + static const Color fillColor = Colors.black; + static const Color outlineColor = Colors.white; + static const double outlineWidth = .5; + static const double barThickness = 1; + + const ScaleBar({ + super.key, + required this.distance, + required this.width, + }); + + @override + Widget build(BuildContext context) { + return Container( + // keep `left` (and not `start`) because zoom buttons are kept right + // because `Google` logo on Google layers are always in the bottom left + alignment: Alignment.bottomLeft, + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + OutlinedText( + textSpans: [ + TextSpan( + text: distance, + style: const TextStyle( + color: fillColor, + fontSize: 11, + ), + ) + ], + outlineWidth: outlineWidth * 2, + outlineColor: outlineColor, + ), + Container( + height: barThickness + outlineWidth * 2, + width: width, + decoration: const BoxDecoration( + color: fillColor, + border: Border.fromBorderSide(BorderSide( + color: outlineColor, + width: outlineWidth, + )), + borderRadius: BorderRadius.all(Radius.circular(8)), + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/common/map/leaflet/tile_layers.dart b/lib/widgets/common/map/leaflet/tile_layers.dart new file mode 100644 index 0000000..916b781 --- /dev/null +++ b/lib/widgets/common/map/leaflet/tile_layers.dart @@ -0,0 +1,98 @@ +import 'dart:io' as io; + +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/map/leaflet/vector_style_reader_extra.dart'; +import 'package:flutter/material.dart'; +import 'package:vector_map_tiles/src/io/io.dart' as vmtio show Directory; // ignore: implementation_imports +import 'package:vector_map_tiles/vector_map_tiles.dart'; +import 'package:vector_tile_renderer/vector_tile_renderer.dart' as vtr; + +class OsmLibertyLayer extends StatefulWidget { + const OsmLibertyLayer({super.key}); + + @override + State<OsmLibertyLayer> createState() => _OsmLibertyLayerState(); +} + +class _OsmLibertyLayerState extends State<OsmLibertyLayer> { + late final Future<TileProviders> _tileProviderFuture; + late final Future<Style> _styleFuture; + + static const _openMapTileProviderSource = 'openmaptiles'; + + // `Americana` provides tiles, but it uses layer syntax that is not supported by the vector tile renderer. + // Full style is at 'https://americanamap.org/style.json' but it is heavy (1.0 MB, mostly for the layers). + static const _americanaTileProviderUri = 'https://tile.ourmap.us/data/v3.json'; + + // `OSM Liberty` is well supported by the vector tile renderer, but it requires an API key for the tiles. + static const _osmLibertyStyleUri = 'https://maputnik.github.io/osm-liberty/style.json'; + + // as of 2024/09/25, + // Americana provider JSON: 39.4 kB + // OSM Liberty style JSON: 48.3 kB + // OSM Liberty sprites JSON 1x: 16.6 kB + // OSM Liberty sprites PNG 1x: 30.4 kB + // OSM Liberty sprites JSON 2x: 16.6 kB + // OSM Liberty sprites PNG 2x: 82.5 kB + // -> total overhead: 233.8 kB + + @override + void initState() { + super.initState(); + + _tileProviderFuture = ExtraStyleReader.readProviderByName( + { + _openMapTileProviderSource: { + 'url': _americanaTileProviderUri, + 'type': 'vector', + } + }, + ).then(TileProviders.new); + + _styleFuture = StyleReader( + uri: _osmLibertyStyleUri, + logger: const vtr.Logger.console(), + ).readExtra(skipSources: true); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder<TileProviders>( + future: _tileProviderFuture, + builder: (context, tileProviderSnapshot) { + return FutureBuilder<Style>( + future: _styleFuture, + builder: (context, styleSnapshot) { + if (tileProviderSnapshot.hasError) return Text(tileProviderSnapshot.error.toString()); + if (styleSnapshot.hasError) return Text(styleSnapshot.error.toString()); + + final tileProviders = tileProviderSnapshot.data; + final style = styleSnapshot.data; + if (tileProviders == null || style == null) return const SizedBox(); + + return VectorTileLayer( + tileProviders: tileProviders, + theme: style.theme, + sprites: style.sprites, + // `vector` is higher quality and follows map orientation, but it is slower + layerMode: VectorTileLayerMode.raster, + cacheFolder: () async { + final cacheRoot = await storageService.getExternalCacheDirectory(); + final path = pContext.join(cacheRoot, 'map_vector_tiles'); + dynamic result; + if (vmtio.Directory == String) { + result = path; + } else if (vmtio.Directory == io.Directory) { + result = io.Directory(path); + } else { + throw Exception('vmtio.Directory type is not supported'); + } + return result; + }, + ); + }, + ); + }, + ); + } +} diff --git a/lib/widgets/common/map/leaflet/vector_style_reader_extra.dart b/lib/widgets/common/map/leaflet/vector_style_reader_extra.dart new file mode 100644 index 0000000..fa9b162 --- /dev/null +++ b/lib/widgets/common/map/leaflet/vector_style_reader_extra.dart @@ -0,0 +1,113 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:vector_map_tiles/vector_map_tiles.dart'; +import 'package:vector_tile_renderer/vector_tile_renderer.dart'; + +extension ExtraStyleReader on StyleReader { + Future<Style> readExtra({required bool skipSources}) async { + final styleText = await _httpGet(uri); + final style = await compute(jsonDecode, styleText); + if (style is! Map<String, dynamic>) { + throw _invalidStyle(uri); + } + final sources = style['sources'] as Map<String, dynamic>; + final Map<String, VectorTileProvider> providerByName = skipSources ? {} : await readProviderByName(sources); + final name = style['name'] as String?; + + final center = style['center']; + LatLng? centerPoint; + if (center is List && center.length == 2) { + centerPoint = LatLng((center[1] as num).toDouble(), (center[0] as num).toDouble()); + } + + double? zoom = (style['zoom'] as num?)?.toDouble(); + if (zoom != null && zoom < 2) { + zoom = null; + centerPoint = null; + } + + final spriteUri = style['sprite']; + SpriteStyle? sprites; + if (spriteUri is String && spriteUri.trim().isNotEmpty) { + final spriteUris = [ + _SpriteUri(json: '$spriteUri@2x.json?secure', image: '$spriteUri@2x.png?secure'), + _SpriteUri(json: '$spriteUri.json?secure', image: '$spriteUri.png?secure'), + ]; + for (final spriteUri in spriteUris) { + dynamic spritesJson; + try { + final spritesJsonText = await _httpGet(spriteUri.json); + spritesJson = await compute(jsonDecode, spritesJsonText); + } catch (e) { + logger.log(() => 'error reading sprite uri: ${spriteUri.json}'); + continue; + } + sprites = SpriteStyle(atlasProvider: () => _loadBinary(spriteUri.image), index: SpriteIndexReader(logger: logger).read(spritesJson)); + break; + } + } + return Style(theme: ThemeReader(logger: logger).read(style), providers: TileProviders(providerByName), sprites: sprites, name: name, center: centerPoint, zoom: zoom); + } + + static Future<Map<String, VectorTileProvider>> readProviderByName(Map<String, dynamic> sources) async { + final providers = <String, VectorTileProvider>{}; + final sourceEntries = sources.entries.toList(); + for (final entry in sourceEntries) { + final type = TileProviderType.values.where((e) => e.name == entry.value['type']).firstOrNull; + if (type == null) continue; + dynamic source; + var entryUrl = entry.value['url'] as String?; + if (entryUrl != null) { + final sourceUrl = entryUrl; + source = await compute(jsonDecode, await _httpGet(sourceUrl)); + if (source is! Map) { + throw _invalidStyle(sourceUrl); + } + } else { + source = entry.value; + } + final entryTiles = source['tiles']; + final maxzoom = source['maxzoom'] as int? ?? 14; + final minzoom = source['minzoom'] as int? ?? 1; + if (entryTiles is List && entryTiles.isNotEmpty) { + final tileUri = entryTiles[0] as String; + final tileUrl = tileUri; + providers[entry.key] = NetworkVectorTileProvider(type: type, urlTemplate: tileUrl, maximumZoom: maxzoom, minimumZoom: minzoom); + } + } + if (providers.isEmpty) { + throw 'Unexpected response'; + } + return providers; + } + + static String _invalidStyle(String url) => 'Uri does not appear to be a valid style: $url'; + + static Future<String> _httpGet(String url) async { + final response = await get(Uri.parse(url)); + if (response.statusCode == 200) { + return response.body; + } else { + throw 'HTTP ${response.statusCode}: ${response.body}'; + } + } + + static Future<Uint8List> _loadBinary(String url) async { + final response = await get(Uri.parse(url)); + if (response.statusCode == 200) { + return response.bodyBytes; + } else { + throw 'HTTP ${response.statusCode}: ${response.body}'; + } + } +} + +class _SpriteUri { + final String json; + final String image; + + const _SpriteUri({required this.json, required this.image}); +} diff --git a/lib/widgets/common/map/map_action_delegate.dart b/lib/widgets/common/map/map_action_delegate.dart new file mode 100644 index 0000000..d9183d7 --- /dev/null +++ b/lib/widgets/common/map/map_action_delegate.dart @@ -0,0 +1,92 @@ +import 'package:aves/geo/uri.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/add_shortcut_dialog.dart'; +import 'package:aves/widgets/dialogs/map/style_selection_dialog.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapActionDelegate with FeedbackMixin { + final AvesMapController controller; + + const MapActionDelegate(this.controller); + + bool isVisible(BuildContext context, MapAction action) { + switch (action) { + case MapAction.selectStyle: + case MapAction.openMapApp: + case MapAction.zoomIn: + case MapAction.zoomOut: + return true; + case MapAction.addShortcut: + return device.canPinShortcut && context.currentRouteName == MapPage.routeName; + } + } + + void onActionSelected(BuildContext context, MapAction action) { + switch (action) { + case MapAction.selectStyle: + selectStyle(context); + case MapAction.openMapApp: + OpenMapAppNotification().dispatch(context); + case MapAction.zoomIn: + controller.zoomBy(1); + case MapAction.zoomOut: + controller.zoomBy(-1); + case MapAction.addShortcut: + _addShortcut(context); + } + } + + static void selectStyle(BuildContext context) { + Navigator.maybeOf(context)?.push<EntryMapStyle>( + MaterialPageRoute( + settings: const RouteSettings(name: MapStyleSelectionDialog.routeName), + builder: (context) => const MapStyleSelectionDialog(), + ), + ); + } + + Future<void> _addShortcut(BuildContext context) async { + final idleBounds = controller.idleBounds; + if (idleBounds == null) { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + return; + } + + final collection = context.read<CollectionLens>(); + final result = await showDialog<(AvesEntry?, String)>( + context: context, + builder: (context) => AddShortcutDialog( + defaultName: '', + collection: collection, + ), + routeSettings: const RouteSettings(name: AddShortcutDialog.routeName), + ); + if (result == null) return; + + final (coverEntry, name) = result; + if (name.isEmpty) return; + + final geoUri = toGeoUri(idleBounds.projectedCenter, zoom: idleBounds.zoom); + await appService.pinToHomeScreen( + name, + coverEntry, + route: MapPage.routeName, + filters: collection.filters, + geoUri: geoUri, + ); + if (!device.showPinShortcutFeedback) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } + } +} + +class OpenMapAppNotification extends Notification {} diff --git a/lib/widgets/common/providers/durations_provider.dart b/lib/widgets/common/providers/durations_provider.dart new file mode 100644 index 0000000..230af4e --- /dev/null +++ b/lib/widgets/common/providers/durations_provider.dart @@ -0,0 +1,14 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:provider/provider.dart'; + +class DurationsProvider extends ProxyProvider<Settings, DurationsData> { + DurationsProvider({ + super.key, + super.child, + }) : super( + update: (context, settings, __) { + return settings.animate ? DurationsData() : DurationsData.noAnimation(); + }, + ); +} diff --git a/lib/widgets/common/providers/filter_group_provider.dart b/lib/widgets/common/providers/filter_group_provider.dart new file mode 100644 index 0000000..884eae5 --- /dev/null +++ b/lib/widgets/common/providers/filter_group_provider.dart @@ -0,0 +1,17 @@ +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class FilterGroupProvider extends ListenableProvider<FilterGroupNotifier> { + FilterGroupProvider({ + super.key, + Uri? initialValue, + super.child, + }) : super( + create: (context) => FilterGroupNotifier(initialValue), + dispose: (context, value) => value.dispose(), + ); +} + +class FilterGroupNotifier extends ValueNotifier<Uri?> { + FilterGroupNotifier(super.value); +} diff --git a/lib/widgets/common/providers/highlight_info_provider.dart b/lib/widgets/common/providers/highlight_info_provider.dart new file mode 100644 index 0000000..9deccf7 --- /dev/null +++ b/lib/widgets/common/providers/highlight_info_provider.dart @@ -0,0 +1,11 @@ +import 'package:aves/model/highlight.dart'; +import 'package:provider/provider.dart'; + +class HighlightInfoProvider extends ChangeNotifierProvider<HighlightInfo> { + HighlightInfoProvider({ + super.key, + super.child, + }) : super( + create: (context) => HighlightInfo(), + ); +} diff --git a/lib/widgets/common/providers/map_theme_provider.dart b/lib/widgets/common/providers/map_theme_provider.dart new file mode 100644 index 0000000..919837d --- /dev/null +++ b/lib/widgets/common/providers/map_theme_provider.dart @@ -0,0 +1,90 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapTheme extends StatelessWidget { + final bool interactive, showCoordinateFilter; + final MapNavigationButton navigationButton; + final Animation<double> scale; + final VisualDensity visualDensity; + final double? mapHeight; + final EdgeInsets attributionPadding; + final Widget child; + + const MapTheme({ + super.key, + required this.interactive, + required this.showCoordinateFilter, + required this.navigationButton, + this.scale = kAlwaysCompleteAnimation, + this.visualDensity = VisualDensity.standard, + this.mapHeight, + this.attributionPadding = EdgeInsets.zero, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ProxyProvider<Settings, MapThemeData>( + update: (context, settings, __) { + return MapThemeData( + interactive: interactive, + showCoordinateFilter: showCoordinateFilter, + navigationButton: navigationButton, + scale: scale, + visualDensity: visualDensity, + mapHeight: mapHeight, + attributionPadding: attributionPadding, + ); + }, + child: child, + ); + } + + static Widget heroFlightShuttleBuilder( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, + ) { + final pushing = flightDirection == HeroFlightDirection.push; + final fromMediaQuery = MediaQuery.of(fromHeroContext); + final toMediaQuery = MediaQuery.of(toHeroContext); + final fromRenderBox = fromHeroContext.findRenderObject()! as RenderBox; + final toRenderBox = toHeroContext.findRenderObject()! as RenderBox; + final fromTheme = fromHeroContext.read<MapThemeData>(); + final toTheme = toHeroContext.read<MapThemeData>(); + + return DefaultTextStyle( + style: DefaultTextStyle.of(toHeroContext).style, + child: AnimatedBuilder( + animation: animation, + builder: (context, child) { + final t = pushing ? animation.value : 1 - animation.value; + return MapTheme( + interactive: false, + showCoordinateFilter: false, + navigationButton: toTheme.navigationButton, + visualDensity: VisualDensity.lerp(fromTheme.visualDensity, toTheme.visualDensity, t), + child: MediaQuery( + data: toMediaQuery.copyWith( + padding: EdgeInsets.lerp(fromMediaQuery.padding, toMediaQuery.padding, t), + viewPadding: EdgeInsets.lerp(fromMediaQuery.viewPadding, toMediaQuery.viewPadding, t), + ), + child: Align( + alignment: Alignment.topCenter, + child: SizedBox.fromSize( + size: Size.lerp(fromRenderBox.size, toRenderBox.size, t), + child: child, + ), + ), + ), + ); + }, + child: toHeroContext.widget, + ), + ); + } +} diff --git a/lib/widgets/common/providers/media_query_data_provider.dart b/lib/widgets/common/providers/media_query_data_provider.dart new file mode 100644 index 0000000..742c775 --- /dev/null +++ b/lib/widgets/common/providers/media_query_data_provider.dart @@ -0,0 +1,21 @@ +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class MediaQueryDataProvider extends StatelessWidget { + final MediaQueryData? value; + final Widget child; + + const MediaQueryDataProvider({ + super.key, + this.value, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return Provider<MediaQueryData>.value( + value: value ?? MediaQuery.of(context), + child: child, + ); + } +} diff --git a/lib/widgets/common/providers/query_provider.dart b/lib/widgets/common/providers/query_provider.dart new file mode 100644 index 0000000..8c05061 --- /dev/null +++ b/lib/widgets/common/providers/query_provider.dart @@ -0,0 +1,27 @@ +import 'package:aves/model/query.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class QueryProvider extends StatelessWidget { + final bool startEnabled; + final String? initialQuery; + final Widget child; + + const QueryProvider({ + super.key, + this.startEnabled = false, + this.initialQuery, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider<Query>( + create: (context) => Query( + enabled: startEnabled, + initialValue: initialQuery, + ), + child: child, + ); + } +} diff --git a/lib/widgets/common/providers/selection_provider.dart b/lib/widgets/common/providers/selection_provider.dart new file mode 100644 index 0000000..b1bd9b6 --- /dev/null +++ b/lib/widgets/common/providers/selection_provider.dart @@ -0,0 +1,20 @@ +import 'package:aves/model/selection.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class SelectionProvider<T> extends StatelessWidget { + final Widget child; + + const SelectionProvider({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider<Selection<T>>( + create: (context) => Selection<T>(), + child: child, + ); + } +} diff --git a/lib/widgets/common/providers/tile_extent_controller_provider.dart b/lib/widgets/common/providers/tile_extent_controller_provider.dart new file mode 100644 index 0000000..0a5d45b --- /dev/null +++ b/lib/widgets/common/providers/tile_extent_controller_provider.dart @@ -0,0 +1,24 @@ +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class TileExtentControllerProvider extends StatelessWidget { + final TileExtentController controller; + final Widget child; + + const TileExtentControllerProvider({ + super.key, + required this.controller, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) => ProxyProvider0<TileExtentController>( + update: (context, __) => controller..setViewportSize(constraints.biggest), + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/providers/viewer_entry_provider.dart b/lib/widgets/common/providers/viewer_entry_provider.dart new file mode 100644 index 0000000..ca3ee34 --- /dev/null +++ b/lib/widgets/common/providers/viewer_entry_provider.dart @@ -0,0 +1,17 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class ViewerEntryProvider extends ListenableProvider<ViewerEntryNotifier> { + ViewerEntryProvider({ + super.key, + super.child, + }) : super( + create: (context) => ViewerEntryNotifier(null), + dispose: (context, value) => value.dispose(), + ); +} + +class ViewerEntryNotifier extends ValueNotifier<AvesEntry?> { + ViewerEntryNotifier(super.value); +} diff --git a/lib/widgets/common/search/delegate.dart b/lib/widgets/common/search/delegate.dart new file mode 100644 index 0000000..e48a21f --- /dev/null +++ b/lib/widgets/common/search/delegate.dart @@ -0,0 +1,150 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:leak_tracker/leak_tracker.dart'; +import 'package:provider/provider.dart'; + +abstract class AvesSearchDelegate extends SearchDelegate { + final String routeName; + final bool canPop; + final TextEditingController queryTextController = TextEditingController(); + final ValueNotifier<SearchBody?> currentBodyNotifier = ValueNotifier(null); + + AvesSearchDelegate({ + required this.routeName, + this.canPop = true, + String? initialQuery, + required super.searchFieldLabel, + required super.searchFieldStyle, + }) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AvesSearchDelegate', + object: this, + ); + } + query = initialQuery ?? ''; + } + + @override + Widget? buildLeading(BuildContext context) { + if (settings.useTvLayout) { + return const Icon(AIcons.search); + } + + // use a property instead of checking `Navigator.canPop(context)` + // because the navigator state changes as soon as we press back + // so the leading may mistakenly switch to the close button + final animate = context.read<Settings>().animate; + return canPop + ? IconButton( + icon: animate + ? AnimatedIcon( + icon: AnimatedIcons.menu_arrow, + progress: transitionAnimation, + ) + : const Icon(Icons.arrow_back), + onPressed: () => goBack(context), + tooltip: MaterialLocalizations.of(context).backButtonTooltip, + ) + : const CloseButton( + onPressed: SystemNavigator.pop, + ); + } + + @override + List<Widget>? buildActions(BuildContext context) { + return [ + if (!settings.useTvLayout && query.isNotEmpty) + IconButton( + icon: const Icon(AIcons.clear), + onPressed: () { + query = ''; + showSuggestions(context); + }, + tooltip: context.l10n.clearTooltip, + ), + ]; + } + + void goBack(BuildContext context) { + clean(); + Navigator.maybeOf(context)?.pop(); + } + + void clean() { + currentBody = null; + searchFieldFocusNode?.unfocus(); + } + + // adapted from Flutter `SearchDelegate` in `/material/search.dart` + + @override + void showResults(BuildContext context) { + if (settings.useTvLayout) { + suggestionsScrollController?.jumpTo(0); + WidgetsBinding.instance.addPostFrameCallback((_) { + suggestionsFocusNode?.requestFocus(); + FocusScope.of(context).nextFocus(); + }); + } else { + searchFieldFocusNode?.unfocus(); + currentBody = SearchBody.results; + } + } + + @override + void showSuggestions(BuildContext context) { + assert(searchFieldFocusNode != null, '_focusNode must be set by route before showSuggestions is called.'); + searchFieldFocusNode!.requestFocus(); + currentBody = SearchBody.suggestions; + } + + @override + Animation<double> get transitionAnimation => proxyAnimation; + + FocusNode? searchFieldFocusNode; + + FocusNode? get suggestionsFocusNode => null; + + ScrollController? get suggestionsScrollController => null; + + final ProxyAnimation proxyAnimation = ProxyAnimation(kAlwaysDismissedAnimation); + + @override + String get query => queryTextController.text; + + @override + set query(String value) { + queryTextController.text = value; + if (queryTextController.text.isNotEmpty) { + queryTextController.selection = TextSelection.fromPosition(TextPosition(offset: queryTextController.text.length)); + } + } + + SearchBody? get currentBody => currentBodyNotifier.value; + + set currentBody(SearchBody? value) { + currentBodyNotifier.value = value; + } + + SearchPageRoute? route; + + /// Releases the resources. + @override + @mustCallSuper + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + currentBodyNotifier.dispose(); + queryTextController.dispose(); + proxyAnimation.parent = null; + super.dispose(); + } +} diff --git a/lib/widgets/common/search/page.dart b/lib/widgets/common/search/page.dart new file mode 100644 index 0000000..7f218e6 --- /dev/null +++ b/lib/widgets/common/search/page.dart @@ -0,0 +1,173 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/double_back.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/common/search/delegate.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class SearchPage extends StatefulWidget { + static const routeName = '/search'; + + final AvesSearchDelegate delegate; + final Animation<double> animation; + + const SearchPage({ + super.key, + required this.delegate, + required this.animation, + }); + + @override + State<SearchPage> createState() => _SearchPageState(); +} + +class _SearchPageState extends State<SearchPage> { + final Debouncer _debouncer = Debouncer(delay: ADurations.searchDebounceDelay); + final FocusNode _searchFieldFocusNode = FocusNode(); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + widget.animation.addStatusListener(_onAnimationStatusChanged); + _searchFieldFocusNode.addListener(_onFocusChanged); + } + + @override + void didUpdateWidget(covariant SearchPage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.delegate != widget.delegate) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + widget.animation.removeStatusListener(_onAnimationStatusChanged); + _searchFieldFocusNode.dispose(); + super.dispose(); + } + + void _registerWidget(SearchPage widget) { + widget.delegate.queryTextController.addListener(_onQueryChanged); + widget.delegate.currentBodyNotifier.addListener(_onSearchBodyChanged); + widget.delegate.searchFieldFocusNode = _searchFieldFocusNode; + } + + void _unregisterWidget(SearchPage widget) { + widget.delegate.queryTextController.removeListener(_onQueryChanged); + widget.delegate.currentBodyNotifier.removeListener(_onSearchBodyChanged); + widget.delegate.searchFieldFocusNode = null; + } + + void _onAnimationStatusChanged(AnimationStatus status) { + if (!status.isCompleted) { + return; + } + widget.animation.removeStatusListener(_onAnimationStatusChanged); + Future.delayed(ADurations.pageTransitionLoose * timeDilation).then((_) { + if (!mounted) return; + _searchFieldFocusNode.requestFocus(); + }); + } + + void _onFocusChanged() { + if (_searchFieldFocusNode.hasFocus && widget.delegate.currentBody != SearchBody.suggestions) { + widget.delegate.showSuggestions(context); + } + } + + void _onQueryChanged() { + _debouncer(() { + if (!mounted) return; + // rebuild ourselves because query changed. + setState(() {}); + }); + } + + void _onSearchBodyChanged() { + setState(() { + // rebuild ourselves because search body changed. + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + Widget leading = Center(child: widget.delegate.buildLeading(context)); + Widget title = DefaultTextStyle.merge( + style: const TextStyle(fontFeatures: [FontFeature.disable('smcp')]), + child: TextField( + controller: widget.delegate.queryTextController, + focusNode: _searchFieldFocusNode, + decoration: InputDecoration( + border: InputBorder.none, + hintText: widget.delegate.searchFieldLabel, + hintStyle: theme.inputDecorationTheme.hintStyle, + ), + textInputAction: TextInputAction.search, + style: Themes.searchFieldStyle(context), + onSubmitted: (_) => widget.delegate.showResults(context), + ), + ); + Widget body; + switch (widget.delegate.currentBody) { + case SearchBody.suggestions: + body = KeyedSubtree( + key: const ValueKey<SearchBody>(SearchBody.suggestions), + child: widget.delegate.buildSuggestions(context), + ); + case SearchBody.results: + body = KeyedSubtree( + key: const ValueKey<SearchBody>(SearchBody.results), + child: widget.delegate.buildResults(context), + ); + case null: + body = const SizedBox(); + } + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + leading = Hero( + tag: AvesAppBar.leadingHeroTag, + transitionOnUserGestures: true, + child: leading, + ); + title = Hero( + tag: AvesAppBar.titleHeroTag, + transitionOnUserGestures: true, + child: title, + ); + body = AnimatedSwitcher( + duration: ADurations.searchBodyTransition, + child: body, + ); + } + + return AvesScaffold( + appBar: AppBar( + leading: leading, + title: title, + actions: widget.delegate.buildActions(context), + ), + body: AvesPopScope( + handlers: [ + tvNavigationPopHandler, + doubleBackPopHandler, + ], + child: body, + ), + ); + } +} diff --git a/lib/widgets/common/search/route.dart b/lib/widgets/common/search/route.dart new file mode 100644 index 0000000..e69a1b8 --- /dev/null +++ b/lib/widgets/common/search/route.dart @@ -0,0 +1,90 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/search/delegate.dart'; +import 'package:aves/widgets/common/search/page.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +// adapted from Flutter `_SearchBody` in `/material/search.dart` +enum SearchBody { suggestions, results } + +// adapted from Flutter `_SearchPageRoute` in `/material/search.dart` +class SearchPageRoute<T> extends PageRoute<T> { + SearchPageRoute({ + required this.delegate, + }) : super(settings: RouteSettings(name: delegate.routeName)) { + assert( + delegate.route == null, + 'The ${delegate.runtimeType} instance is currently used by another active ' + 'search. Please close that search by calling close() on the SearchDelegate ' + 'before opening another search with the same delegate instance.', + ); + delegate.route = this; + } + + @override + void dispose() { + // `delegate` is always created by the caller at route creation time, + // so it should always be disposed when the route is disposed + delegate.dispose(); + super.dispose(); + } + + final AvesSearchDelegate delegate; + + @override + Color? get barrierColor => null; + + @override + String? get barrierLabel => null; + + @override + Duration get transitionDuration => const Duration(milliseconds: 300); + + @override + bool get maintainState => false; + + @override + Widget buildTransitions( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + Widget child, + ) { + // a simple fade is usually more fitting for a search page, + // instead of the `pageTransitionsTheme` used by the rest of the app + final animate = context.read<Settings>().animate; + return animate + ? FadeTransition( + opacity: animation, + child: child, + ) + : child; + } + + @override + Animation<double> createAnimation() { + final Animation<double> animation = super.createAnimation(); + delegate.proxyAnimation.parent = animation; + return animation; + } + + @override + Widget buildPage( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + return SearchPage( + delegate: delegate, + animation: animation, + ); + } + + @override + void didComplete(T? result) { + super.didComplete(result); + assert(delegate.route == this); + delegate.route = null; + delegate.currentBody = null; + } +} diff --git a/lib/widgets/common/thumbnail/decorated.dart b/lib/widgets/common/thumbnail/decorated.dart new file mode 100644 index 0000000..f4b4190 --- /dev/null +++ b/lib/widgets/common/thumbnail/decorated.dart @@ -0,0 +1,92 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/common/grid/overlay.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout_builder.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:aves/widgets/common/thumbnail/notifications.dart'; +import 'package:aves/widgets/common/thumbnail/overlay.dart'; +import 'package:flutter/material.dart'; + +class DecoratedThumbnail extends StatelessWidget { + final AvesEntry entry; + final double tileExtent; + final ValueNotifier<bool>? cancellableNotifier; + final bool isMosaic, selectable, highlightable; + final Object? Function()? heroTagger; + final HeroPlaceholderBuilder? heroPlaceholderBuilder; + final TransitionBuilder? imageDecorator; + + static Color borderColor(BuildContext context) => Theme.of(context).dividerColor; + + static double borderWidth(BuildContext context) => AvesBorder.straightBorderWidth(context); + + const DecoratedThumbnail({ + super.key, + required this.entry, + required this.tileExtent, + this.cancellableNotifier, + this.isMosaic = false, + this.selectable = true, + this.highlightable = true, + this.heroTagger, + this.heroPlaceholderBuilder, + this.imageDecorator, + }); + + @override + Widget build(BuildContext context) { + final double thumbnailHeight = tileExtent; + final double thumbnailWidth; + if (isMosaic) { + thumbnailWidth = thumbnailHeight * + entry.displayAspectRatio.clamp( + MosaicSectionLayoutBuilder.minThumbnailAspectRatio, + MosaicSectionLayoutBuilder.maxThumbnailAspectRatio, + ); + } else { + thumbnailWidth = tileExtent; + } + + Widget child = ThumbnailImage( + entry: entry, + extent: tileExtent, + devicePixelRatio: MediaQuery.devicePixelRatioOf(context), + isMosaic: isMosaic, + cancellableNotifier: cancellableNotifier, + heroTag: heroTagger?.call(), + heroPlaceholderBuilder: heroPlaceholderBuilder, + ); + + child = Stack( + fit: StackFit.passthrough, + children: [ + imageDecorator?.call(context, child) ?? child, + ThumbnailEntryOverlay(entry: entry), + if (selectable) ...[ + GridItemSelectionOverlay<AvesEntry>( + item: entry, + padding: const EdgeInsets.all(2), + ), + ThumbnailZoomOverlay( + onZoom: () => OpenViewerNotification(entry).dispatch(context), + ), + ], + if (highlightable) ThumbnailHighlightOverlay(entry: entry), + ], + ); + + return Container( + // `decoration` with sub logical pixel width yields scintillating borders + // so we use `foregroundDecoration` instead + foregroundDecoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: borderColor(context), + width: borderWidth(context), + )), + ), + width: thumbnailWidth, + height: thumbnailHeight, + child: child, + ); + } +} diff --git a/lib/widgets/common/thumbnail/error.dart b/lib/widgets/common/thumbnail/error.dart new file mode 100644 index 0000000..9acc11b --- /dev/null +++ b/lib/widgets/common/thumbnail/error.dart @@ -0,0 +1,77 @@ +import 'dart:io'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/mime_utils.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class ErrorThumbnail extends StatefulWidget { + final AvesEntry entry; + final double extent; + + const ErrorThumbnail({ + super.key, + required this.entry, + required this.extent, + }); + + @override + State<ErrorThumbnail> createState() => _ErrorThumbnailState(); +} + +class _ErrorThumbnailState extends State<ErrorThumbnail> { + late Future<bool> _exists; + + AvesEntry get entry => widget.entry; + + double get extent => widget.extent; + + @override + void initState() { + super.initState(); + final path = entry.trashDetails?.path ?? entry.path; + _exists = path != null ? File(path).exists() : SynchronousFuture(true); + } + + @override + Widget build(BuildContext context) { + final color = Themes.backgroundTextColor(context); + return FutureBuilder<bool>( + future: _exists, + builder: (context, snapshot) { + Widget child; + if (snapshot.connectionState != ConnectionState.done) { + child = const SizedBox(); + } else { + final exists = snapshot.data!; + child = exists + ? LayoutBuilder(builder: (context, constraints) { + final fontSize = min(extent, constraints.biggest.width) / 5; + return Text( + MimeUtils.displayType(entry.mimeType), + style: TextStyle( + color: color, + fontSize: fontSize, + ), + textAlign: TextAlign.center, + ); + }) + : Icon( + AIcons.broken, + size: extent / 2, + color: color, + ); + } + return Container( + alignment: Alignment.center, + color: Themes.firstLayerColor(context), + width: extent, + height: extent, + child: child, + ); + }); + } +} diff --git a/lib/widgets/common/thumbnail/image.dart b/lib/widgets/common/thumbnail/image.dart new file mode 100644 index 0000000..db1a8a2 --- /dev/null +++ b/lib/widgets/common/thumbnail/image.dart @@ -0,0 +1,352 @@ +import 'dart:math'; + +import 'package:aves/image_providers/thumbnail_provider.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/enums/entry_background.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/fx/checkered_decoration.dart'; +import 'package:aves/widgets/common/fx/transition_image.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout_builder.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/common/thumbnail/error.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ThumbnailImage extends StatefulWidget { + final AvesEntry entry; + final double extent, devicePixelRatio; + final bool isMosaic, progressive; + final BoxFit? fit; + final bool showLoadingBackground; + final ValueNotifier<bool>? cancellableNotifier; + final Object? heroTag; + final HeroPlaceholderBuilder? heroPlaceholderBuilder; + + const ThumbnailImage({ + super.key, + required this.entry, + required this.extent, + required this.devicePixelRatio, + this.progressive = true, + this.isMosaic = false, + this.fit, + this.showLoadingBackground = true, + this.cancellableNotifier, + this.heroTag, + this.heroPlaceholderBuilder, + }); + + @override + State<ThumbnailImage> createState() => _ThumbnailImageState(); + + static Color computeLoadingBackgroundColor(int hashCode, Brightness brightness) { + var rgb = 0x30 + hashCode % 0x20; + if (brightness == Brightness.light) { + rgb = 0xFF - rgb; + } + return Color.fromARGB(0xFF, rgb, rgb, rgb); + } +} + +class _ThumbnailImageState extends State<ThumbnailImage> { + final _providers = <_ConditionalImageProvider>[]; + _ProviderStream? _currentProviderStream; + ImageInfo? _lastImageInfo; + Object? _lastException; + late final ImageStreamListener _streamListener; + + AvesEntry get entry => widget.entry; + + double get extent => widget.extent; + + bool get isMosaic => widget.isMosaic; + + @override + void initState() { + super.initState(); + _streamListener = ImageStreamListener(_onImageLoad, onError: _onError); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant ThumbnailImage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.entry != entry) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(ThumbnailImage widget) { + // TODO TLAD [leak] `widget.entry.visualChangeNotifier` + widget.entry.visualChangeNotifier.addListener(_onVisualChanged); + _initProvider(); + } + + void _unregisterWidget(ThumbnailImage widget) { + widget.entry.visualChangeNotifier.removeListener(_onVisualChanged); + _pauseProvider(); + _currentProviderStream?.stopListening(); + _currentProviderStream = null; + _replaceImage(null); + } + + void _initProvider() { + if (!entry.isDecodingSupported) return; + + _lastException = null; + _providers.clear(); + + final highQuality = entry.getThumbnail(extent: extent); + ThumbnailProvider? lowQuality; + if (widget.progressive && !entry.isSvg) { + if (entry.isVideo) { + // previously fetched thumbnail + final cached = entry.bestCachedThumbnail; + final lowQualityExtent = cached.key.extent; + if (lowQualityExtent > 0 && lowQualityExtent != extent) { + lowQuality = cached; + } + } else { + // default platform thumbnail + lowQuality = entry.getThumbnail(); + } + } + _providers.addAll([ + if (lowQuality != null) + _ConditionalImageProvider( + lowQuality, + ), + _ConditionalImageProvider( + highQuality, + _needSizedProvider, + ), + ]); + _loadNextProvider(); + } + + void _loadNextProvider([ImageInfo? imageInfo]) { + final nextIndex = _currentProviderStream == null ? 0 : (_providers.indexOf(_currentProviderStream!.provider) + 1); + if (nextIndex < _providers.length) { + final provider = _providers[nextIndex]; + if (provider.predicate?.call(imageInfo) ?? true) { + _currentProviderStream?.stopListening(); + _currentProviderStream = _ProviderStream(provider, _streamListener); + _currentProviderStream!.startListening(); + } + } + } + + void _onImageLoad(ImageInfo imageInfo, bool synchronousCall) { + _replaceImage(imageInfo); + _loadNextProvider(imageInfo); + } + + void _replaceImage(ImageInfo? imageInfo) { + _lastImageInfo?.dispose(); + _lastImageInfo = imageInfo; + if (imageInfo != null) { + setState(() {}); + } + } + + void _onError(Object exception, StackTrace? stackTrace) { + if (!mounted) return; + setState(() => _lastException = exception); + } + + bool _needSizedProvider(ImageInfo? currentImageInfo) { + if (currentImageInfo == null) return true; + final currentImage = currentImageInfo.image; + final sizedThreshold = extent * widget.devicePixelRatio; + return sizedThreshold > min(currentImage.width, currentImage.height); + } + + void _pauseProvider() async { + if (widget.cancellableNotifier?.value ?? false) { + final key = await _currentProviderStream?.provider.provider.obtainKey(ImageConfiguration.empty); + if (key is ThumbnailProviderKey) { + mediaFetchService.cancelThumbnail(key); + } + } + } + + Color? _loadingBackgroundColor; + + Color loadingBackgroundColor(BuildContext context) { + _loadingBackgroundColor ??= ThumbnailImage.computeLoadingBackgroundColor(entry.uri.hashCode, Theme.of(context).brightness); + return _loadingBackgroundColor!; + } + + @override + Widget build(BuildContext context) { + final animate = context.select<Settings, bool>((v) => v.animate); + if (!entry.isDecodingSupported || _lastException != null) { + return _buildError(context, animate); + } + + // use `RawImage` instead of `Image`, using `ImageInfo` to check dimensions + // and have more control when chaining image providers + + final thumbnailHeight = extent; + final double thumbnailWidth; + if (isMosaic) { + thumbnailWidth = thumbnailHeight * + entry.displayAspectRatio.clamp( + MosaicSectionLayoutBuilder.minThumbnailAspectRatio, + MosaicSectionLayoutBuilder.maxThumbnailAspectRatio, + ); + } else { + thumbnailWidth = extent; + } + final canHaveAlpha = entry.canHaveAlpha; + + final fit = widget.fit ?? (entry.isSvg ? BoxFit.contain : BoxFit.cover); + final imageInfo = _lastImageInfo; + Widget image = imageInfo == null + ? Container( + color: widget.showLoadingBackground ? loadingBackgroundColor(context) : Colors.transparent, + width: thumbnailWidth, + height: thumbnailHeight, + ) + : Selector<Settings, EntryBackground>( + selector: (context, s) => s.imageBackground, + builder: (context, background, child) { + // avoid background color filter or layer when the entry cannot be transparent + final backgroundColor = canHaveAlpha && background.isColor ? background.color : null; + + if (canHaveAlpha && background == EntryBackground.checkered) { + return LayoutBuilder( + builder: (context, constraints) { + final availableSize = constraints.biggest; + final fitSize = applyBoxFit(fit, entry.displaySize, availableSize).destination; + final offset = (fitSize / 2 - availableSize / 2) as Offset; + final child = CustomPaint( + painter: CheckeredPainter(checkSize: extent / 8, offset: offset), + child: RawImage( + image: imageInfo.image, + debugImageLabel: imageInfo.debugLabel, + width: fitSize.width, + height: fitSize.height, + scale: imageInfo.scale, + fit: BoxFit.cover, + ), + ); + // the thumbnail is centered for correct decoration sizing + // when constraints are tight during hero animation + return constraints.isTight ? Center(child: child) : child; + }, + ); + } + + return RawImage( + image: imageInfo.image, + debugImageLabel: imageInfo.debugLabel, + width: thumbnailWidth, + height: thumbnailHeight, + scale: imageInfo.scale, + color: backgroundColor, + colorBlendMode: BlendMode.dstOver, + fit: fit, + ); + }, + ); + + final heroTag = widget.heroTag; + if (animate && heroTag != null) { + final background = settings.imageBackground; + final backgroundColor = background.isColor ? background.color : null; + image = Hero( + tag: heroTag, + flightShuttleBuilder: (flightContext, animation, flightDirection, fromHeroContext, toHeroContext) { + // as of Flutter v3.27.0-0.1.pre, the flight `animation` is incorrect when diverting a pop: + // - diverting a push (t = 0 -> 1) with a pop (t = 1 -> 0) works as expected (t = 0 -> [0,1] -> 0) + // - diverting a pop (t = 1 -> 0) with a push (t = 0 -> 1) finishes the pop (t = 1 -> [0,1] -> 0) instead of diverting (t = 1 -> [0,1] -> 1) + Widget child = TransitionImage( + image: entry.bestCachedThumbnail, + animation: animation, + thumbnailFit: BoxFit.cover, + viewerFit: BoxFit.contain, + background: backgroundColor, + ); + if (!settings.viewerUseCutout) { + child = SafeCutoutArea( + animation: animation, + child: child, + ); + } + return child; + }, + placeholderBuilder: widget.heroPlaceholderBuilder, + transitionOnUserGestures: true, + child: image, + ); + } + + return image; + } + + Widget _buildError(BuildContext context, bool animate) { + Widget child = ErrorThumbnail( + entry: entry, + extent: extent, + ); + + final heroTag = widget.heroTag; + if (animate && heroTag != null) { + child = Hero( + tag: heroTag, + flightShuttleBuilder: (flightContext, animation, flightDirection, fromHeroContext, toHeroContext) { + return MediaQueryDataProvider( + child: DefaultTextStyle( + style: DefaultTextStyle.of(toHeroContext).style, + child: toHeroContext.widget, + ), + ); + }, + transitionOnUserGestures: true, + child: child, + ); + } + + return child; + } + + // when the entry image itself changed (e.g. after rotation) + void _onVisualChanged() async { + // rebuild to refresh the thumbnails + _pauseProvider(); + _initProvider(); + setState(() {}); + } +} + +class _ConditionalImageProvider { + final ImageProvider provider; + final bool Function(ImageInfo?)? predicate; + + const _ConditionalImageProvider(this.provider, [this.predicate]); +} + +class _ProviderStream { + final _ConditionalImageProvider provider; + final ImageStream _stream; + final ImageStreamListener listener; + + _ProviderStream(this.provider, this.listener) : _stream = provider.provider.resolve(ImageConfiguration.empty); + + void startListening() => _stream.addListener(listener); + + void stopListening() => _stream.removeListener(listener); +} diff --git a/lib/widgets/common/thumbnail/notifications.dart b/lib/widgets/common/thumbnail/notifications.dart new file mode 100644 index 0000000..d5edca4 --- /dev/null +++ b/lib/widgets/common/thumbnail/notifications.dart @@ -0,0 +1,9 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class OpenViewerNotification extends Notification { + final AvesEntry entry; + + const OpenViewerNotification(this.entry); +} diff --git a/lib/widgets/common/thumbnail/overlay.dart b/lib/widgets/common/thumbnail/overlay.dart new file mode 100644 index 0000000..44ffe84 --- /dev/null +++ b/lib/widgets/common/thumbnail/overlay.dart @@ -0,0 +1,121 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/fx/sweeper.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ThumbnailEntryOverlay extends StatelessWidget { + final AvesEntry entry; + + const ThumbnailEntryOverlay({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + final iconBuilder = context.select<GridThemeData, GridThemeIconBuilder>((t) => t.iconBuilder); + final children = iconBuilder(context, entry); + if (children.isEmpty) return const SizedBox(); + return Align( + alignment: AlignmentDirectional.bottomStart, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: children, + ), + ); + } +} + +class ThumbnailHighlightOverlay extends StatefulWidget { + final AvesEntry entry; + + const ThumbnailHighlightOverlay({ + super.key, + required this.entry, + }); + + @override + State<ThumbnailHighlightOverlay> createState() => _ThumbnailHighlightOverlayState(); +} + +class _ThumbnailHighlightOverlayState extends State<ThumbnailHighlightOverlay> { + final ValueNotifier<bool> _highlightedNotifier = ValueNotifier(false); + + AvesEntry get entry => widget.entry; + + static const startAngle = pi * -3 / 4; + + @override + void dispose() { + _highlightedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final highlightInfo = context.watch<HighlightInfo>(); + _highlightedNotifier.value = highlightInfo.contains(entry); + return Sweeper( + builder: (context) => Container( + decoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: Theme.of(context).colorScheme.primary, + width: context.select<GridThemeData, double>((t) => t.highlightBorderWidth), + )), + ), + ), + toggledNotifier: _highlightedNotifier, + startAngle: startAngle, + centerSweep: false, + onSweepEnd: highlightInfo.clear, + ); + } +} + +class ThumbnailZoomOverlay extends StatelessWidget { + final VoidCallback? onZoom; + + const ThumbnailZoomOverlay({ + super.key, + this.onZoom, + }); + + static const alignment = AlignmentDirectional.bottomEnd; + + @override + Widget build(BuildContext context) { + final duration = context.select<DurationsData, Duration>((v) => v.formTransition); + final isSelecting = context.select<Selection<AvesEntry>, bool>((selection) => selection.isSelecting); + final interactiveDimension = context.select<GridThemeData, double>((t) => t.interactiveDimension); + return AnimatedSwitcher( + duration: duration, + child: isSelecting + ? Align( + alignment: alignment, + child: GestureDetector( + onTap: onZoom, + child: Container( + alignment: alignment, + padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 2), + width: interactiveDimension, + height: interactiveDimension, + child: Icon( + AIcons.showFullscreenArrows, + size: context.select<GridThemeData, double>((t) => t.iconSize), + color: Colors.white70, + ), + ), + ), + ) + : const SizedBox(), + ); + } +} diff --git a/lib/widgets/common/thumbnail/scroller.dart b/lib/widgets/common/thumbnail/scroller.dart new file mode 100644 index 0000000..c0adf63 --- /dev/null +++ b/lib/widgets/common/thumbnail/scroller.dart @@ -0,0 +1,206 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/behaviour/known_extent_scroll_physics.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves/widgets/common/thumbnail/decorated.dart'; +import 'package:flutter/material.dart'; + +class ThumbnailScroller extends StatefulWidget { + final double availableWidth; + final int entryCount; + final AvesEntry? Function(int index) entryBuilder; + final ValueNotifier<int?> indexNotifier; + final void Function(int index)? onTap; + final Object? Function(AvesEntry entry)? heroTagger; + final bool scrollable, highlightable, showLocation; + + const ThumbnailScroller({ + super.key, + required this.availableWidth, + required this.entryCount, + required this.entryBuilder, + required this.indexNotifier, + this.onTap, + this.heroTagger, + this.highlightable = false, + this.showLocation = true, + this.scrollable = true, + }); + + @override + State<ThumbnailScroller> createState() => _ThumbnailScrollerState(); + + static double get preferredHeight => _ThumbnailScrollerState.thumbnailExtent; +} + +class _ThumbnailScrollerState extends State<ThumbnailScroller> { + final ValueNotifier<bool> _cancellableNotifier = ValueNotifier(true); + late ScrollController _scrollController; + bool _isAnimating = false, _isScrolling = false; + + static const double thumbnailExtent = 48; + static const double separatorWidth = 2; + static const double itemExtent = thumbnailExtent + separatorWidth; + + int get entryCount => widget.entryCount; + + ValueNotifier<int?> get indexNotifier => widget.indexNotifier; + + bool get scrollable => widget.scrollable; + + static double widthFor(int pageCount) => pageCount == 0 ? 0 : pageCount * thumbnailExtent + (pageCount - 1) * separatorWidth; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant ThumbnailScroller oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.indexNotifier != widget.indexNotifier) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + _cancellableNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(ThumbnailScroller widget) { + final scrollOffset = indexToScrollOffset(indexNotifier.value ?? 0); + _scrollController = ScrollController(initialScrollOffset: scrollOffset); + _scrollController.addListener(_onScrollChanged); + widget.indexNotifier.addListener(_onIndexChanged); + } + + void _unregisterWidget(ThumbnailScroller widget) { + _scrollController.removeListener(_onScrollChanged); + _scrollController.dispose(); + widget.indexNotifier.removeListener(_onIndexChanged); + } + + @override + Widget build(BuildContext context) { + final marginWidth = max(0.0, (widget.availableWidth - thumbnailExtent) / 2 - separatorWidth); + final padding = scrollable ? EdgeInsets.only(left: marginWidth + separatorWidth, right: marginWidth) : EdgeInsets.zero; + + return GridTheme( + extent: thumbnailExtent, + showLocation: widget.showLocation, + showTrash: false, + child: SizedBox( + width: scrollable ? null : widthFor(entryCount), + height: thumbnailExtent, + child: ListView.builder( + scrollDirection: Axis.horizontal, + controller: _scrollController, + // as of Flutter v2.10.2, `FixedExtentScrollController` can only be used with `ListWheelScrollView` + // and `FixedExtentScrollPhysics` can only be used with Scrollables that uses the `FixedExtentScrollController` + // so we use `KnownExtentScrollPhysics`, adapted from `FixedExtentScrollPhysics` without the constraints + physics: scrollable + ? KnownExtentScrollPhysics( + indexToScrollOffset: indexToScrollOffset, + scrollOffsetToIndex: scrollOffsetToIndex, + ) + : const NeverScrollableScrollPhysics(), + padding: padding, + itemExtent: itemExtent, + itemBuilder: (context, index) => _buildThumbnail(index), + itemCount: entryCount, + ), + ), + ); + } + + Widget _buildThumbnail(int index) { + final pageEntry = widget.entryBuilder(index); + if (pageEntry == null) return const SizedBox(); + + return Stack( + children: [ + GestureDetector( + onTap: () { + indexNotifier.value = index; + widget.onTap?.call(index); + }, + child: DecoratedThumbnail( + entry: pageEntry, + tileExtent: thumbnailExtent, + // the retrieval task queue can pile up for thumbnails of heavy pages + // (e.g. thumbnails of 15MP HEIF images inside 100MB+ HEIC containers) + // so we cancel these requests when possible + cancellableNotifier: _cancellableNotifier, + selectable: false, + highlightable: widget.highlightable, + heroTagger: () => widget.heroTagger?.call(pageEntry), + ), + ), + IgnorePointer( + child: ValueListenableBuilder<int?>( + valueListenable: indexNotifier, + builder: (context, currentIndex, child) { + return AnimatedContainer( + color: currentIndex == index ? Colors.transparent : Colors.black45, + width: thumbnailExtent, + height: thumbnailExtent, + duration: ADurations.thumbnailScrollerShadeAnimation, + ); + }, + ), + ), + ], + ); + } + + Future<void> _goTo(int index) async { + if (!scrollable) return; + + final targetOffset = indexToScrollOffset(index); + final offsetDelta = (targetOffset - _scrollController.offset).abs(); + + if (offsetDelta > widget.availableWidth * 2) { + _scrollController.jumpTo(targetOffset); + } else { + _isAnimating = true; + await _scrollController.animateTo( + targetOffset, + duration: ADurations.thumbnailScrollerScrollAnimation, + curve: Curves.easeOutCubic, + ); + _isAnimating = false; + } + } + + void _onScrollChanged() { + if (!_isAnimating) { + final index = scrollOffsetToIndex(_scrollController.offset); + if (indexNotifier.value != index) { + _isScrolling = true; + indexNotifier.value = index; + } + } + } + + void _onIndexChanged() { + if (!_isScrolling && !_isAnimating) { + final index = indexNotifier.value; + if (index != null) { + _goTo(index); + } + } + _isScrolling = false; + } + + double indexToScrollOffset(int index) => index * itemExtent; + + int scrollOffsetToIndex(double offset) => (offset / itemExtent).round(); +} diff --git a/lib/widgets/common/tile_extent_controller.dart b/lib/widgets/common/tile_extent_controller.dart new file mode 100644 index 0000000..bf4567d --- /dev/null +++ b/lib/widgets/common/tile_extent_controller.dart @@ -0,0 +1,126 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/widgets.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class TileExtentController { + final String settingsRouteKey; + final int columnCountMin, columnCountDefault; + final double extentMin, extentMax, spacing, horizontalPadding; + late final ValueNotifier<double> extentNotifier; + + late double userPreferredExtent; + Size _viewportSize = Size.zero; + final Set<StreamSubscription> _subscriptions = {}; + + Size get viewportSize => _viewportSize; + + TileExtentController({ + required this.settingsRouteKey, + this.columnCountMin = 2, + required this.columnCountDefault, + required this.extentMin, + required this.extentMax, + required this.spacing, + required this.horizontalPadding, + }) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$TileExtentController', + object: this, + ); + } + // initialize extent to 0, so that it will be dynamically sized on first launch + extentNotifier = ValueNotifier(0); + userPreferredExtent = settings.getTileExtent(settingsRouteKey); + _subscriptions.add(settings.updateTileExtentStream.listen((_) => _onSettingsChanged())); + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + void _onSettingsChanged() { + if (userPreferredExtent != settings.getTileExtent(settingsRouteKey)) { + _update(); + } + } + + void setViewportSize(Size viewportSize) { + // sanitize screen size (useful when reloading while screen is off, reporting a 0,0 size) + final viewportSizeMin = Size.square(extentMin * columnCountMin); + // dimensions are rounded to prevent updates on minor changes + // e.g. available space on S10e is `Size(360.0, 721.0)` when status bar is visible, `Size(360.0, 721.3)` when it is not + final newViewportSize = Size(max(viewportSize.width, viewportSizeMin.width).roundToDouble(), max(viewportSize.height, viewportSizeMin.height).roundToDouble()); + if (_viewportSize != newViewportSize) { + _viewportSize = newViewportSize; + _update(); + } + } + + double setUserPreferredColumnCount(int columnCount) => _update(userPreferredExtent: _extentForColumnCount(columnCount)); + + double setUserPreferredExtent(double extent) => _update(userPreferredExtent: extent.roundToDouble()); + + double _update({double? userPreferredExtent}) { + final preferredExtent = userPreferredExtent ?? settings.getTileExtent(settingsRouteKey); + final targetExtent = preferredExtent > 0 ? preferredExtent : extentNotifier.value; + + final columnCount = _effectiveColumnCountForExtent(targetExtent); + final newExtent = _extentForColumnCount(columnCount).clamp(effectiveExtentMin, effectiveExtentMax); + + if (this.userPreferredExtent != preferredExtent) { + this.userPreferredExtent = preferredExtent; + settings.setTileExtent(settingsRouteKey, preferredExtent); + } + if (extentNotifier.value != newExtent) { + extentNotifier.value = newExtent; + } + return newExtent; + } + + double _extentMax() => min(extentMax, (viewportSize.shortestSide - (horizontalPadding * 2) - spacing * (columnCountMin - 1)) / columnCountMin); + + double _columnCountForExtent(double extent) => (viewportSize.width - (horizontalPadding * 2) + spacing) / (extent + spacing); + + double _extentForColumnCount(int columnCount) => (viewportSize.width - (horizontalPadding * 2) - spacing * (columnCount - 1)) / columnCount; + + int _effectiveColumnCountMin() => max(columnCountMin, _columnCountForExtent(_extentMax()).ceil()); + + int _effectiveColumnCountMax() => max(columnCountMin, _columnCountForExtent(extentMin).floor()); + + int _effectiveColumnCountForExtent(double extent) { + if (extent > 0) { + final columnCount = _columnCountForExtent(extent); + final countMax = _effectiveColumnCountMax(); + final countMin = min(_effectiveColumnCountMin(), countMax); + return columnCount.round().clamp(countMin, countMax); + } + return columnCountDefault; + } + + double get effectiveExtentMin => min(_extentForColumnCount(_effectiveColumnCountMax()), effectiveExtentMax); + + double get effectiveExtentMax => _extentForColumnCount(_effectiveColumnCountMin()); + + (int min, int max) get effectiveColumnRange => (_effectiveColumnCountMin(), _effectiveColumnCountMax()); + + int get columnCount => _effectiveColumnCountForExtent(extentNotifier.value); + + Duration getTileAnimationDelay(Duration pageTarget) { + final extent = extentNotifier.value; + final columnCount = ((viewportSize.width - (horizontalPadding * 2) + spacing) / (extent + spacing)).round(); + final rowCount = (viewportSize.height + spacing) ~/ (extent + spacing); + return pageTarget ~/ (columnCount + rowCount) * timeDilation; + } +} |
