-
Notifications
You must be signed in to change notification settings - Fork 7
/
ReorderableLazyCollection.kt
847 lines (758 loc) · 33.3 KB
/
ReorderableLazyCollection.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
/*
* Copyright 2023 Calvin Liang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sh.calvin.reorderable
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.VisibilityThreshold
import androidx.compose.animation.core.spring
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.interaction.DragInteraction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toOffset
import androidx.compose.ui.unit.toSize
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeout
object ReorderableLazyCollectionDefaults {
val ScrollThreshold = 48.dp
}
internal const val ScrollAmountMultiplier = 0.05f
internal data class AbsolutePixelPadding(
val start: Float,
val end: Float,
val top: Float,
val bottom: Float,
) {
companion object {
val Zero = AbsolutePixelPadding(0f, 0f, 0f, 0f)
@Composable
fun fromPaddingValues(paddingValues: PaddingValues): AbsolutePixelPadding {
val density = LocalDensity.current
val layoutDirection = LocalLayoutDirection.current
return AbsolutePixelPadding(
start = with(density) {
paddingValues.calculateStartPadding(layoutDirection).toPx()
},
end = with(density) { paddingValues.calculateEndPadding(layoutDirection).toPx() },
top = with(density) { paddingValues.calculateTopPadding().toPx() },
bottom = with(density) { paddingValues.calculateBottomPadding().toPx() },
)
}
}
}
internal interface LazyCollectionItemInfo<out T> {
val index: Int
val key: Any
val offset: IntOffset
val size: IntSize
val data: T
val center: IntOffset
get() = IntOffset(offset.x + size.width / 2, offset.y + size.height / 2)
}
internal data class CollectionScrollPadding(
val start: Float,
val end: Float,
) {
companion object {
val Zero = CollectionScrollPadding(0f, 0f)
fun fromAbsolutePixelPadding(
orientation: Orientation,
padding: AbsolutePixelPadding,
reverseLayout: Boolean,
): CollectionScrollPadding {
return when (orientation) {
Orientation.Vertical -> CollectionScrollPadding(
start = padding.top,
end = padding.bottom,
)
Orientation.Horizontal -> CollectionScrollPadding(
start = padding.start,
end = padding.end,
)
}.let {
when (reverseLayout) {
true -> CollectionScrollPadding(
start = it.end,
end = it.start,
)
false -> it
}
}
}
}
}
/**
* The offsets in the main axis from the start of the content to the
* start and end of the content minus the padding.
*/
internal data class ScrollAreaOffsets(
val start: Float,
val end: Float,
)
internal interface LazyCollectionLayoutInfo<out T> {
val visibleItemsInfo: List<LazyCollectionItemInfo<T>>
val viewportSize: IntSize
val orientation: Orientation
val reverseLayout: Boolean
val beforeContentPadding: Int
val mainAxisViewportSize: Int
get() = when (orientation) {
Orientation.Vertical -> viewportSize.height
Orientation.Horizontal -> viewportSize.width
}
fun getScrollAreaOffsets(
padding: AbsolutePixelPadding,
) = getScrollAreaOffsets(
CollectionScrollPadding.fromAbsolutePixelPadding(
orientation,
padding,
reverseLayout,
)
)
fun getScrollAreaOffsets(padding: CollectionScrollPadding): ScrollAreaOffsets {
val (startPadding, endPadding) = padding
val contentEndOffset = when (orientation) {
Orientation.Vertical -> viewportSize.height
Orientation.Horizontal -> viewportSize.width
} - endPadding
return ScrollAreaOffsets(
start = startPadding,
end = contentEndOffset,
)
}
/**
* get items that are fully inside the content area
*/
fun getItemsInContentArea(padding: AbsolutePixelPadding) = getItemsInContentArea(
CollectionScrollPadding.fromAbsolutePixelPadding(
orientation,
padding,
reverseLayout,
)
)
/**
* get items that are fully inside the content area
*/
fun getItemsInContentArea(padding: CollectionScrollPadding = CollectionScrollPadding.Zero): List<LazyCollectionItemInfo<T>> {
val (contentStartOffset, contentEndOffset) = getScrollAreaOffsets(
padding
)
return when (orientation) {
Orientation.Vertical -> {
visibleItemsInfo.filter { item ->
item.offset.y >= contentStartOffset && item.offset.y + item.size.height <= contentEndOffset
}
}
Orientation.Horizontal -> {
visibleItemsInfo.filter { item ->
item.offset.x >= contentStartOffset && item.offset.x + item.size.width <= contentEndOffset
}
}
}
}
}
internal interface LazyCollectionState<out T> {
val firstVisibleItemIndex: Int
val firstVisibleItemScrollOffset: Int
val layoutInfo: LazyCollectionLayoutInfo<T>
suspend fun animateScrollBy(
value: Float,
animationSpec: AnimationSpec<Float> = spring(),
): Float
suspend fun scrollToItem(scrollToIndex: Int, firstVisibleItemScrollOffset: Int)
}
interface ReorderableLazyCollectionStateInterface {
val isAnyItemDragging: Boolean
}
// base on https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/LazyColumnDragAndDropDemo.kt;drc=edde6e8b9d304264598f962a3b0e5c267e1373bb
// and https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/LazyGridDragAndDropDemo.kt;drc=44e4233f7bc0290a1509ef2d448f1309eb63248f
@Stable
open class ReorderableLazyCollectionState<out T> internal constructor(
private val state: LazyCollectionState<T>,
private val scope: CoroutineScope,
private val onMoveState: State<suspend CoroutineScope.(from: T, to: T) -> Unit>,
/**
* The threshold in pixels for scrolling the list when dragging an item.
* If the dragged item is within this threshold of the top or bottom of the list, the list will scroll.
* Must be greater than 0.
*/
private val scrollThreshold: Float,
private val scrollThresholdPadding: AbsolutePixelPadding,
private val scroller: Scroller,
private val layoutDirection: LayoutDirection,
/**
* Whether this is a LazyVerticalStaggeredGrid
*/
private val lazyVerticalStaggeredGridRtlFix: Boolean = false,
/**
* A function that determines whether the `draggingItem` should be moved with the `item`.
* Given their bounding rectangles, return `true` if they should be moved.
* The default implementation is to move if the dragging item's bounding rectangle has crossed the center of the item's bounding rectangle.
*/
private val shouldItemMove: (draggingItem: Rect, item: Rect) -> Boolean = { draggingItem, item ->
draggingItem.contains(item.center)
},
) : ReorderableLazyCollectionStateInterface {
private val onMoveStateMutex: Mutex = Mutex()
internal val orientation: Orientation
get() = state.layoutInfo.orientation
private var draggingItemKey by mutableStateOf<Any?>(null)
private val draggingItemIndex: Int?
get() = draggingItemLayoutInfo?.index
/**
* Whether any item is being dragged. This property is observable.
*/
override val isAnyItemDragging by derivedStateOf {
draggingItemKey != null
}
private var draggingItemDraggedDelta by mutableStateOf(Offset.Zero)
private var draggingItemInitialOffset by mutableStateOf(IntOffset.Zero)
// visibleItemsInfo doesn't update immediately after onMove, draggingItemLayoutInfo.item may be outdated for a short time.
// not a clean solution, but it works.
private var draggingItemTargetIndex by mutableStateOf<Int?>(null)
private var predictedDraggingItemOffset by mutableStateOf<IntOffset?>(null)
private val draggingItemLayoutInfo: LazyCollectionItemInfo<T>?
get() = draggingItemKey?.let { draggingItemKey ->
state.layoutInfo.visibleItemsInfo.firstOrNull { it.key == draggingItemKey }
}
internal val draggingItemOffset: Offset
get() = (draggingItemLayoutInfo?.let {
val offset =
if (it.index == draggingItemTargetIndex || draggingItemTargetIndex == null) {
draggingItemTargetIndex = null
predictedDraggingItemOffset = null
it.offset
} else {
predictedDraggingItemOffset ?: it.offset
}
draggingItemDraggedDelta +
(draggingItemInitialOffset.toOffset() - offset.toOffset())
.reverseAxisIfNecessary()
.reverseAxisWithLayoutDirectionIfLazyVerticalStaggeredGridRtlFix()
}) ?: Offset.Zero
// the offset of the handle center from the top left of the dragging item when dragging starts
private var draggingItemHandleOffset = Offset.Zero
internal val reorderableKeys = HashSet<Any?>()
internal var previousDraggingItemKey by mutableStateOf<Any?>(null)
private set
internal var previousDraggingItemOffset = Animatable(Offset.Zero, Offset.VectorConverter)
private set
private fun Offset.reverseAxisWithReverseLayoutIfNecessary() =
when (state.layoutInfo.reverseLayout) {
true -> reverseAxis(orientation)
false -> this
}
private fun Offset.reverseAxisWithLayoutDirectionIfNecessary() = when (orientation) {
Orientation.Vertical -> this
Orientation.Horizontal -> reverseAxisWithLayoutDirection()
}
private fun Offset.reverseAxisWithLayoutDirection() = when (layoutDirection) {
LayoutDirection.Ltr -> this
LayoutDirection.Rtl -> reverseAxis(Orientation.Horizontal)
}
private fun Offset.reverseAxisWithLayoutDirectionIfLazyVerticalStaggeredGridRtlFix() =
when (layoutDirection) {
LayoutDirection.Ltr -> this
LayoutDirection.Rtl -> if (lazyVerticalStaggeredGridRtlFix && orientation == Orientation.Vertical)
reverseAxis(Orientation.Horizontal)
else this
}
private fun Offset.reverseAxisIfNecessary() =
this.reverseAxisWithReverseLayoutIfNecessary()
.reverseAxisWithLayoutDirectionIfNecessary()
private fun Offset.mainAxis() = getAxis(orientation)
private fun IntOffset.mainAxis() = getAxis(orientation)
internal suspend fun onDragStart(key: Any, handleOffset: Offset) {
state.layoutInfo.visibleItemsInfo.firstOrNull { item ->
item.key == key
}?.also {
val mainAxisOffset = it.offset.mainAxis()
if (mainAxisOffset < 0) {
// if item is not fully in view, scroll to it
state.animateScrollBy(mainAxisOffset.toFloat(), spring())
}
draggingItemKey = key
draggingItemInitialOffset = it.offset
draggingItemHandleOffset = handleOffset
}
}
internal fun onDragStop() {
val previousDraggingItemInitialOffset = draggingItemLayoutInfo?.offset
if (draggingItemIndex != null) {
previousDraggingItemKey = draggingItemKey
val startOffset = draggingItemOffset
scope.launch {
previousDraggingItemOffset.snapTo(startOffset)
previousDraggingItemOffset.animateTo(
Offset.Zero,
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = Offset.VisibilityThreshold
)
)
previousDraggingItemKey = null
}
}
draggingItemDraggedDelta = Offset.Zero
draggingItemKey = null
draggingItemInitialOffset = previousDraggingItemInitialOffset ?: IntOffset.Zero
scroller.tryStop()
draggingItemTargetIndex = null
predictedDraggingItemOffset = null
}
internal fun onDrag(offset: Offset) {
draggingItemDraggedDelta += offset
val draggingItem = draggingItemLayoutInfo ?: return
// how far the dragging item is from the original position
val dragOffset = draggingItemOffset.reverseAxisIfNecessary()
.reverseAxisWithLayoutDirectionIfLazyVerticalStaggeredGridRtlFix()
val startOffset = draggingItem.offset.toOffset() + dragOffset
val endOffset = startOffset + draggingItem.size.toSize()
val (contentStartOffset, contentEndOffset) = state.layoutInfo.getScrollAreaOffsets(
scrollThresholdPadding
)
// the distance from the top or left of the list to the center of the dragging item handle
val handleOffset =
when (state.layoutInfo.reverseLayout ||
(layoutDirection == LayoutDirection.Rtl &&
orientation == Orientation.Horizontal)) {
true -> endOffset - draggingItemHandleOffset
false -> startOffset + draggingItemHandleOffset
} + IntOffset.fromAxis(
orientation,
state.layoutInfo.beforeContentPadding
).toOffset()
// check if the handle center is in the scroll threshold
val distanceFromStart = (handleOffset.getAxis(orientation) - contentStartOffset)
.coerceAtLeast(0f)
val distanceFromEnd = (contentEndOffset - handleOffset.getAxis(orientation))
.coerceAtLeast(0f)
val isScrollingStarted = if (distanceFromStart < scrollThreshold) {
scroller.start(
Scroller.Direction.BACKWARD,
getScrollSpeedMultiplier(distanceFromStart),
maxScrollDistanceProvider = {
// distance from the start of the dragging item's stationary position to the end of the list
(draggingItemLayoutInfo?.let {
state.layoutInfo.mainAxisViewportSize -
it.offset.toOffset().getAxis(orientation) - 1f
}) ?: 0f
},
onScroll = {
moveDraggingItemToEnd(Scroller.Direction.BACKWARD)
}
)
} else if (distanceFromEnd < scrollThreshold) {
scroller.start(
Scroller.Direction.FORWARD,
getScrollSpeedMultiplier(distanceFromEnd),
maxScrollDistanceProvider = {
// distance from the end of the dragging item's stationary position to the start of the list
(draggingItemLayoutInfo?.let {
val visibleItems = state.layoutInfo.visibleItemsInfo
// use the item before the dragging item to prevent the dragging item from becoming the firstVisibleItem
// TODO(foundation v1.7.0): remove once foundation v1.7.0 is out
val itemBeforeDraggingItem =
visibleItems.getOrNull(visibleItems.indexOfFirst { it.key == draggingItemKey } - 1)
var itemToAlmostScrollOff = itemBeforeDraggingItem ?: it
var scrollDistance =
itemToAlmostScrollOff.offset.toOffset().getAxis(orientation) +
itemToAlmostScrollOff.size.getAxis(orientation) - 1f
if (scrollDistance <= 0f) {
itemToAlmostScrollOff = it
scrollDistance =
itemToAlmostScrollOff.offset.toOffset().getAxis(orientation) +
itemToAlmostScrollOff.size.getAxis(orientation) - 1f
}
scrollDistance
}) ?: 0f
},
onScroll = {
moveDraggingItemToEnd(Scroller.Direction.FORWARD)
}
)
} else {
scroller.tryStop()
false
}
if (!onMoveStateMutex.tryLock()) return
if (!scroller.isScrolling && !isScrollingStarted) {
val draggingItemRect = Rect(startOffset, endOffset)
// find a target item to move with
val targetItem = findTargetItem(
draggingItemRect,
items = state.layoutInfo.visibleItemsInfo,
) {
it.index != draggingItem.index
}
if (targetItem != null) {
scope.launch {
moveItems(draggingItem, targetItem)
}
}
}
onMoveStateMutex.unlock()
}
// keep dragging item in visible area to prevent it from disappearing
private suspend fun moveDraggingItemToEnd(
direction: Scroller.Direction,
) {
// wait for the current moveItems to finish
onMoveStateMutex.lock()
val draggingItem = draggingItemLayoutInfo
if (draggingItem == null) {
onMoveStateMutex.unlock()
return
}
val isDraggingItemAtEnd = when (direction) {
Scroller.Direction.FORWARD -> draggingItem.index == state.layoutInfo.visibleItemsInfo.lastOrNull()?.index
Scroller.Direction.BACKWARD -> draggingItem.index == state.firstVisibleItemIndex
}
if (isDraggingItemAtEnd) {
onMoveStateMutex.unlock()
return
}
val dragOffset = draggingItemOffset.reverseAxisIfNecessary()
.reverseAxisWithLayoutDirectionIfLazyVerticalStaggeredGridRtlFix()
val startOffset = draggingItem.offset.toOffset() + dragOffset
val endOffset = startOffset + draggingItem.size.toSize()
val draggingItemRect = Rect(startOffset, endOffset).maxOutAxis(orientation)
val targetItem = findTargetItem(
draggingItemRect,
items = state.layoutInfo.getItemsInContentArea(scrollThresholdPadding),
direction.opposite,
) {
// TODO(foundation v1.7.0): remove `state.firstVisibleItemIndex` check once foundation v1.7.0 is out
it.index != state.firstVisibleItemIndex
} ?: state.layoutInfo.getItemsInContentArea(
scrollThresholdPadding
).let {
val targetItemFunc = { item: LazyCollectionItemInfo<T> ->
item.key in reorderableKeys && item.index != state.firstVisibleItemIndex
}
when (direction) {
Scroller.Direction.FORWARD -> it.findLast(targetItemFunc)
Scroller.Direction.BACKWARD -> it.find(targetItemFunc)
}
}
val job = scope.launch {
if (targetItem != null) {
moveItems(draggingItem, targetItem)
}
}
onMoveStateMutex.unlock()
job.join()
}
private fun Rect.maxOutAxis(orientation: Orientation): Rect {
return when (orientation) {
Orientation.Vertical -> copy(
top = Float.NEGATIVE_INFINITY,
bottom = Float.POSITIVE_INFINITY,
)
Orientation.Horizontal -> copy(
left = Float.NEGATIVE_INFINITY,
right = Float.POSITIVE_INFINITY,
)
}
}
private fun findTargetItem(
draggingItemRect: Rect,
items: List<LazyCollectionItemInfo<T>> = state.layoutInfo.getItemsInContentArea(),
direction: Scroller.Direction = Scroller.Direction.FORWARD,
additionalPredicate: (LazyCollectionItemInfo<T>) -> Boolean = { true },
): LazyCollectionItemInfo<T>? {
val targetItemFunc = { item: LazyCollectionItemInfo<T> ->
val targetItemRect = Rect(item.offset.toOffset(), item.size.toSize())
shouldItemMove(draggingItemRect, targetItemRect)
&& item.key in reorderableKeys
&& additionalPredicate(item)
}
val targetItem = when (direction) {
Scroller.Direction.FORWARD -> items.find(targetItemFunc)
Scroller.Direction.BACKWARD -> items.findLast(targetItemFunc)
}
return targetItem
}
private val layoutInfoFlow = snapshotFlow { state.layoutInfo }
companion object {
const val MoveItemsLayoutInfoUpdateMaxWaitDuration = 1000L
}
private suspend fun moveItems(
draggingItem: LazyCollectionItemInfo<T>,
targetItem: LazyCollectionItemInfo<T>,
) {
if (draggingItem.index == targetItem.index) return
// TODO(foundation v1.7.0): when `requestScrollToItem` is released uncomment this and remove `scrollToIndex` and the following `if` block
// see https://android-review.googlesource.com/c/platform/frameworks/support/+/2987293
// see https://github.com/Calvin-LL/Reorderable/issues/4
// if (
// draggingItem.index == state.firstVisibleItemIndex ||
// targetItem.index == state.firstVisibleItemIndex
// ) {
// state.requestScrollToItem(
// state.firstVisibleItemIndex,
// state.firstVisibleItemScrollOffset
// )
// }
//
// onMoveState.value(draggingItem, targetItem)
val scrollToIndex = if (targetItem.index == state.firstVisibleItemIndex) {
draggingItem.index
} else if (draggingItem.index == state.firstVisibleItemIndex) {
targetItem.index
} else {
null
}
if (scrollToIndex != null) {
// this is needed to neutralize automatic keeping the first item first.
// see https://github.com/Calvin-LL/Reorderable/issues/4
state.scrollToItem(scrollToIndex, state.firstVisibleItemScrollOffset)
}
try {
onMoveStateMutex.withLock {
scope.(onMoveState.value)(draggingItem.data, targetItem.data)
predictedDraggingItemOffset = if (targetItem.index > draggingItem.index) {
(targetItem.offset + targetItem.size) - draggingItem.size
} else {
targetItem.offset
}
draggingItemTargetIndex = targetItem.index
withTimeout(MoveItemsLayoutInfoUpdateMaxWaitDuration) {
// the first result from layoutInfoFlow is the current layoutInfo
// the second result is the updated layoutInfo
layoutInfoFlow.take(2).collect()
}
}
} catch (e: CancellationException) {
// do nothing
}
}
internal fun isItemDragging(key: Any): State<Boolean> {
return derivedStateOf {
key == draggingItemKey
}
}
private fun getScrollSpeedMultiplier(distance: Float): Float {
// map distance in scrollThreshold..-scrollThreshold to 1..10
return (1 - ((distance + scrollThreshold) / (scrollThreshold * 2)).coerceIn(
0f,
1f
)) * 10
}
}
interface ReorderableCollectionItemScope {
/**
* Make the UI element the draggable handle for the reorderable item.
*
* This modifier can only be used on the UI element that is a child of [ReorderableItem].
*
* @param enabled Whether or not drag is enabled
* @param interactionSource [MutableInteractionSource] that will be used to emit [DragInteraction.Start] when this draggable is being dragged.
* @param onDragStarted The function that is called when the item starts being dragged
* @param onDragStopped The function that is called when the item stops being dragged
*/
fun Modifier.draggableHandle(
enabled: Boolean = true,
interactionSource: MutableInteractionSource? = null,
onDragStarted: (startedPosition: Offset) -> Unit = {},
onDragStopped: () -> Unit = {},
): Modifier
/**
* Make the UI element the draggable handle for the reorderable item. Drag will start only after a long press.
*
* This modifier can only be used on the UI element that is a child of [ReorderableItem].
*
* @param enabled Whether or not drag is enabled
* @param interactionSource [MutableInteractionSource] that will be used to emit [DragInteraction.Start] when this draggable is being dragged.
* @param onDragStarted The function that is called when the item starts being dragged
* @param onDragStopped The function that is called when the item stops being dragged
*/
fun Modifier.longPressDraggableHandle(
enabled: Boolean = true,
interactionSource: MutableInteractionSource? = null,
onDragStarted: (startedPosition: Offset) -> Unit = {},
onDragStopped: () -> Unit = {},
): Modifier
}
internal class ReorderableCollectionItemScopeImpl(
private val reorderableLazyCollectionState: ReorderableLazyCollectionState<*>,
private val key: Any,
private val itemPositionProvider: () -> Offset,
) : ReorderableCollectionItemScope {
/**
* Make the UI element the draggable handle for the reorderable item.
*
* @param enabled Whether or not drag is enabled
* @param interactionSource [MutableInteractionSource] that will be used to emit [DragInteraction.Start] when this draggable is being dragged.
* @param onDragStarted The function that is called when the item starts being dragged
* @param onDragStopped The function that is called when the item stops being dragged
*/
override fun Modifier.draggableHandle(
enabled: Boolean,
interactionSource: MutableInteractionSource?,
onDragStarted: (startedPosition: Offset) -> Unit,
onDragStopped: () -> Unit,
) = composed {
var handleOffset by remember { mutableStateOf(Offset.Zero) }
var handleSize by remember { mutableStateOf(IntSize.Zero) }
val coroutineScope = rememberCoroutineScope()
onGloballyPositioned {
handleOffset = it.positionInRoot()
handleSize = it.size
}.draggable(
key1 = reorderableLazyCollectionState,
enabled = enabled && (reorderableLazyCollectionState.isItemDragging(key).value || !reorderableLazyCollectionState.isAnyItemDragging),
interactionSource = interactionSource,
onDragStarted = {
coroutineScope.launch {
val handleOffsetRelativeToItem = handleOffset - itemPositionProvider()
val handleCenter = Offset(
handleOffsetRelativeToItem.x + handleSize.width / 2f,
handleOffsetRelativeToItem.y + handleSize.height / 2f
)
reorderableLazyCollectionState.onDragStart(key, handleCenter)
}
onDragStarted(it)
},
onDragStopped = {
reorderableLazyCollectionState.onDragStop()
onDragStopped()
},
onDrag = { change, dragAmount ->
change.consume()
reorderableLazyCollectionState.onDrag(dragAmount)
},
)
}
/**
* Make the UI element the draggable handle for the reorderable item. Drag will start only after a long press.
*
* @param enabled Whether or not drag is enabled
* @param interactionSource [MutableInteractionSource] that will be used to emit [DragInteraction.Start] when this draggable is being dragged
* @param onDragStarted The function that is called when the item starts being dragged
* @param onDragStopped The function that is called when the item stops being dragged
*/
override fun Modifier.longPressDraggableHandle(
enabled: Boolean,
interactionSource: MutableInteractionSource?,
onDragStarted: (startedPosition: Offset) -> Unit,
onDragStopped: () -> Unit,
) = composed {
var handleOffset by remember { mutableStateOf(Offset.Zero) }
var handleSize by remember { mutableStateOf(IntSize.Zero) }
val coroutineScope = rememberCoroutineScope()
onGloballyPositioned {
handleOffset = it.positionInRoot()
handleSize = it.size
}.longPressDraggable(
key1 = reorderableLazyCollectionState,
enabled = enabled && (reorderableLazyCollectionState.isItemDragging(key).value || !reorderableLazyCollectionState.isAnyItemDragging),
interactionSource = interactionSource,
onDragStarted = {
coroutineScope.launch {
val handleOffsetRelativeToItem = handleOffset - itemPositionProvider()
val handleCenter = Offset(
handleOffsetRelativeToItem.x + handleSize.width / 2f,
handleOffsetRelativeToItem.y + handleSize.height / 2f
)
reorderableLazyCollectionState.onDragStart(key, handleCenter)
}
onDragStarted(it)
},
onDragStopped = {
reorderableLazyCollectionState.onDragStop()
onDragStopped()
},
onDrag = { change, dragAmount ->
change.consume()
reorderableLazyCollectionState.onDrag(dragAmount)
},
)
}
}
/**
* A composable that allows items to be reordered by dragging.
*
* @param state The return value of [rememberReorderableLazyListState], [rememberReorderableLazyGridState], or [rememberReorderableLazyStaggeredGridState]
* @param key The key of the item, must be the same as the key passed to the parent composable
* @param enabled Whether or this item is reorderable. If true, the item will not move for other items but may still be draggable. To make an item not draggable, set `enable = false` in [Modifier.draggable] or [Modifier.longPressDraggable] instead.
* @param dragging Whether or not this item is currently being dragged
*/
@ExperimentalFoundationApi
@Composable
internal fun ReorderableCollectionItem(
state: ReorderableLazyCollectionState<*>,
key: Any,
modifier: Modifier = Modifier,
enabled: Boolean = true,
dragging: Boolean,
content: @Composable ReorderableCollectionItemScope.(isDragging: Boolean) -> Unit,
) {
var itemPosition by remember { mutableStateOf(Offset.Zero) }
Box(
modifier.onGloballyPositioned {
itemPosition = it.positionInRoot()
}
) {
ReorderableCollectionItemScopeImpl(
reorderableLazyCollectionState = state,
key = key,
itemPositionProvider = { itemPosition },
).content(dragging)
}
LaunchedEffect(state.reorderableKeys, enabled) {
if (enabled) {
state.reorderableKeys.add(key)
} else {
state.reorderableKeys.remove(key)
}
}
}