Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

➕ Support Drag and Select feature #175 #660

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
130189a
➕ Support Drag and Select feature
WeiJun0507 Nov 9, 2024
a1e594d
➕ Support Drag and Select feature
WeiJun0507 Nov 17, 2024
aa6f46e
➕ Support Drag and Select feature
WeiJun0507 Nov 17, 2024
0e82a3b
➕ Support Drag and Select feature
WeiJun0507 Nov 23, 2024
3faa7a0
Merge branch 'fluttercandies:main' into drag_select_featue_v2
WeiJun0507 Nov 23, 2024
6a366fb
➕ Support Drag and Select feature
WeiJun0507 Nov 23, 2024
1f989bb
➕ Support Drag and Select feature
WeiJun0507 Nov 24, 2024
c42e7cc
➕ Support Drag and Select feature
WeiJun0507 Nov 24, 2024
f7dd57d
♻️ Use horizonal gestures to trigger aggregator calculations
AlexV525 Dec 2, 2024
ff77528
♻️ Refine the coordinator and add multiple gestures support
AlexV525 Dec 3, 2024
6bca4c2
♻️ `enableDragAndSelect` -> `dragToSelect`
AlexV525 Dec 3, 2024
cb46460
🐛 Fix dimension calculations
AlexV525 Dec 4, 2024
b6bcc6e
🐛 Fix the missing range from the largest index
AlexV525 Dec 4, 2024
ec57fba
♿️ Try to fix accessibility issues
AlexV525 Dec 4, 2024
9a1bcdf
🐛 Fix grid revert calculations
AlexV525 Dec 4, 2024
3026576
🐛 Fix column and row index inaccurate when asset is less than a page
WeiJun0507 Dec 12, 2024
9388ada
🐛 Fix android revert drag select calculation
WeiJun0507 Dec 17, 2024
f72478d
⚡️ Optimize column and row index calculation in reverse grid
WeiJun0507 Dec 18, 2024
f9016c1
:bug: Fix drag select index accuracy when asset size is one page
WeiJun0507 Dec 23, 2024
77d4429
Revert ":bug: Fix drag select index accuracy when asset size is one p…
WeiJun0507 Dec 23, 2024
dfa8352
🐛 Fix drag select index accuracy when asset size is one page
WeiJun0507 Dec 23, 2024
f39b2ba
🐛 Improve the accuracy of select asset on iOS device
WeiJun0507 Dec 30, 2024
8580c40
🐛 Fix bottom gaps when grid reverting on Android
AlexV525 Dec 31, 2024
60239f6
🐛 Improve the accuracy of select asset on iOS device
WeiJun0507 Jan 4, 2025
643af2f
🐛 Fix anchors and reverts
AlexV525 Jan 7, 2025
a02aa2c
🐛 Fix placeholders count
AlexV525 Jan 7, 2025
7eba1b4
⚡️ Unify calculations and comments
AlexV525 Jan 7, 2025
7835a6c
🚸 Improves auto-scroll
AlexV525 Jan 12, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions example/lib/constants/picker_method.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class PickMethod {
pickerConfig: AssetPickerConfig(
maxAssets: maxAssetsCount,
selectedAssets: assets,
enableDragAndSelect: true,
),
);
},
Expand Down
5 changes: 5 additions & 0 deletions lib/src/constants/config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class AssetPickerConfig {
this.assetsChangeCallback,
this.assetsChangeRefreshPredicate,
this.shouldAutoplayPreview = false,
this.enableDragAndSelect = true,
}) : assert(
pickerTheme == null || themeColor == null,
'pickerTheme and themeColor cannot be set at the same time.',
Expand Down Expand Up @@ -205,4 +206,8 @@ class AssetPickerConfig {
/// Whether the preview should auto play.
/// 预览是否自动播放
final bool shouldAutoplayPreview;

/// Should enable drag and select function.
/// 是否开启拖拽选择
final bool enableDragAndSelect;
}
188 changes: 188 additions & 0 deletions lib/src/delegates/asset_grid_drag_selection_aggregator.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class AssetGridDragSelectionAggregator {
AssetGridDragSelectionAggregator({
required this.delegate,
});

/// [ChangeNotifier] for asset picker.
/// 资源选择器状态保持
final DefaultAssetPickerBuilderDelegate delegate;

/// 拖拽状态
/// Drag status
bool isInDragging = false;

/// 边缘自动滚动控制器
/// Edge Auto Scrolling Detector. Use to support edge auto scroll when drag position reach the edge of device's screen.
EdgeDraggingAutoScroller? _autoScroller;

// An eyeballed value for a smooth scrolling experience.
static const double _kDefaultAutoScrollVelocityScalar = 50;

/// 起始选择序号
/// Item index of the first selected item
int initialSelectedIdx = -1;

/// 拖拽选择 或 拖拽取消选择
/// Drag to select or deselect state
bool dragSelect = true;

/// 长按启动拖拽
/// Long Press to enable drag and select
void onDragStart(
BuildContext context,
LongPressStartDetails details,
int index,
AssetEntity entity,
) {
isInDragging = true;

final scrollableState = _checkScrollableStatePresent(context);
if (scrollableState == null) {
return;
}

_autoScroller = EdgeDraggingAutoScroller(
scrollableState,
velocityScalar: _kDefaultAutoScrollVelocityScalar,
);

initialSelectedIdx = index;

dragSelect = !delegate.provider.selectedAssets.contains(entity);
}

void onDragUpdate(
BuildContext context,
LongPressMoveUpdateDetails details,
double itemSize,
int gridCount,
double topPadding,
) {
if (!isInDragging) {
return;
}

if (dragSelect &&
delegate.provider.selectedAssets.length ==
delegate.provider.maxAssets) {
AlexV525 marked this conversation as resolved.
Show resolved Hide resolved
return;
}

final scrollableState = _checkScrollableStatePresent(context);
if (scrollableState == null) {
return;
}

final column = _getDragPositionIndex(details.globalPosition.dx, itemSize);
final row = _getDragPositionIndex(
details.globalPosition.dy -
topPadding -
(View.of(context).viewPadding.top /
View.of(context).devicePixelRatio) +
scrollableState.position.pixels,
itemSize,
);

final currentDragIndex = row * gridCount + column;

List<AssetEntity> filteredAssetList = <AssetEntity>[];
AlexV525 marked this conversation as resolved.
Show resolved Hide resolved
// add asset
if (currentDragIndex < initialSelectedIdx) {
filteredAssetList = delegate.provider.currentAssets
.getRange(
currentDragIndex,
math.min(
initialSelectedIdx + 1, delegate.provider.currentAssets.length),
)
.toList()
..reversed;
} else {
filteredAssetList = delegate.provider.currentAssets
.getRange(
initialSelectedIdx,
math.min(
currentDragIndex + 1, delegate.provider.currentAssets.length),
)
.toList();
}

for (final asset in filteredAssetList) {
delegate.selectAsset(context, asset, currentDragIndex, !dragSelect);
}

final bool stopAutoScroll =
(!dragSelect && delegate.provider.selectedAssets.isEmpty) ||
AlexV525 marked this conversation as resolved.
Show resolved Hide resolved
(dragSelect &&
delegate.provider.selectedAssets.length ==
delegate.provider.maxAssets);

if (stopAutoScroll) {
_autoScroller?.stopAutoScroll();
_autoScroller = null;
return;
}

if (!dragSelect && delegate.provider.selectedAssets.isEmpty) {}
AlexV525 marked this conversation as resolved.
Show resolved Hide resolved

_autoScroller?.startAutoScrollIfNecessary(
Rect.fromLTWH(
(column + 1) * itemSize,
details.globalPosition.dy > MediaQuery.sizeOf(context).height * 0.8
? (row + 1) * itemSize
: math.max(topPadding, details.globalPosition.dy),
itemSize,
itemSize,
),
AlexV525 marked this conversation as resolved.
Show resolved Hide resolved
);
}

void onDragEnd(LongPressEndDetails details) {
resetDraggingStatus();
}

/// 复原拖拽状态
/// Reset dragging status
void resetDraggingStatus() {
isInDragging = false;
initialSelectedIdx = -1;
dragSelect = true;
_autoScroller?.stopAutoScroll();
_autoScroller = null;
}

/// 检查 [Scrollable] state是否存在
/// Check if the [Scrollable] state is exist
///
/// This is to ensure that the edge auto scrolling is functioning and the drag function is placed correctly
/// inside the Scrollable
/// 拖拽选择功能必须被放在 可滚动视图下才能启动边缘自动滚动功能
ScrollableState? _checkScrollableStatePresent(BuildContext context) {
final scrollable = Scrollable.maybeOf(context);
assert(
scrollable != null,
'To use drag and select function, Scrollable state must be the present to get the actual item position.',
);
assert(
scrollable?.position.axis == Axis.vertical,
'To use drag and select function. The Scrollable Axis must be in vertical direction',
);

if (scrollable == null || scrollable.position.axis != Axis.vertical) {
resetDraggingStatus();
return null;
}

return scrollable;
}

/// 获取坐标
/// Get Coordinate Helper
int _getDragPositionIndex(double delta, double itemSize) {
return delta ~/ itemSize;
}
}
52 changes: 46 additions & 6 deletions lib/src/delegates/asset_picker_builder_delegate.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import 'dart:async';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'dart:ui';
AlexV525 marked this conversation as resolved.
Show resolved Hide resolved

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
Expand All @@ -13,6 +14,7 @@ import 'package:flutter/services.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:photo_manager_image_provider/photo_manager_image_provider.dart';
import 'package:provider/provider.dart';
import 'package:wechat_assets_picker/src/delegates/asset_grid_drag_selection_aggregator.dart';
AlexV525 marked this conversation as resolved.
Show resolved Hide resolved
import 'package:wechat_picker_library/wechat_picker_library.dart';

import '../constants/constants.dart';
Expand Down Expand Up @@ -760,11 +762,14 @@ class DefaultAssetPickerBuilderDelegate
this.specialPickerType,
this.keepScrollOffset = false,
this.shouldAutoplayPreview = false,
this.enableDragAndSelect = true,
}) {
// Add the listener if [keepScrollOffset] is true.
if (keepScrollOffset) {
gridScrollController.addListener(keepScrollOffsetListener);
}

dragSelector = AssetGridDragSelectionAggregator(delegate: this);
}

