diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 710bc14..46c1350 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -72,6 +72,17 @@ class FlumeView(context: Context) : FrameLayout(context) { private val jumps = JumpGate() 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 @@ -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)) @@ -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 } + // 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() { @@ -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() @@ -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 @@ -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() @@ -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)) { @@ -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) @@ -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() @@ -503,6 +594,7 @@ class FlumeView(context: Context) : FrameLayout(context) { ) } } + scroller.onStopped = { if (token == scrollToken) landCommand() } layoutManager.startSmoothScroll(scroller) return } @@ -510,6 +602,7 @@ class FlumeView(context: Context) : FrameLayout(context) { 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. @@ -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. @@ -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 -> @@ -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) @@ -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() } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index 2715f92..211a17f 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -38,6 +38,7 @@ class FlumeViewManager : ViewGroupManager(), 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) @@ -70,6 +71,7 @@ class FlumeViewManager : ViewGroupManager(), 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) @@ -312,12 +314,19 @@ class FlumeViewManager : ViewGroupManager(), 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) diff --git a/android/src/main/java/me/sectiontn/flume/ScrollEvents.kt b/android/src/main/java/me/sectiontn/flume/ScrollEvents.kt index 5e85e8e..92e6a46 100644 --- a/android/src/main/java/me/sectiontn/flume/ScrollEvents.kt +++ b/android/src/main/java/me/sectiontn/flume/ScrollEvents.kt @@ -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(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" + } +} diff --git a/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt b/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt index b24c637..9a1d9ca 100644 --- a/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt +++ b/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt @@ -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) diff --git a/android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt b/android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt index c984f4b..217dca2 100644 --- a/android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt +++ b/android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt @@ -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) + } } diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 11b2082..576f169 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -31,6 +31,7 @@ #include "adapter/EdgeTracker.h" #include "adapter/JumpGate.h" #include "adapter/ListRows.h" +#include "adapter/ScrollCommands.h" #include "adapter/ScrollTargets.h" #include "adapter/Viewability.h" #include "bindings/Engine.h" @@ -204,6 +205,9 @@ @implementation FLMView { BOOL _reclaimAfterGlide; // a glide's lent slots go back to the pool when it ends std::optional _realign; int _realigns; + flume::ScrollCommands _commands; + BOOL _commandGlides; // the command in flight started the glide running, so its end lands the command + BOOL _replacingGlide; // inside the setContentOffset that starts a glide } + (ComponentDescriptorProvider)componentDescriptorProvider @@ -719,6 +723,8 @@ - (void)scheduleOpening - (void)detach { + // Leaving the window or the store ends the command in flight, as a drag does. + [self endCommand]; if (!_attached) { return; } @@ -814,6 +820,8 @@ - (void)applyListOps:(const flume::ListOps &)ops count:(int)count } _realign.reset(); if (anchor.outcome == flume::AnchorOutcome::ScrollToEdge) { + // Anchoring's own scroll replaces the command in flight, as on Android. + [self endCommand]; _pendingTarget.reset(); [self dropJump]; [self scrollTo:[_layout offsetForVisualEdge:anchor.edge] animated:anchor.animated]; @@ -1100,6 +1108,7 @@ - (void)scrollViewDidScroll:(UIScrollView *)scrollView // React rows show bare under UIKit's own glide, so a list that can show them scrolls to its top through the jump gate. - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView { + [self endCommand]; if (_attached && _rows.dataCount > 0 && [self showsReactRows]) { // The visual top, which is the content end when inverted. const BOOL end = _inverted; @@ -1128,6 +1137,7 @@ - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView _pendingTarget.reset(); _gliding = NO; [self dropJump]; + [self endCommand]; [self reclaimGlideSlots]; // The list takes the touch, so no React handler under it may still press, as on Android. FLMCancelJSTouches(self); @@ -1175,6 +1185,8 @@ - (void)listDidLayout [weakSelf realignIfIdle]; }); } + // As Android settles on each layout pass, so a realign that new data cleared still ends its command. + [self settleCommand]; // A press starts only at rest, so the shadow tree learns where React rows show only then. const BOOL moving = _collectionView.isDragging || _collectionView.isDecelerating || _pendingTarget.has_value() || _gliding; if (!moving || !_collectionView.scrollEnabled) { @@ -1401,6 +1413,10 @@ - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView // Rows measured during the glide can move the target, so an animated command lands on it again. - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { + // The glide a new one replaces ends inside the new setContentOffset, and the new glide carries on. + if (_replacingGlide) { + return; + } _gliding = NO; if (_pendingTarget && _rows.dataCount > 0) { FLMPendingTarget target = *_pendingTarget; @@ -1414,6 +1430,13 @@ - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView [self reclaimGlideSlots]; [self emitScrollEvents:_scrollEvents.didEndScrollingAnimation() velocity:CGPointZero]; [self writeShadowOrigins]; + // Also after a touch stopped the glide, which UIKit ends here too. + if (std::exchange(_commandGlides, NO)) { + [self landCommand]; + } else { + // A command that landed without moving while this older glide ran ends at its rest. + [self settleCommand]; + } } #pragma mark - Presses @@ -1526,17 +1549,23 @@ - (void)scrollTo:(CGFloat)offset animated:(BOOL)animated if (std::fabs(offset - [self currentOffset]) <= 0.5) { _pendingTarget.reset(); [self reclaimGlideSlots]; + [self landCommand]; return; } if (animated) { _scrollEvents.scrolledProgrammatically(true); + _replacingGlide = YES; [_collectionView setContentOffset:[self pointAt:offset] animated:YES]; + _replacingGlide = NO; _gliding = YES; + // The end of this glide lands the command that started it. + _commandGlides = _commands.pending() != 0; return; } _gliding = NO; [_collectionView setContentOffset:[self pointAt:offset] animated:NO]; [self emitScrollEvents:_scrollEvents.scrolledProgrammatically(false) velocity:CGPointZero]; + [self landCommand]; } // The content start is the visual top, or the bottom when inverted. @@ -1671,6 +1700,7 @@ - (void)runJump:(const FLMJump &)jump [self requestSlotsFlush]; if (!_attached || _rows.dataCount == 0) { pool.reclaim(); + [self landCommand]; return; } if (jump.animated) { @@ -1745,6 +1775,7 @@ - (void)dropJump [_slots pool].reclaim(); [self requestSlotsFlush]; } + [self settleCommand]; } // After the next layout pass, so the rows the glide ends on bind their lent slots first. @@ -1771,11 +1802,48 @@ - (void)realignIfIdle _realigns++; [_collectionView setContentOffset:[self pointAt:offset] animated:NO]; } - return; - } - if ([self visibleSlotCellsShow]) { + } else if ([self visibleSlotCellsShow]) { _realign.reset(); } + [self settleCommand]; +} + +// A glide still running belongs to the command before, so its end lands nothing. +- (void)beginCommand:(NSInteger)requestId +{ + _commands.begin(static_cast(requestId)); + _commandGlides = NO; +} + +- (void)landCommand +{ + _commands.land(); + [self settleCommand]; +} + +// Ends the command once its own movement landed and the list rests. +- (void)settleCommand +{ + flume::ScrollCommands::Rest rest; + rest.moving = _collectionView.isDecelerating || _gliding || _pendingTarget.has_value(); + rest.dragging = _collectionView.isDragging; + rest.jumpWaiting = _jumps.pending().has_value() || _readyJump.has_value(); + rest.realignPending = _realign.has_value(); + [self emitCommandEnd:_commands.settle(rest)]; +} + +// A drag, the status bar, anchoring's own scroll or leaving the window ends the command in flight. +- (void)endCommand +{ + [self emitCommandEnd:_commands.end()]; +} + +- (void)emitCommandEnd:(int32_t)commandId +{ + auto emitter = std::static_pointer_cast(_eventEmitter); + if (commandId != 0 && emitter != nullptr) { + emitter->onScrollCommandEnd(FlumeViewEventEmitter::OnScrollCommandEnd{commandId}); + } } - (BOOL)visibleSlotCellsShow @@ -1811,9 +1879,15 @@ - (void)startScrollToTarget:(const FLMPendingTarget &)target animated:(BOOL)anim [self scrollTo:offset animated:YES]; } -- (void)scrollToIndex:(NSInteger)index animated:(BOOL)animated viewPosition:(double)viewPosition viewOffset:(double)viewOffset +- (void)scrollToIndex:(NSInteger)requestId + index:(NSInteger)index + animated:(BOOL)animated + viewPosition:(double)viewPosition + viewOffset:(double)viewOffset { + [self beginCommand:requestId]; if (!_attached) { + [self landCommand]; return; } [self scrollToTarget:FLMPendingTarget{FLMPendingTarget::Kind::Index, static_cast(index), viewPosition, viewOffset} @@ -1821,12 +1895,14 @@ - (void)scrollToIndex:(NSInteger)index animated:(BOOL)animated viewPosition:(dou } // The content start lands on measured rows; further offsets stay on the estimates. -- (void)scrollToOffset:(double)offset animated:(BOOL)animated +- (void)scrollToOffset:(NSInteger)requestId offset:(double)offset animated:(BOOL)animated { + [self beginCommand:requestId]; + [self dropJump]; if (!_attached || _rows.dataCount == 0) { + [self landCommand]; return; } - [self dropJump]; if (offset <= 0) { [self scrollToTarget:FLMPendingTarget{FLMPendingTarget::Kind::Start, 0, 0, 0} animated:animated]; return; @@ -1845,9 +1921,12 @@ - (void)scrollToOffset:(double)offset animated:(BOOL)animated animated:animated]; } -- (void)scrollToEnd:(BOOL)animated +- (void)scrollToEnd:(NSInteger)requestId animated:(BOOL)animated { + [self beginCommand:requestId]; if (!_attached || _rows.dataCount == 0) { + [self dropJump]; + [self landCommand]; return; } [self scrollToTarget:FLMPendingTarget{FLMPendingTarget::Kind::End, _rows.dataCount - 1, 1, 0} diff --git a/src/Flume.tsx b/src/Flume.tsx index 3a497ee..0b99684 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -126,6 +126,8 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { const prev = useRef<{ storeId: number; signature?: string; state?: DataState }>({ storeId }); const warned = useRef({ duplicates: false, messages: new Set() }); const nativeRef = useRef>(null); + // Native reports the end of a scroll command by this id, which only grows. + const commandId = useRef(0); // React Native's RefreshControl rule: a pull starts native refreshing, so an unchanged prop is sent back. const wantsRefreshing = refresh.refreshing; const nativeRefreshing = useRef(wantsRefreshing); @@ -464,15 +466,23 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { if (index < 0 || index >= count.current) { warn(`scrollToIndex: index ${index} is out of range for ${count.current} items`); } - Commands.scrollToIndex(native, index, animated, viewPosition, viewOffset); + Commands.scrollToIndex( + native, + ++commandId.current, + index, + animated, + viewPosition, + viewOffset, + ); }, scrollToOffset: ({ offset, animated = true }) => { const native = nativeRef.current; - if (native !== null) Commands.scrollToOffset(native, offset, animated); + if (native !== null) Commands.scrollToOffset(native, ++commandId.current, offset, animated); }, scrollToEnd: (params) => { const native = nativeRef.current; - if (native !== null) Commands.scrollToEnd(native, params?.animated ?? true); + if (native !== null) + Commands.scrollToEnd(native, ++commandId.current, params?.animated ?? true); }, getScrollableNode: () => nativeRef.current, getAnimatableRef: () => nativeRef.current, diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index c67ed95..0db4653 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -840,7 +840,7 @@ describe('Flume ref', () => { vi.resetModules(); }); - it('sends the commands with FlatList defaults', async () => { + it('sends the commands with FlatList defaults and a growing id', async () => { installHost(); const { Flume } = await import('../Flume'); const { Commands } = await import('../specs/FlumeViewNativeComponent'); @@ -849,9 +849,9 @@ describe('Flume ref', () => { ref.current?.scrollToIndex({ index: 0 }); ref.current?.scrollToOffset({ offset: 20, animated: false }); ref.current?.scrollToEnd(); - expect(Commands.scrollToIndex).toHaveBeenCalledWith(expect.anything(), 0, true, 0, 0); - expect(Commands.scrollToOffset).toHaveBeenCalledWith(expect.anything(), 20, false); - expect(Commands.scrollToEnd).toHaveBeenCalledWith(expect.anything(), true); + expect(Commands.scrollToIndex).toHaveBeenCalledWith(expect.anything(), 1, 0, true, 0, 0); + expect(Commands.scrollToOffset).toHaveBeenCalledWith(expect.anything(), 2, 20, false); + expect(Commands.scrollToEnd).toHaveBeenCalledWith(expect.anything(), 3, true); }); }); diff --git a/src/specs/FlumeViewNativeComponent.ts b/src/specs/FlumeViewNativeComponent.ts index 59fc64c..0f45794 100644 --- a/src/specs/FlumeViewNativeComponent.ts +++ b/src/specs/FlumeViewNativeComponent.ts @@ -153,14 +153,17 @@ export interface NativeProps extends ViewProps { >; onRefresh?: CodegenTypes.DirectEventHandler; onSlotsChanged?: CodegenTypes.DirectEventHandler; + // Every scroll command up to id has ended. + onScrollCommandEnd?: CodegenTypes.DirectEventHandler>; } type FlumeViewType = HostComponent; -// viewPosition is in content order; offsets are in dp. +// viewPosition is in content order and offsets are in dp. requestId grows per command and comes back in onScrollCommandEnd. interface NativeCommands { scrollToIndex: ( viewRef: React.ElementRef, + requestId: CodegenTypes.Int32, index: CodegenTypes.Int32, animated: boolean, viewPosition: CodegenTypes.Double, @@ -168,10 +171,15 @@ interface NativeCommands { ) => void; scrollToOffset: ( viewRef: React.ElementRef, + requestId: CodegenTypes.Int32, offset: CodegenTypes.Double, animated: boolean, ) => void; - scrollToEnd: (viewRef: React.ElementRef, animated: boolean) => void; + scrollToEnd: ( + viewRef: React.ElementRef, + requestId: CodegenTypes.Int32, + animated: boolean, + ) => void; // A pull starts refreshing natively; the wrapper sends the controlled prop back when it did not change. setNativeRefreshing: (viewRef: React.ElementRef, refreshing: boolean) => void; }