Skip to content

Commit 9c9bb76

Browse files
simonhampclaude
andauthored
Spring a snapping pan back when the finger rests before letting go (#223)
On Android a snapping one-axis pan picked its point from a velocity tracker that only ever saw move events. A finger held still and then lifted kept the speed of its last move, so a drag let go short of halfway still flung on to the next point. The drag now also notes when the finger lifts, in the Initial pass so it is known before the detector ends the drag. If the last move was more than 40ms before the lift it lets go with no velocity, which is how Android's own VelocityTracker treats the up event. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 830f555 commit 9c9bb76

3 files changed

Lines changed: 197 additions & 43 deletions

File tree

‎resources/android/GestureAreaRenderer.kt‎

Lines changed: 96 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ import com.nativephp.mobile.ui.nativerender.NodeView
5757
import com.nativephp.mobile.ui.nativerender.SharedValueStore
5858
import kotlinx.coroutines.CoroutineScope
5959
import kotlinx.coroutines.Job
60+
import kotlinx.coroutines.coroutineScope
6061
import kotlinx.coroutines.launch
6162
import kotlin.math.abs
6263
import kotlin.math.exp
@@ -482,11 +483,11 @@ object GestureAreaRenderer {
482483
// axes so `on_drag_end` can report an unbound one too.
483484
// A snapping axis follows the finger from where it was
484485
// when the drag began (rawX / rawY), with resistance
485-
// past its outer points, and the tracker's fling picks
486-
// the point it springs to on release.
486+
// past its outer points, and the fling it lets go with
487+
// picks the point it springs to on release.
487488
var rawX = 0f
488489
var rawY = 0f
489-
val velocity = VelocityTracker()
490+
val velocity = ReleaseVelocity()
490491
// A one-axis pan's trigger, if it has one, and whether the
491492
// pull is past its point.
492493
val pullsX = panXId != 0 && panYId == 0 && !triggerX.isEmpty
@@ -496,7 +497,7 @@ object GestureAreaRenderer {
496497
snapping.stop()
497498
rawX = if (panXId != 0) SharedValueStore.valueOf(panXId) else 0f
498499
rawY = if (panYId != 0) SharedValueStore.valueOf(panYId) else 0f
499-
velocity.resetTracking()
500+
velocity.reset()
500501
}
501502
val onDrag: (Offset, Offset) -> Unit = { bound, raw ->
502503
gestureX += raw.x.toDp().value
@@ -529,7 +530,7 @@ object GestureAreaRenderer {
529530
val onEnd: (Boolean) -> Unit = { lifted ->
530531
// px per second, into dp like the pan itself. A pull
531532
// always goes back to rest.
532-
val fling = velocity.calculateVelocity()
533+
val fling = velocity.atRelease()
533534
val x = when {
534535
panXId == 0 -> gestureX
535536
pullsX -> restX.also { snapping.to(panXId, it, scope) }
@@ -550,44 +551,50 @@ object GestureAreaRenderer {
550551
gestureX = 0f
551552
gestureY = 0f
552553
}
553-
when {
554-
// A pull: the same as below, but only a drag its own way.
555-
pullsX || pullsY -> detectPull(
556-
horizontal = pullsX,
557-
way = if (pullsX) triggerX.distance else triggerY.distance,
558-
onStart = onStart,
559-
onEnd = onEnd,
560-
) { change, dragAmount ->
561-
velocity.addPosition(change.uptimeMillis, change.position)
562-
val raw = change.position - change.previousPosition
563-
onDrag(if (pullsX) Offset(dragAmount, 0f) else Offset(0f, dragAmount), raw)
564-
}
565-
// One axis bound: detect on that axis only, so the
566-
// other direction stays free for an enclosing
567-
// scroll container.
568-
panXId != 0 && panYId == 0 -> detectHorizontalDragGestures(
569-
onDragStart = onStart,
570-
onDragEnd = { onEnd(true) },
571-
onDragCancel = { onEnd(false) },
572-
) { change, dragAmount ->
573-
velocity.addPosition(change.uptimeMillis, change.position)
574-
onDrag(Offset(dragAmount, 0f), change.position - change.previousPosition)
575-
}
576-
panXId == 0 && panYId != 0 -> detectVerticalDragGestures(
577-
onDragStart = onStart,
578-
onDragEnd = { onEnd(true) },
579-
onDragCancel = { onEnd(false) },
580-
) { change, dragAmount ->
581-
velocity.addPosition(change.uptimeMillis, change.position)
582-
onDrag(Offset(0f, dragAmount), change.position - change.previousPosition)
583-
}
584-
else -> detectDragGestures(
585-
onDragStart = onStart,
586-
onDragEnd = { onEnd(true) },
587-
onDragCancel = { onEnd(false) },
588-
) { change, dragAmount ->
589-
velocity.addPosition(change.uptimeMillis, change.position)
590-
onDrag(dragAmount, dragAmount)
554+
coroutineScope {
555+
// The detectors below end a drag without saying
556+
// when the finger lifted, so hear that here first,
557+
// for the fling a snap settles by.
558+
if (!snapX.isEmpty || !snapY.isEmpty) launch { velocity.watchLifts(this@pointerInput) }
559+
when {
560+
// A pull: the same as below, but only a drag its own way.
561+
pullsX || pullsY -> detectPull(
562+
horizontal = pullsX,
563+
way = if (pullsX) triggerX.distance else triggerY.distance,
564+
onStart = onStart,
565+
onEnd = onEnd,
566+
) { change, dragAmount ->
567+
velocity.add(change)
568+
val raw = change.position - change.previousPosition
569+
onDrag(if (pullsX) Offset(dragAmount, 0f) else Offset(0f, dragAmount), raw)
570+
}
571+
// One axis bound: detect on that axis only, so the
572+
// other direction stays free for an enclosing
573+
// scroll container.
574+
panXId != 0 && panYId == 0 -> detectHorizontalDragGestures(
575+
onDragStart = onStart,
576+
onDragEnd = { onEnd(true) },
577+
onDragCancel = { onEnd(false) },
578+
) { change, dragAmount ->
579+
velocity.add(change)
580+
onDrag(Offset(dragAmount, 0f), change.position - change.previousPosition)
581+
}
582+
panXId == 0 && panYId != 0 -> detectVerticalDragGestures(
583+
onDragStart = onStart,
584+
onDragEnd = { onEnd(true) },
585+
onDragCancel = { onEnd(false) },
586+
) { change, dragAmount ->
587+
velocity.add(change)
588+
onDrag(Offset(0f, dragAmount), change.position - change.previousPosition)
589+
}
590+
else -> detectDragGestures(
591+
onDragStart = onStart,
592+
onDragEnd = { onEnd(true) },
593+
onDragCancel = { onEnd(false) },
594+
) { change, dragAmount ->
595+
velocity.add(change)
596+
onDrag(dragAmount, dragAmount)
597+
}
591598
}
592599
}
593600
}
@@ -1188,6 +1195,52 @@ object GestureAreaRenderer {
11881195
!isEmpty && if (distance < 0f) offset <= distance else offset >= distance
11891196
}
11901197

1198+
/**
1199+
* The speed a drag lets go with, in px per second. A tracker fed only
1200+
* the moves the drag detectors pass on keeps the last move's speed
1201+
* however long the finger then rests, so a drag held still and let go
1202+
* short of halfway would fling on to the next snap point. Told when the
1203+
* finger lifted, a finger that hadn't moved for more than 40ms before
1204+
* lets go with none, as Android's own VelocityTracker judges it from
1205+
* the up event.
1206+
*/
1207+
private class ReleaseVelocity {
1208+
private val tracker = VelocityTracker()
1209+
private var lastMove = 0L
1210+
private var liftedAt = 0L
1211+
1212+
fun reset() {
1213+
tracker.resetTracking()
1214+
lastMove = 0L
1215+
liftedAt = 0L
1216+
}
1217+
1218+
fun add(change: PointerInputChange) {
1219+
tracker.addPosition(change.uptimeMillis, change.position)
1220+
lastMove = change.uptimeMillis
1221+
}
1222+
1223+
/**
1224+
* Notes each finger that lifts. The Initial pass reaches here before
1225+
* a drag detector's Main pass ends the drag on the same event.
1226+
*/
1227+
suspend fun watchLifts(scope: PointerInputScope) = scope.awaitPointerEventScope {
1228+
while (true) {
1229+
awaitPointerEvent(PointerEventPass.Initial).changes.forEach {
1230+
if (it.changedToUpIgnoreConsumed()) liftedAt = it.uptimeMillis
1231+
}
1232+
}
1233+
}
1234+
1235+
fun atRelease(): Velocity =
1236+
if (liftedAt - lastMove > StoppedMillis) Velocity.Zero else tracker.calculateVelocity()
1237+
1238+
private companion object {
1239+
/** Android's own: no move for this long before the finger lifts means it had stopped. */
1240+
const val StoppedMillis = 40L
1241+
}
1242+
}
1243+
11911244
/** Springs a snapping or trigger axis to where it rests, on release or a PHP write-back. */
11921245
private class SnapPan {
11931246
private var job: Job? = null

‎tests/android/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ scroll container, and a bound pan still follows the finger. `NodeView` here
2727
stands in for core's: each child is a fixed-size box, clickable like a core
2828
`pressable` when it has a press handler.
2929

30+
`GestureAreaSnapTest` drags a snapping pan (`pan-y-snap`) quickly to short of
31+
halfway. Held still before it lifts, it springs back to 0 rather than flinging
32+
on with the speed of its last move. Let go while moving, or moving again after
33+
a pause, it carries on to the far point.
34+
3035
`GestureAreaTriggerTest` pulls a pan with a trigger point (`pan-x-trigger`):
3136
let go past the point it fires `@trigger` and springs back, short of it or
3237
after coming back under it it only springs back, the haptic plays each time
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package com.nativephp.plugins.native_ui.ui
2+
3+
import androidx.compose.ui.Modifier
4+
import androidx.compose.ui.geometry.Offset
5+
import androidx.compose.ui.test.*
6+
import androidx.compose.ui.test.junit4.createComposeRule
7+
import androidx.compose.ui.unit.dp
8+
import com.nativephp.mobile.ui.nativerender.*
9+
import org.junit.After
10+
import org.junit.Assert.assertEquals
11+
import org.junit.Before
12+
import org.junit.Rule
13+
import org.junit.Test
14+
import org.junit.runner.RunWith
15+
import org.robolectric.RobolectricTestRunner
16+
import org.robolectric.annotation.Config
17+
18+
/**
19+
* A snapping pan (`pan-y-snap`) settles on the point nearest where the
20+
* finger's speed would carry it. A finger that stopped before it lifted
21+
* has no speed left, so it settles on the point nearest where it is.
22+
*/
23+
@RunWith(RobolectricTestRunner::class)
24+
@Config(sdk = [35])
25+
class GestureAreaSnapTest {
26+
@get:Rule val compose = createComposeRule()
27+
28+
/** A settle cut short by the last test's teardown leaves the pan where it was. */
29+
@Before fun rest() {
30+
SharedValueStore.set(PanId, 0f)
31+
}
32+
33+
@After fun reset() {
34+
NativeUIBridge.events.clear()
35+
}
36+
37+
@Test fun dragHeldStillThenLetGoShortOfHalfwaySpringsBack() {
38+
render()
39+
compose.onNodeWithTag("node-2").performTouchInput {
40+
drag()
41+
// No moves while the finger rests, as on a device.
42+
advanceEventTime(200)
43+
up()
44+
}
45+
compose.runOnIdle {
46+
assertEquals(0f, SharedValueStore.valueOf(PanId), 0.01f)
47+
assertEquals(listOf("change:8:0.0,0.0"), events())
48+
}
49+
}
50+
51+
@Test fun flickLetGoShortOfHalfwayCarriesToTheFarPoint() {
52+
render()
53+
compose.onNodeWithTag("node-2").performTouchInput {
54+
drag()
55+
up()
56+
}
57+
compose.runOnIdle {
58+
assertEquals(600f, SharedValueStore.valueOf(PanId), 0.01f)
59+
assertEquals(listOf("change:8:0.0,600.0"), events())
60+
}
61+
}
62+
63+
@Test fun flickAfterAPauseStillCarriesToTheFarPoint() {
64+
render()
65+
compose.onNodeWithTag("node-2").performTouchInput {
66+
drag()
67+
advanceEventTime(200)
68+
repeat(3) { moveBy(Offset(0f, 25.dp.toPx())) }
69+
up()
70+
}
71+
compose.runOnIdle { assertEquals(600f, SharedValueStore.valueOf(PanId), 0.01f) }
72+
}
73+
74+
/** About 190dp down (200 less touch slop) at 25dp a frame: under halfway, but quick. */
75+
private fun TouchInjectionScope.drag() {
76+
down(center)
77+
repeat(8) { moveBy(Offset(0f, 25.dp.toPx())) }
78+
}
79+
80+
private fun render() {
81+
compose.setContent { GestureAreaRenderer.Render(area(), Modifier) }
82+
}
83+
84+
private fun events() = NativeUIBridge.events.filter { it.startsWith("change:8:") }
85+
86+
private fun area() = NativeUINode(
87+
1, "", null, null,
88+
GenericProps(mapOf("pan-y-id" to PanId, "pan-y-initial" to 0f, "pan-y-snap" to "-600,0,600", "on_drag_end" to 8)),
89+
0, 0, listOf(NativeUINode(2, "", null, null, GenericProps(emptyMap()), 0, 0, emptyList())),
90+
)
91+
92+
private companion object {
93+
/** Its own SharedValue, so no other test's pan moves it. */
94+
const val PanId = 4401
95+
}
96+
}

0 commit comments

Comments
 (0)