/// [ChangeNotifier] for asset picker.
Expand Down Expand Up @@ -810,6 +815,10 @@ class DefaultAssetPickerBuilderDelegate
/// * [SpecialPickerType.noPreview] 禁用资源预览。多选时单击资产将直接选中,单选时选中并返回。
final SpecialPickerType? specialPickerType;

/// Drag Selector
/// 拖拽选择器
late final AssetGridDragSelectionAggregator dragSelector;

/// Whether the picker should save the scroll offset between pushes and pops.
/// 选择器是否可以从同样的位置开始选择
final bool keepScrollOffset;
Expand All @@ -818,6 +827,10 @@ class DefaultAssetPickerBuilderDelegate
/// 预览是否自动播放
final bool shouldAutoplayPreview;

/// Should enable drag and select function.
/// 是否开启拖拽选择
final bool enableDragAndSelect;

/// [Duration] when triggering path switching.
/// 切换路径时的动画时长
Duration get switchingPathDuration => const Duration(milliseconds: 300);
Expand Down Expand Up @@ -1268,6 +1281,9 @@ class DefaultAssetPickerBuilderDelegate
context.topPadding + appBarPreferredSize!.height;

final textDirection = Directionality.of(context);
final double screenWidth = MediaQuery.sizeOf(context).width;
final double itemSize = screenWidth / gridCount;

