Thracian
Thracian

Reputation: 66516

How does drag work and interact with scroll and scrollable Composables like Pager, BottomSheet or LazyLists?

This is a share your knowledge, Q&A-style to explain how drag works, and how it interacts with scroll which is used in LazyLists, Pagers, BottomSheets or using Modifier.scroll as these components do under the hood. I recently see some questions that people don't understand how it works and why it doesn't get invoked with Pager and other scrollable Composables.

There are no answers about how drag checks threshold and invokes drag, why Pager doesn't allow drag or calling PointerInputChange.consume() has any effect, which doesn't have any, or when onDragCancel is invoked and most importantly implementing your own drag gesture that can work in any condition or any gesture based on your requirements.

This is how scroll and works with a Pager or any Composable with scroll in same orientation by default by modifying with parameters it's possible to invoke drag, scroll or both.

enter image description here

You can also refer question below

DetectDragGestures on HorizontalPager

And how to create a gesture to invoke drag conditionally to swipe a card out of a list

enter image description here

Upvotes: 4

Views: 283

Answers (1)

Thracian
Thracian

Reputation: 66516

How detectDragGestures work

detectDragGestures is a AwaitPointerEventScope function which can be called inside Modifier.pointerInput().

Modifier.pointerInput(Unit){
    detectDragGestures(
        onDragStart = {
            
        },
        onDrag = {change: PointerInputChange, dragAmount: Offset ->  
            
        },
        onDragEnd = {
            
        },
        onDragCancel = {
            
        }
    )
}

Source code of detectDragGestures

internal suspend fun PointerInputScope.detectDragGestures(
    onDragStart:
        (
            down: PointerInputChange, slopTriggerChange: PointerInputChange, overSlopOffset: Offset
        ) -> Unit,
    onDragEnd: (change: PointerInputChange) -> Unit,
    onDragCancel: () -> Unit,
    shouldAwaitTouchSlop: () -> Boolean,
    orientationLock: Orientation?,
    onDrag: (change: PointerInputChange, dragAmount: Offset) -> Unit
) {
    var overSlop: Offset

    awaitEachGesture {
        val initialDown = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
        val awaitTouchSlop = shouldAwaitTouchSlop()

        if (!awaitTouchSlop) {
            initialDown.consume()
        }
        val down = awaitFirstDown(requireUnconsumed = false)
        var drag: PointerInputChange?
        overSlop = Offset.Zero

        if (awaitTouchSlop) {
            do {
                drag =
                    awaitPointerSlopOrCancellation(
                        down.id,
                        down.type,
                        orientation = orientationLock
                    ) { change, over ->
                        change.consume()
                        overSlop = over
                    }
            } while (drag != null && !drag.isConsumed)
        } else {
            drag = initialDown
        }

        if (drag != null) {
            onDragStart.invoke(down, drag, overSlop)
            onDrag(drag, overSlop)
            val upEvent =
                drag(
                    pointerId = drag.id,
                    onDrag = {
                        onDrag(it, it.positionChange())
                        it.consume()
                    },
                    orientation = orientationLock,
                    motionConsumed = { it.isConsumed }
                )
            if (upEvent == null) {
                onDragCancel()
            } else {
                onDragEnd(upEvent)
            }
        }
    }
}

This is not the public one but public one only sets shouldAwaitTouchSlop true and orientation null which means can detect drag in x and y coordinates.

It initially checks val down = awaitFirstDown(requireUnconsumed = false) with requireUnconsumed false which means no other first touch or awaitFirstDown event can prevent this check by consuming it previously. You can refer about consume and passes in this answer in more detail.

It means that you can call drag with Modifier.clickable or Button even though they consume down event.

After awaitFirstDown, next comes, most important part of drag which is waiting for passing pointer slope. It checks for passing threshold, or minimum amount of drag, inside awaitPointerSlopOrCancellation, and what happens inside this function is the reason drag doesn't get invoked with scroll modifier or any scrollable Composable in same orientation.

Source code

private suspend inline fun AwaitPointerEventScope.awaitPointerSlopOrCancellation(
    pointerId: PointerId,
    pointerType: PointerType,
    orientation: Orientation?,
    onPointerSlopReached: (PointerInputChange, Offset) -> Unit,
): PointerInputChange? {
    if (currentEvent.isPointerUp(pointerId)) {
        return null // The pointer has already been lifted, so the gesture is canceled
    }
    val touchSlop = viewConfiguration.pointerSlop(pointerType)
    var pointer: PointerId = pointerId
    val touchSlopDetector = TouchSlopDetector(orientation)
    while (true) {
        val event = awaitPointerEvent()
        val dragEvent = event.changes.fastFirstOrNull { it.id == pointer } ?: return null
        if (dragEvent.isConsumed) {
            return null
        } else if (dragEvent.changedToUpIgnoreConsumed()) {
            val otherDown = event.changes.fastFirstOrNull { it.pressed }
            if (otherDown == null) {
                // This is the last "up"
                return null
            } else {
                pointer = otherDown.id
            }
        } else {
            val postSlopOffset = touchSlopDetector.addPointerInputChange(dragEvent, touchSlop)
            if (postSlopOffset.isSpecified) {
                onPointerSlopReached(dragEvent, postSlopOffset)
                if (dragEvent.isConsumed) {
                    return dragEvent
                } else {
                    touchSlopDetector.reset()
                }
            } else {
                // verify that nothing else consumed the drag event
                awaitPointerEvent(PointerEventPass.Final)
                if (dragEvent.isConsumed) {
                    return null
                }
            }
        }
    }
}

The lines dragEvent.isConsumed where it checks if it has been consumed before, scroll consumes this and it returns true, then after there is another check in final pass, this is for checking if anything started consuming in the mean time TouchSlopDetector measurements happen.

