Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
128 changes: 119 additions & 9 deletions android/src/main/java/me/sectiontn/flume/FlumeView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ class FlumeView(context: Context) : FrameLayout(context) {

private val jumps = JumpGate<Jump>()
private val jumpDue = Runnable { jumps.due(SystemClock.uptimeMillis())?.let { runJump(it) } }
private val commands = ScrollCommands()
// The jump of the command in flight once it has run, which new data sends again at its target.
private var landing: Jump? = null
// The offset of the command's glide in flight, which a data reset sends again.
private var landingOffsetDp: Double? = null
// An instant scroll lands with the next layout pass, an offset glide at its first idle state after it moved.
private var landOnLayout = false
private var landOnIdle = false
private var movedSinceScroll = false
// Bumped by every scroll the view starts, so a stopped smooth scroller of an earlier one lands nothing.
private var scrollToken = 0
private var reclaimOnLayout = false
private var reclaimOnIdle = false
var emitScrollEvents = false
Expand Down Expand Up @@ -205,7 +216,10 @@ class FlumeView(context: Context) : FrameLayout(context) {
if (index >= 0) emitPress(index, FlumeJni.keyAt(storeId, index), pressId, long)
}
adapter.onFirstData = { applyInitialScroll() }
adapter.onAutoscroll = { position, viewPosition, animated -> requestJump(JumpTarget.Position(position), animated, viewPosition, 0.0) }
adapter.onAutoscroll = { position, viewPosition, animated ->
endScrollCommand()
requestJump(JumpTarget.Position(position), animated, viewPosition, 0.0)
}
refreshLayout.addView(recycler, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
refreshLayout.setOnRefreshListener { dispatch(FlumeRefreshEvent(UIManagerHelper.getSurfaceId(this), id)) }
addView(slots.parking, LayoutParams(0, 0))
Expand All @@ -214,12 +228,29 @@ class FlumeView(context: Context) : FrameLayout(context) {
addView(sticky.reactPinned, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
adapter.onDataChanged = { reset ->
viewability.invalidate()
// A command still on its way lands on its target in the new rows, not where anchoring keeps the old ones.
val again = landing?.takeIf { commands.pending != 0 && jumps.pending == null }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Only a reset stops an offset glide, so only a reset sends it again.
val againOffset = landingOffsetDp?.takeIf { reset && commands.pending != 0 }
if (again != null || againOffset != null) {
scrollToken++
pendingAlign = null
landOnIdle = false
// Begun again before stopScroll, whose idle state would end a command its scroller had landed.
commands.begin(commands.pending)
}
if (reset) {
recycler.stopScroll()
pendingAlign = null
}
applySpans()
retargetJump()
if (again != null) {
requestJump(again.target, again.animated, again.viewPosition, again.viewOffsetDp)
} else if (againOffset != null) {
scrollToOffset(commands.pending, againOffset, true)
} else {
retargetJump()
}
}
adapter.onStickyIndicesChanged = { applySpans() }
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
Expand All @@ -244,9 +275,11 @@ class FlumeView(context: Context) : FrameLayout(context) {
emitScroll(kind, afterDrag = scrollState == RecyclerView.SCROLL_STATE_DRAGGING)
}
scrollState = newState
if (newState == RecyclerView.SCROLL_STATE_SETTLING) movedSinceScroll = true
if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
pendingAlign = null
jumps.cancel()?.let { dropJump(it) }
endScrollCommand()
viewability.interacted = true
evaluateViewability()
if (keyboardDismissOnDrag) recycler.dismissKeyboard()
Expand All @@ -256,6 +289,11 @@ class FlumeView(context: Context) : FrameLayout(context) {
realign()
// Inline, so the state is queued before a touch the next looper turn delivers.
writeOrigins()
if (landOnIdle && movedSinceScroll) {
landOnIdle = false
commands.land()
}
settleCommand()
}
if (newState == RecyclerView.SCROLL_STATE_IDLE && reclaimOnIdle) {
reclaimOnIdle = false
Expand Down Expand Up @@ -321,6 +359,11 @@ class FlumeView(context: Context) : FrameLayout(context) {
removeCallbacks(realignAfterLayout)
post(realignAfterLayout)
}
if (landOnLayout) {
landOnLayout = false
commands.land()
}
settleCommand()
sticky.refresh()
updateEmptyLength()
updateFooterLength()
Expand Down Expand Up @@ -396,13 +439,19 @@ class FlumeView(context: Context) : FrameLayout(context) {
}

// index counts data items, as FlatList's does; the header and footer are reached by offset and scrollToEnd.
fun scrollToIndex(index: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) =
fun scrollToIndex(id: Int, index: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) {
commands.begin(id)
requestJump(JumpTarget.Index(index), animated, viewPosition, viewOffsetDp)
}

// React rows paint a frame or more after their bind, so a jump first has the rows it will show rendered.
private fun requestJump(target: JumpTarget, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) {
jumps.cancel()?.let { dropJump(it) }
if (target.position(rows) == null && !target.waitsForData(rows)) return
forgetLanding()
if (target.position(rows) == null && !target.waitsForData(rows)) {
landCommand()
return
}
val jump = Jump(target, animated, viewPosition, viewOffsetDp, adapter.allocateHolderId())
val waiting = reserveJump(jump)
if (waiting.isEmpty() && !target.waitsForData(rows)) {
Expand Down Expand Up @@ -436,11 +485,52 @@ class FlumeView(context: Context) : FrameLayout(context) {
private fun runJump(jump: Jump) {
removeCallbacks(jumpDue)
slots.lend(jump.owner)
val position = jump.target.position(rows) ?: return
val position = jump.target.position(rows) ?: return landCommand()
if (jump.animated) reclaimOnIdle = true else reclaimOnLayout = true
landing = jump
startScroll(position, jump.animated, jump.viewPosition, jump.viewOffsetDp)
}

// A new scroll replaces the landing of the one before it.
private fun forgetLanding() {
landing = null
landingOffsetDp = null
landOnLayout = false
landOnIdle = false
scrollToken++
}

private fun landCommand() {
commands.land()
settleCommand()
}

private fun settleCommand() {
val ended = commands.settle(
ScrollCommands.Rest(
moving = scrollState == RecyclerView.SCROLL_STATE_SETTLING,
dragging = scrollState == RecyclerView.SCROLL_STATE_DRAGGING,
jumpWaiting = jumps.pending != null,
realignPending = pendingAlign != null,
),
)
if (ended != 0) {
landing = null
landingOffsetDp = null
dispatch(FlumeScrollCommandEndEvent(UIManagerHelper.getSurfaceId(this), id, ended))
}
}

// A drag, leaving the window, anchoring's own scroll or a dropped view ends the command in flight.
fun endScrollCommand() {
landing = null
landingOffsetDp = null
landOnLayout = false
landOnIdle = false
val ended = commands.end()
if (ended != 0) dispatch(FlumeScrollCommandEndEvent(UIManagerHelper.getSurfaceId(this), id, ended))
}

private fun dropJump(jump: Jump) {
removeCallbacks(jumpDue)
slots.dropReserved(jump.owner)
Expand Down Expand Up @@ -471,7 +561,8 @@ class FlumeView(context: Context) : FrameLayout(context) {
}

private fun startScroll(position: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) {
val target = ScrollTargets.clampIndex(position, rows.itemCount) ?: return
val target = ScrollTargets.clampIndex(position, rows.itemCount) ?: return landCommand()
val token = scrollToken
viewability.interacted = true
recycler.stopScroll()
val viewOffsetPx = (viewOffsetDp * density).roundToInt()
Expand Down Expand Up @@ -503,13 +594,15 @@ class FlumeView(context: Context) : FrameLayout(context) {
)
}
}
scroller.onStopped = { if (token == scrollToken) landCommand() }
layoutManager.startSmoothScroll(scroller)
return
}
val viewportPx = if (geometry.horizontal) geometry.innerWidthPx else geometry.innerHeightPx
val itemPx = if (ScrollTargets.needsLength(viewPosition)) rowLengthPx(target) else 0
if (realigns) pendingAlign = PendingAlign(target, viewPosition, viewOffsetPx, itemPx, anchoredAtEnd = anchoredAtEnd)
layoutManager.scrollToPositionWithOffset(target, ScrollTargets.offsetPx(viewPosition, viewOffsetPx, viewportPx, itemPx))
landOnLayout = true
}

// RecyclerView drops a layout request made inside its own layout pass, so a correction found there waits for the pass to end.
Expand All @@ -531,6 +624,7 @@ class FlumeView(context: Context) : FrameLayout(context) {
} else if (offset != null || (target != null && reactRowsReady())) {
pendingAlign = null
}
settleCommand()
}

// The start as scrollToPositionWithOffset counts it: from the padded start edge, or from the end under a reversed layout.
Expand Down Expand Up @@ -625,11 +719,13 @@ class FlumeView(context: Context) : FrameLayout(context) {
}

// Offsets count from the content start; the visual delta flips for an inverted list.
fun scrollToOffset(offsetDp: Double, animated: Boolean) {
fun scrollToOffset(id: Int, offsetDp: Double, animated: Boolean) {
commands.begin(id)
viewability.interacted = true
// Before stopScroll, whose idle state would run an older command's realign.
pendingAlign = null
jumps.cancel()?.let { dropJump(it) }
forgetLanding()
recycler.stopScroll()
val targetPx = (offsetDp * density).roundToInt()
ScrollTargets.startRow(targetPx)?.let { row ->
Expand All @@ -641,10 +737,21 @@ class FlumeView(context: Context) : FrameLayout(context) {
val visual = if (inverted) -delta else delta
val dx = if (geometry.horizontal) visual else 0
val dy = if (geometry.horizontal) 0 else visual
if (animated) recycler.smoothScrollBy(dx, dy) else recycler.scrollBy(dx, dy)
if (visual != 0 && animated) {
movedSinceScroll = false
landOnIdle = true
landingOffsetDp = offsetDp
recycler.smoothScrollBy(dx, dy)
return
}
if (visual != 0) recycler.scrollBy(dx, dy)
landCommand()
}

fun scrollToEnd(animated: Boolean) = requestJump(JumpTarget.End, animated, 1f, 0.0)
fun scrollToEnd(id: Int, animated: Boolean) {
commands.begin(id)
requestJump(JumpTarget.End, animated, 1f, 0.0)
}

fun setListOverScrollMode(value: String?) {
recycler.overScrollMode = OverScroll.mode(value)
Expand Down Expand Up @@ -931,6 +1038,9 @@ class FlumeView(context: Context) : FrameLayout(context) {
override fun onDetachedFromWindow() {
dropMountListener()
adapter.detach()
// As on iOS, leaving the window ends a waiting jump and the command in flight.
jumps.cancel()?.let { dropJump(it) }
endScrollCommand()
super.onDetachedFromWindow()
}

Expand Down
17 changes: 13 additions & 4 deletions android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class FlumeViewManager : ViewGroupManager<FlumeView>(), FlumeViewManagerInterfac
}

override fun onDropViewInstance(view: FlumeView) {
view.endScrollCommand()
// A view dropped while detached registered its mount listener after its own detach cleanup.
view.dropMountListener()
view.setStateWrapper(null)
Expand Down Expand Up @@ -70,6 +71,7 @@ class FlumeViewManager : ViewGroupManager<FlumeView>(), FlumeViewManagerInterfac
FlumeEdgeEvent.START to mapOf("registrationName" to "onStartReached"),
FlumeRefreshEvent.NAME to mapOf("registrationName" to "onRefresh"),
FlumeSlotsEvent.NAME to mapOf("registrationName" to "onSlotsChanged"),
FlumeScrollCommandEndEvent.NAME to mapOf("registrationName" to "onScrollCommandEnd"),
)

@ReactProp(name = "itemAnimations", defaultBoolean = true)
Expand Down Expand Up @@ -312,12 +314,19 @@ class FlumeViewManager : ViewGroupManager<FlumeView>(), FlumeViewManagerInterfac
view.rowsPressable = value
}

override fun scrollToIndex(view: FlumeView, index: Int, animated: Boolean, viewPosition: Double, viewOffset: Double) =
view.scrollToIndex(index, animated, viewPosition.toFloat(), viewOffset)
override fun scrollToIndex(
view: FlumeView,
requestId: Int,
index: Int,
animated: Boolean,
viewPosition: Double,
viewOffset: Double,
) = view.scrollToIndex(requestId, index, animated, viewPosition.toFloat(), viewOffset)

override fun scrollToOffset(view: FlumeView, offset: Double, animated: Boolean) = view.scrollToOffset(offset, animated)
override fun scrollToOffset(view: FlumeView, requestId: Int, offset: Double, animated: Boolean) =
view.scrollToOffset(requestId, offset, animated)

override fun scrollToEnd(view: FlumeView, animated: Boolean) = view.scrollToEnd(animated)
override fun scrollToEnd(view: FlumeView, requestId: Int, animated: Boolean) = view.scrollToEnd(requestId, animated)

override fun setNativeRefreshing(view: FlumeView, refreshing: Boolean) = view.setNativeRefreshing(refreshing)

Expand Down
14 changes: 14 additions & 0 deletions android/src/main/java/me/sectiontn/flume/ScrollEvents.kt
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,17 @@ class FlumeScrollEvent(
putDouble("right", right.toDouble())
}
}

// Every scroll command up to commandId has ended. Never coalesced, so no end the wrapper waits for is replaced.
class FlumeScrollCommandEndEvent(surfaceId: Int, viewTag: Int, val commandId: Int) :
Event<FlumeScrollCommandEndEvent>(surfaceId, viewTag) {
override fun getEventName(): String = NAME

override fun canCoalesce(): Boolean = false

override fun getEventData(): WritableMap = Arguments.createMap().apply { putInt("id", commandId) }

companion object {
const val NAME = "topScrollCommandEnd"
}
}
7 changes: 7 additions & 0 deletions android/src/main/java/me/sectiontn/flume/ScrollTargets.kt
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@ class FlumeSmoothScroller(
private val msPerPx: Float? = null,
) : LinearSmoothScroller(context) {
var onTarget: ((View) -> Unit)? = null
// RecyclerView may still run the last segment after this, so the list rests only at its idle state.
var onStopped: (() -> Unit)? = null

override fun onStop() {
super.onStop()
onStopped?.invoke()
}

override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float = msPerPx ?: super.calculateSpeedPerPixel(displayMetrics)

Expand Down
10 changes: 10 additions & 0 deletions android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,14 @@ class ScrollEventsTest {
// Across a horizontal list: 4 left and 6 right of a 360 px viewport leave an extent of 350.
assertEquals(Pair(1000 - 350 + 360, 300), ScrollMetrics.contentSizePx(true, 1000, padding, 360, 300))
}

@Test
fun theCommandEndEventNeverCoalesces() {
assertFalse(FlumeScrollCommandEndEvent(1, 2, 7).canCoalesce())
}

@Test
fun theCommandEndEventCarriesTheId() {
assertEquals(7, FlumeScrollCommandEndEvent(1, 2, 7).commandId)
}
}
Loading
Loading