Widget sliverGrid(BuildContext context, List<AssetEntity> assets) {
return SliverGrid(
delegate: SliverChildBuilderDelegate(
Expand All @@ -1278,15 +1294,39 @@ class DefaultAssetPickerBuilderDelegate
}
index -= placeholderCount;
}
return MergeSemantics(
child: Directionality(
textDirection: textDirection,
child: assetGridItemBuilder(

Widget child = assetGridItemBuilder(
context,
index,
assets,
specialItem: specialItem,
);

if (enableDragAndSelect) {
child = GestureDetector(
onLongPressStart: (d) => dragSelector.onDragStart(
context,
d,
index,
assets,
specialItem: specialItem,
assets[index],
),
onLongPressMoveUpdate: (d) => dragSelector.onDragUpdate(
context,
d,
itemSize,
gridCount,
topPadding,
),
onLongPressCancel: dragSelector.resetDraggingStatus,
onLongPressEnd: dragSelector.onDragEnd,
child: child,
);
}

return MergeSemantics(
child: Directionality(
textDirection: textDirection,
child: child,
),
);
},
Expand Down
1 change: 1 addition & 0 deletions lib/src/delegates/asset_picker_delegate.dart
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ class AssetPickerDelegate {
themeColor: pickerConfig.themeColor,
locale: Localizations.maybeLocaleOf(context),
shouldAutoplayPreview: pickerConfig.shouldAutoplayPreview,
enableDragAndSelect: pickerConfig.enableDragAndSelect,
),
);
final List<AssetEntity>? result = await Navigator.maybeOf(
Expand Down