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/basic | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'lib/widgets/common/basic')
32 files changed, 5209 insertions, 0 deletions
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, +} |