After this pass returns nullable drag:PointerInputChange? inside detectDragGestures

       drag =
                    awaitPointerSlopOrCancellation(
                        down.id,
                        down.type,
                        orientation = orientationLock
                    ) { change, over ->
                        change.consume()
                       

if drag is not null and if any other gesture didn't consume during slope check drag gets invoked

internal suspend inline fun AwaitPointerEventScope.drag(
    pointerId: PointerId,
    onDrag: (PointerInputChange) -> Unit,
    orientation: Orientation?,
    motionConsumed: (PointerInputChange) -> Boolean
): PointerInputChange? {
    if (currentEvent.isPointerUp(pointerId)) {
        return null // The pointer has already been lifted, so the gesture is canceled
    }
    var pointer = pointerId
    while (true) {
        val change =
            awaitDragOrUp(pointer) {
                val positionChange = it.positionChangeIgnoreConsumed()
                val motionChange =
                    if (orientation == null) {
                        positionChange.getDistance()
                    } else {
                        if (orientation == Orientation.Vertical) positionChange.y
                        else positionChange.x
                    }
                motionChange != 0.0f
            } ?: return null

        if (motionConsumed(change)) {
            return null
        }

        if (change.changedToUpIgnoreConsumed()) {
            return change
        }

        onDrag(change)
        pointer = change.id
    }
}

drag calls awaitDragOrUp that calls awaitPointerEvent that checks if current pointer with pointerId is dragging, this means if you put down 2 fingers and move first one second one continues drag. The line where motionConsumed(change) is invoked inside detectDragGestures as

           val upEvent =
                drag(
                    pointerId = drag.id,
                    onDrag = {
                        onDrag(it, it.positionChange())
                        it.consume()
                    },
                    orientation = orientationLock,
                    motionConsumed = { it.isConsumed }
                )

As you can see motionConsumed checks if it.isConsumed, this is the part drag is canceled even if you change how you check slope and pass it by not checking if it has been consumed.

If you add a condition to motionConsumed = { it.isConsumed and another condition} and to awaitPointerSlopOrCancellation it's possible to create a drag gesture can work with any other drag or scrollable, continuous movement gesture.

Another side note, calling it.consume() has no effect in onDrag callback. If you check onDrag callback of drag you will see that consume() is called after the callback. Since it's already called on line above your code, it has no effect. Drag prevents other events if they check consume flag for awaitPointerEvent.

And based on upEvent is null or not onDragEnd or onDragCancel is called. onDragEnd is the callback that is almost always called. It has no bounds check like button, even if you move your finger out of Composable with this modifier drag still continue to be invoked and when you lift last pointer this callback is invoked.

For onDragCancel to be invoked while dragging another continuous gesture should consume.

How to create a custom drag gesture to work with other gestures

There are 3 things for any gesture to work with any other gesture in harmony. 1- A flag to require consuming in condition specified 2- Exposing PointerInputChange to consume when required 3- And PointerEventPass to change propagation direction. For ie, before scroll or transform, etc.

And for drag you can also add option to check slope because it takes time and during that time scroll can already be invoked.

I created a sample like this, full code is available here, also will add it to gesture library as well.

suspend fun PointerInputScope.detectDragGesture(
    shouldAwaitTouchSlop: Boolean = true,
    requireUnconsumed: Boolean = true,
    pass: PointerEventPass = PointerEventPass.Main,
    onDragStart: (change: PointerInputChange, initialDelta: Offset) -> Unit = { _, _ -> },
    onDragEnd: (change: PointerInputChange) -> Unit = {},
    onDragCancel: () -> Unit = {},
    onDrag: (change: PointerInputChange, dragAmount: Offset) -> Unit,
) {
    awaitEachGesture {
        val initialDown =
            awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)

        if (!shouldAwaitTouchSlop) {
            initialDown.consume()
        }
        val down = awaitFirstDown(requireUnconsumed = false)

        var drag: PointerInputChange?
        var overSlop = Offset.Zero
        var initialDelta = Offset.Zero

        if (shouldAwaitTouchSlop) {
            do {
                drag = awaitTouchSlopOrCancellation(
                    pointerId = down.id,
                    requireUnconsumed = requireUnconsumed,
                ) { change, over ->
                    change.consume()
                    overSlop = over
                }

            } while (drag != null && !drag.isConsumed)

            initialDelta = overSlop
        } else {
            drag = initialDown
        }

        if (drag != null) {
            onDragStart.invoke(drag, initialDelta)
            onDrag(drag, overSlop)

            val upEvent = drag(
                pointerId = drag.id,
                pass = pass,
                onDrag = {
                    val dragAmount = if (requireUnconsumed)
                        it.positionChange() else
                        it.positionChangeIgnoreConsumed()
                    onDrag(it, dragAmount)
                },
                orientation = null,
                motionConsumed = {
                    it.isConsumed && requireUnconsumed
                }
            )
            if (upEvent == null) {
                onDragCancel()
            } else {
                onDragEnd(upEvent)
            }
        }
    }
}

it adds pass and requireUnconsumed to awaitTouchSlopOrCancellation and drag and doesn't call consume() inside onDrag and sets consume condition based on requiredConsumed.

val upEvent = drag(
    pointerId = drag.id,
    pass = pass,
    onDrag = {
        val dragAmount = if (requireUnconsumed)
            it.positionChange() else
            it.positionChangeIgnoreConsumed()
        onDrag(it, dragAmount)
    },
    orientation = null,
    motionConsumed = {
        it.isConsumed && requireUnconsumed
    }
)

Upvotes: 4

Related Questions