From 5e0814e3f1f8f49aecd0110fa2de90da860a958a Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 25 Nov 2026 09:05:20 +0100 Subject: [PATCH 01/17] feat: track the scroll command in flight on both platforms --- .../java/me/sectiontn/flume/ScrollCommands.kt | 38 +++++++++ .../me/sectiontn/flume/ScrollCommandsTest.kt | 83 +++++++++++++++++++ cpp/adapter/ScrollCommands.cpp | 28 +++++++ cpp/adapter/ScrollCommands.h | 32 +++++++ cpp/tests/scroll_commands_test.cpp | 78 +++++++++++++++++ 5 files changed, 259 insertions(+) create mode 100644 android/src/main/java/me/sectiontn/flume/ScrollCommands.kt create mode 100644 android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt create mode 100644 cpp/adapter/ScrollCommands.cpp create mode 100644 cpp/adapter/ScrollCommands.h create mode 100644 cpp/tests/scroll_commands_test.cpp diff --git a/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt new file mode 100644 index 0000000..a627926 --- /dev/null +++ b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt @@ -0,0 +1,38 @@ +package me.sectiontn.flume + +// The scroll command in flight: its id is reported once, when it settles at rest or is interrupted. +class ScrollCommands { + data class Rest(val moving: Boolean, val dragging: Boolean, val jumpWaiting: Boolean, val realignPending: Boolean) + + var pending = 0 + private set + private var landed = false + + fun begin(id: Int) { + pending = id + landed = false + } + + // The command's own movement has finished, so a list at rest ends it. + fun land() { + landed = pending != 0 + } + + // Ends the command in flight and returns its id, or 0 when there is none. + fun end(): Int { + val id = pending + reset() + return id + } + + // Ends the command once it has landed and the list rests, else returns 0. + fun settle(rest: Rest): Int { + if (!landed || rest.moving || rest.dragging || rest.jumpWaiting || rest.realignPending) return 0 + return end() + } + + fun reset() { + pending = 0 + landed = false + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt new file mode 100644 index 0000000..a41e0c2 --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt @@ -0,0 +1,83 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertEquals +import org.junit.Test + +class ScrollCommandsTest { + private val rest = ScrollCommands.Rest(moving = false, dragging = false, jumpWaiting = false, realignPending = false) + + @Test + fun endsTheCommandInFlightOnce() { + val commands = ScrollCommands() + commands.begin(3) + assertEquals(3, commands.pending) + assertEquals(3, commands.end()) + assertEquals(0, commands.pending) + assertEquals(0, commands.end()) + } + + @Test + fun reportsNothingWithNoCommand() { + val commands = ScrollCommands() + assertEquals(0, commands.end()) + assertEquals(0, commands.settle(rest)) + } + + @Test + fun aNewerCommandIsTheOneReported() { + val commands = ScrollCommands() + commands.begin(3) + commands.begin(4) + assertEquals(4, commands.end()) + } + + @Test + fun resetForgetsTheCommand() { + val commands = ScrollCommands() + commands.begin(3) + commands.land() + commands.reset() + assertEquals(0, commands.end()) + assertEquals(0, commands.settle(rest)) + } + + @Test + fun anEndAfterResetAndANewCommandReportsTheNewOne() { + val commands = ScrollCommands() + commands.begin(3) + commands.reset() + commands.begin(1) + assertEquals(1, commands.end()) + } + + @Test + fun settlesOnlyAtRest() { + val commands = ScrollCommands() + commands.begin(3) + commands.land() + assertEquals(0, commands.settle(rest.copy(moving = true))) + assertEquals(0, commands.settle(rest.copy(dragging = true))) + assertEquals(0, commands.settle(rest.copy(jumpWaiting = true))) + assertEquals(0, commands.settle(rest.copy(realignPending = true))) + assertEquals(3, commands.settle(rest)) + assertEquals(0, commands.settle(rest)) + } + + @Test + fun doesNotSettleBeforeItLands() { + val commands = ScrollCommands() + commands.begin(3) + assertEquals(0, commands.settle(rest)) + commands.land() + assertEquals(3, commands.settle(rest)) + } + + @Test + fun aNewerCommandClearsTheLandedMark() { + val commands = ScrollCommands() + commands.begin(3) + commands.land() + commands.begin(4) + assertEquals(0, commands.settle(rest)) + } +} diff --git a/cpp/adapter/ScrollCommands.cpp b/cpp/adapter/ScrollCommands.cpp new file mode 100644 index 0000000..f298d56 --- /dev/null +++ b/cpp/adapter/ScrollCommands.cpp @@ -0,0 +1,28 @@ +#include "adapter/ScrollCommands.h" + +namespace flume { + +void ScrollCommands::begin(int32_t id) { + id_ = id; + landed_ = false; +} + +void ScrollCommands::land() { landed_ = id_ != 0; } + +int32_t ScrollCommands::end() { + const int32_t id = id_; + reset(); + return id; +} + +int32_t ScrollCommands::settle(const Rest& rest) { + if (!landed_ || rest.moving || rest.dragging || rest.jumpWaiting || rest.realignPending) return 0; + return end(); +} + +void ScrollCommands::reset() { + id_ = 0; + landed_ = false; +} + +} // namespace flume diff --git a/cpp/adapter/ScrollCommands.h b/cpp/adapter/ScrollCommands.h new file mode 100644 index 0000000..3c4b5eb --- /dev/null +++ b/cpp/adapter/ScrollCommands.h @@ -0,0 +1,32 @@ +#pragma once + +#include + +namespace flume { + +// The scroll command in flight: its id is reported once, when it settles at rest or is interrupted. +class ScrollCommands { + public: + struct Rest { + bool moving = false; + bool dragging = false; + bool jumpWaiting = false; + bool realignPending = false; + }; + + void begin(int32_t id); + // The command's own movement has finished, so a list at rest ends it. + void land(); + // Ends the command in flight and returns its id, or 0 when there is none. + int32_t end(); + // Ends the command once it has landed and the list rests, else returns 0. + int32_t settle(const Rest& rest); + int32_t pending() const { return id_; } + void reset(); + + private: + int32_t id_ = 0; + bool landed_ = false; +}; + +} // namespace flume diff --git a/cpp/tests/scroll_commands_test.cpp b/cpp/tests/scroll_commands_test.cpp new file mode 100644 index 0000000..8f8f6c3 --- /dev/null +++ b/cpp/tests/scroll_commands_test.cpp @@ -0,0 +1,78 @@ +#include "doctest.h" + +#include "adapter/ScrollCommands.h" + +using namespace flume; + +namespace { + +constexpr ScrollCommands::Rest kRest{}; + +} // namespace + +TEST_CASE("ScrollCommands ends the command in flight once") { + ScrollCommands commands; + commands.begin(3); + CHECK(commands.pending() == 3); + CHECK(commands.end() == 3); + CHECK(commands.pending() == 0); + CHECK(commands.end() == 0); +} + +TEST_CASE("ScrollCommands reports nothing with no command") { + ScrollCommands commands; + CHECK(commands.end() == 0); + CHECK(commands.settle(kRest) == 0); +} + +TEST_CASE("ScrollCommands a newer command is the one reported") { + ScrollCommands commands; + commands.begin(3); + commands.begin(4); + CHECK(commands.end() == 4); +} + +TEST_CASE("ScrollCommands reset forgets the command") { + ScrollCommands commands; + commands.begin(3); + commands.land(); + commands.reset(); + CHECK(commands.end() == 0); + CHECK(commands.settle(kRest) == 0); +} + +TEST_CASE("ScrollCommands an end after reset and a new command reports the new one") { + ScrollCommands commands; + commands.begin(3); + commands.reset(); + commands.begin(1); + CHECK(commands.end() == 1); +} + +TEST_CASE("ScrollCommands settles only at rest") { + ScrollCommands commands; + commands.begin(3); + commands.land(); + CHECK(commands.settle({.moving = true}) == 0); + CHECK(commands.settle({.dragging = true}) == 0); + CHECK(commands.settle({.jumpWaiting = true}) == 0); + CHECK(commands.settle({.realignPending = true}) == 0); + CHECK(commands.settle(kRest) == 3); + CHECK(commands.settle(kRest) == 0); +} + +TEST_CASE("ScrollCommands does not settle before it lands") { + ScrollCommands commands; + commands.begin(3); + CHECK(commands.settle(kRest) == 0); + commands.land(); + CHECK(commands.settle(kRest) == 3); +} + +TEST_CASE("ScrollCommands a newer command clears the landed mark") { + ScrollCommands commands; + commands.begin(3); + commands.land(); + commands.begin(4); + CHECK(commands.settle(kRest) == 0); +} From 4838a4163cbbb193fa02fdef4635979399a7137f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 25 Nov 2026 09:35:06 +0100 Subject: [PATCH 02/17] fix: land a waiting scroll on its index after new data arrives setData(next) and scrollToIndex in one handler send the command before the data. On Android the waiting jump kept slots for the old keys, which never render, so it sat on the new top rows until its 1 s deadline. With a list shorter than the index, both platforms clamped to the old last row and stayed there (rows 94-99 on Android, 495-499 on iOS, for index 200). A data change now aims the waiting jump at its index in the new rows and keeps its deadline, and an index past the data waits for the data to grow. --- .../main/java/me/sectiontn/flume/FlumeView.kt | 51 ++++++++++------ .../main/java/me/sectiontn/flume/JumpGate.kt | 9 +++ .../java/me/sectiontn/flume/JumpTarget.kt | 21 +++++++ .../java/me/sectiontn/flume/JumpGateTest.kt | 33 ++++++++++ .../java/me/sectiontn/flume/JumpTargetTest.kt | 45 ++++++++++++++ cpp/adapter/JumpGate.h | 8 +++ cpp/tests/jump_gate_test.cpp | 29 +++++++++ ios/FLMView.mm | 60 ++++++++++++++++--- 8 files changed, 231 insertions(+), 25 deletions(-) create mode 100644 android/src/main/java/me/sectiontn/flume/JumpTarget.kt create mode 100644 android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index ac7df1e..84d578e 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -68,7 +68,7 @@ class FlumeView(context: Context) : FrameLayout(context) { get() = scrollState == RecyclerView.SCROLL_STATE_IDLE || !recycler.scrollEnabled // A jump onto React rows waits for the rows it shows; its retained slots are lent to their binds when it runs. - private data class Jump(val position: Int, val animated: Boolean, val viewPosition: Float, val viewOffsetDp: Double, val owner: Int) + private data class Jump(val target: JumpTarget, val animated: Boolean, val viewPosition: Float, val viewOffsetDp: Double, val owner: Int) private val jumps = JumpGate() private val jumpDue = Runnable { jumps.due(SystemClock.uptimeMillis())?.let { runJump(it) } } @@ -205,7 +205,7 @@ 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 -> scrollToPosition(position, animated, viewPosition, 0.0) } + adapter.onAutoscroll = { position, viewPosition, animated -> 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)) @@ -219,6 +219,7 @@ class FlumeView(context: Context) : FrameLayout(context) { pendingAlign = null } applySpans() + retargetJump() } adapter.onStickyIndicesChanged = { applySpans() } recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { @@ -395,21 +396,16 @@ 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) { - val target = ScrollTargets.clampIndex(index, rows.dataCount) ?: return - scrollToPosition(rows.position(target), animated, viewPosition, viewOffsetDp) - } + fun scrollToIndex(index: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) = + 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 scrollToPosition(position: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { - val target = ScrollTargets.clampIndex(position, rows.itemCount) ?: return + private fun requestJump(target: JumpTarget, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { jumps.cancel()?.let { dropJump(it) } - val owner = adapter.allocateHolderId() - val window = jumpWindow(target, animated, viewPosition) - val requests = window.filter { isReactRow(it) }.map { adapter.slotRequest(it, viewTypeAt(it)) } - val waiting = slots.reserve(owner, requests) - val jump = Jump(target, animated, viewPosition, viewOffsetDp, owner) - if (waiting.isEmpty()) { + if (target.position(rows) == null && !target.waitsForData(rows)) return + val jump = Jump(target, animated, viewPosition, viewOffsetDp, adapter.allocateHolderId()) + val waiting = reserveJump(jump) + if (waiting.isEmpty() && !target.waitsForData(rows)) { runJump(jump) return } @@ -418,11 +414,30 @@ class FlumeView(context: Context) : FrameLayout(context) { postDelayed(jumpDue, ScrollTargets.JUMP_WAIT_MS) } + // The slots of the React rows the jump shows that have not rendered yet. + private fun reserveJump(jump: Jump): Set { + val position = jump.target.position(rows) ?: return emptySet() + val window = jumpWindow(position, jump.animated, jump.viewPosition) + val requests = window.filter { isReactRow(it) }.map { adapter.slotRequest(it, viewTypeAt(it)) } + return slots.reserve(jump.owner, requests) + } + + // New data moves a waiting jump's target, so it waits for the new rows it shows, before the same deadline. + private fun retargetJump() { + val waiting = jumps.pending ?: return + slots.dropReserved(waiting.owner) + val jump = waiting.copy(owner = adapter.allocateHolderId()) + val slotsLeft = reserveJump(jump) + jumps.retarget(jump, slotsLeft) + if (slotsLeft.isEmpty() && !jump.target.waitsForData(rows)) jumps.cancel()?.let { runJump(it) } + } + private fun runJump(jump: Jump) { removeCallbacks(jumpDue) slots.lend(jump.owner) + val position = jump.target.position(rows) ?: return if (jump.animated) reclaimOnIdle = true else reclaimOnLayout = true - startScroll(jump.position, jump.animated, jump.viewPosition, jump.viewOffsetDp) + startScroll(position, jump.animated, jump.viewPosition, jump.viewOffsetDp) } private fun dropJump(jump: Jump) { @@ -617,7 +632,7 @@ class FlumeView(context: Context) : FrameLayout(context) { recycler.stopScroll() val targetPx = (offsetDp * density).roundToInt() ScrollTargets.startRow(targetPx)?.let { row -> - scrollToPosition(row, animated, 0f, 0.0) + requestJump(JumpTarget.Position(row), animated, 0f, 0.0) return } val (offsetPx, rangePx, extentPx) = scrollMetrics() @@ -628,7 +643,7 @@ class FlumeView(context: Context) : FrameLayout(context) { if (animated) recycler.smoothScrollBy(dx, dy) else recycler.scrollBy(dx, dy) } - fun scrollToEnd(animated: Boolean) = scrollToPosition(rows.itemCount - 1, animated, 1f, 0.0) + fun scrollToEnd(animated: Boolean) = requestJump(JumpTarget.End, animated, 1f, 0.0) fun setListOverScrollMode(value: String?) { recycler.overScrollMode = OverScroll.mode(value) @@ -789,7 +804,7 @@ class FlumeView(context: Context) : FrameLayout(context) { if (initialScrollIndex < rows.dataCount) { layoutManager.scrollToPositionWithOffset(ScrollTargets.initialPosition(initialScrollIndex, rows), 0) } else { - scrollToPosition(ScrollTargets.initialPosition(initialScrollIndex, rows), false, 1f, 0.0) + requestJump(JumpTarget.Position(ScrollTargets.initialPosition(initialScrollIndex, rows)), false, 1f, 0.0) } } diff --git a/android/src/main/java/me/sectiontn/flume/JumpGate.kt b/android/src/main/java/me/sectiontn/flume/JumpGate.kt index 38d59a4..ff677c5 100644 --- a/android/src/main/java/me/sectiontn/flume/JumpGate.kt +++ b/android/src/main/java/me/sectiontn/flume/JumpGate.kt @@ -16,6 +16,15 @@ class JumpGate(private val waitMs: Long = ScrollTargets.JUMP_WAIT_MS) { return replaced } + // Swaps the waiting jump for one aimed at new rows, keeping its deadline. Returns the old one, or null when none waits. + fun retarget(jump: J, slots: Set): J? { + val replaced = pending ?: return null + pending = jump + waiting.clear() + waiting.addAll(slots) + return replaced + } + fun rendered(slot: Int): J? { if (pending == null || !waiting.remove(slot) || waiting.isNotEmpty()) return null return take() diff --git a/android/src/main/java/me/sectiontn/flume/JumpTarget.kt b/android/src/main/java/me/sectiontn/flume/JumpTarget.kt new file mode 100644 index 0000000..ef3334b --- /dev/null +++ b/android/src/main/java/me/sectiontn/flume/JumpTarget.kt @@ -0,0 +1,21 @@ +package me.sectiontn.flume + +// A scroll command's target in data terms, so a jump that waits through a data change lands on the same index. +sealed interface JumpTarget { + data class Index(val index: Int) : JumpTarget + + // An adapter position, such as the content start or an edge anchoring scrolls to. + data class Position(val position: Int) : JumpTarget + + data object End : JumpTarget + + // The adapter position to land on, or null with no rows. + fun position(rows: ListRows): Int? = when (this) { + is Index -> ScrollTargets.clampIndex(index, rows.dataCount)?.let(rows::position) + is Position -> ScrollTargets.clampIndex(position, rows.itemCount) + End -> ScrollTargets.clampIndex(rows.itemCount - 1, rows.itemCount) + } + + // An index past the data waits for the data to grow, as when new data and the scroll come from one handler. + fun waitsForData(rows: ListRows): Boolean = this is Index && index >= rows.dataCount +} diff --git a/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt b/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt index 9d2baa9..a04beba 100644 --- a/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt +++ b/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt @@ -48,4 +48,37 @@ class JumpGateTest { assertNull(gate.rendered(5)) assertEquals("a", gate.pending) } + + @Test + fun aRetargetKeepsTheFirstDeadline() { + val gate = JumpGate(waitMs = 1000) + gate.request("a", setOf(1), nowMs = 0) + assertEquals("a", gate.retarget("b", setOf(2))) + assertNull(gate.due(nowMs = 999)) + assertEquals("b", gate.due(nowMs = 1000)) + } + + @Test + fun aRetargetWaitsForItsOwnSlots() { + val gate = JumpGate() + gate.request("a", setOf(1), nowMs = 0) + gate.retarget("b", setOf(2)) + assertNull(gate.rendered(1)) + assertEquals("b", gate.rendered(2)) + } + + @Test + fun aRetargetWithNoJumpWaitingDoesNothing() { + val gate = JumpGate() + assertNull(gate.retarget("b", setOf(2))) + assertNull(gate.pending) + } + + @Test + fun aJumpWithNoSlotsWaitsForItsDeadline() { + val gate = JumpGate(waitMs = 1000) + gate.request("a", emptySet(), nowMs = 0) + assertNull(gate.rendered(1)) + assertEquals("a", gate.due(nowMs = 1000)) + } } diff --git a/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt b/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt new file mode 100644 index 0000000..0a6fad4 --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt @@ -0,0 +1,45 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class JumpTargetTest { + private val rows = ListRows(header = true, dataCount = 10, footer = true) + + @Test + fun anIndexLandsOnItsDataRow() { + assertEquals(4, JumpTarget.Index(3).position(rows)) + assertFalse(JumpTarget.Index(3).waitsForData(rows)) + } + + @Test + fun anIndexPastTheDataLandsOnTheLastDataRowAndWaitsForData() { + assertEquals(10, JumpTarget.Index(20).position(rows)) + assertTrue(JumpTarget.Index(20).waitsForData(rows)) + assertTrue(JumpTarget.Index(10).waitsForData(rows)) + } + + @Test + fun theEndIsTheLastRowWithTheFooter() { + assertEquals(11, JumpTarget.End.position(rows)) + assertFalse(JumpTarget.End.waitsForData(rows)) + } + + @Test + fun aPositionStaysInsideTheRows() { + assertEquals(0, JumpTarget.Position(0).position(rows)) + assertEquals(11, JumpTarget.Position(50).position(rows)) + } + + @Test + fun noRowsHaveNoPosition() { + val empty = ListRows() + assertNull(JumpTarget.Index(0).position(empty)) + assertNull(JumpTarget.End.position(empty)) + assertNull(JumpTarget.Position(0).position(empty)) + assertTrue(JumpTarget.Index(0).waitsForData(empty)) + } +} diff --git a/cpp/adapter/JumpGate.h b/cpp/adapter/JumpGate.h index d65f69e..2ac4ec5 100644 --- a/cpp/adapter/JumpGate.h +++ b/cpp/adapter/JumpGate.h @@ -24,6 +24,14 @@ class JumpGate { return replaced; } + // Swaps the waiting jump for one aimed at new rows, keeping its deadline. Returns the old one, or nothing when none waits. + std::optional retarget(Jump jump, std::unordered_set slots) { + if (!pending_) return std::nullopt; + std::optional replaced = std::exchange(pending_, std::move(jump)); + waiting_ = std::move(slots); + return replaced; + } + std::optional rendered(int slot) { if (!pending_ || waiting_.erase(slot) == 0 || !waiting_.empty()) return std::nullopt; return take(); diff --git a/cpp/tests/jump_gate_test.cpp b/cpp/tests/jump_gate_test.cpp index 13d528e..51d4a64 100644 --- a/cpp/tests/jump_gate_test.cpp +++ b/cpp/tests/jump_gate_test.cpp @@ -44,3 +44,32 @@ TEST_CASE("a rendered slot of no jump is ignored") { CHECK_FALSE(gate.rendered(5)); CHECK(gate.pending() == "a"); } + +TEST_CASE("a retarget keeps the first deadline") { + JumpGate gate(1000); + gate.request("a", {1}, 0); + CHECK(gate.retarget("b", {2}) == "a"); + CHECK_FALSE(gate.due(999)); + CHECK(gate.due(1000) == "b"); +} + +TEST_CASE("a retarget waits for its own slots") { + JumpGate gate; + gate.request("a", {1}, 0); + gate.retarget("b", {2}); + CHECK_FALSE(gate.rendered(1)); + CHECK(gate.rendered(2) == "b"); +} + +TEST_CASE("a retarget with no jump waiting does nothing") { + JumpGate gate; + CHECK_FALSE(gate.retarget("b", {2})); + CHECK_FALSE(gate.pending()); +} + +TEST_CASE("a jump with no slots waits for its deadline") { + JumpGate gate(1000); + gate.request("a", {}, 0); + CHECK_FALSE(gate.rendered(1)); + CHECK(gate.due(1000) == "a"); +} diff --git a/ios/FLMView.mm b/ios/FLMView.mm index a564f08..ff2010d 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -767,6 +767,7 @@ - (void)applyListOps:(const flume::ListOps &)ops count:(int)count [self lendSlotCells]; [self reloadCollection]; [self scheduleOpening]; + [self retargetJump]; return; } const flume::AnchorDecision anchor = @@ -818,6 +819,7 @@ - (void)applyListOps:(const flume::ListOps &)ops count:(int)count [self scrollTo:[_layout offsetForVisualEdge:anchor.edge] animated:anchor.animated]; } [self reindexSlotCells]; + [self retargetJump]; } // Inserts and removes move rows without a rebind, so each slot's index follows its cell. @@ -1558,9 +1560,9 @@ - (void)scrollToTarget:(const FLMPendingTarget &)target animated:(BOOL)animated { [self dropJump]; const int owner = ++_nextHolderId; - const std::unordered_set waiting = [self reserveJumpTo:target animated:animated owner:owner]; + const std::unordered_set waiting = [self reserveJumpTo:[self landingFor:target] animated:animated owner:owner]; const FLMJump jump{target, static_cast(animated), owner}; - if (waiting.empty()) { + if (waiting.empty() && ![self waitsForData:target]) { [self runJump:jump]; return; } @@ -1676,12 +1678,57 @@ - (void)runJump:(const FLMJump &)jump } else { _reclaimSlots = YES; } + const FLMPendingTarget landing = [self landingFor:jump.target]; _realign.reset(); if (jump.timedOut) { - _realign = jump.target; + _realign = landing; _realigns = 0; } - [self startScrollToTarget:jump.target animated:jump.animated]; + [self startScrollToTarget:landing animated:jump.animated]; +} + +// The target on the rows there are now: an index past the data lands on the last item, the end on the new end. +- (FLMPendingTarget)landingFor:(const FLMPendingTarget &)target +{ + FLMPendingTarget landing = target; + if (target.kind == FLMPendingTarget::Kind::End) { + landing.index = std::max(0, _rows.dataCount - 1); + } else if (target.kind == FLMPendingTarget::Kind::Index) { + landing.index = flume::clampIndex(target.index, _rows.dataCount).value_or(0); + } + return landing; +} + +// An index past the data waits for the data to grow, as when new data and the scroll come from one handler. +- (BOOL)waitsForData:(const FLMPendingTarget &)target +{ + return target.kind == FLMPendingTarget::Kind::Index && target.index >= _rows.dataCount; +} + +// New data moves a waiting jump's target, so it waits for the new rows it shows, before the same deadline. +- (void)retargetJump +{ + if (!_jumps.pending()) { + return; + } + FLMJump jump = *_jumps.pending(); + flume::SlotPool &pool = [_slots pool]; + pool.lend(jump.owner); + pool.reclaim(); + jump.owner = ++_nextHolderId; + std::unordered_set waiting = [self reserveJumpTo:[self landingFor:jump.target] + animated:jump.animated + owner:jump.owner]; + const BOOL ready = waiting.empty() && ![self waitsForData:jump.target]; + _jumps.retarget(jump, std::move(waiting)); + [self requestSlotsFlush]; + if (ready) { + _readyJump = _jumps.cancel(); + __weak FLMView *weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [weakSelf runReadyJump]; + }); + } } // A drag, another command, a reload or leaving the window ends a waiting jump and gives its slots back. @@ -1765,11 +1812,10 @@ - (void)startScrollToTarget:(const FLMPendingTarget &)target animated:(BOOL)anim - (void)scrollToIndex:(NSInteger)index animated:(BOOL)animated viewPosition:(double)viewPosition viewOffset:(double)viewOffset { - if (!_attached || _rows.dataCount == 0) { + if (!_attached) { return; } - const int clamped = *flume::clampIndex(static_cast(index), _rows.dataCount); - [self scrollToTarget:FLMPendingTarget{FLMPendingTarget::Kind::Index, clamped, viewPosition, viewOffset} + [self scrollToTarget:FLMPendingTarget{FLMPendingTarget::Kind::Index, static_cast(index), viewPosition, viewOffset} animated:animated]; } From 9e0653c6984f7e61a8937d89f9a5539cdd3bef57 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 25 Nov 2026 10:30:05 +0100 Subject: [PATCH 03/17] feat(android): report when each scroll command ends Each scroll command now carries an id, and Android sends onScrollCommandEnd with it once the list rests: after the layout pass and realign of an instant scroll, at the idle state after a glide, and at once when nothing moves. A drag, leaving the window and anchoring's own scroll end the command early. New data sends a command still on its way to its target in the new rows, where anchoring used to put back the old top row and the list ended at its last row. --- .../main/java/me/sectiontn/flume/FlumeView.kt | 116 ++++++++++++++++-- .../me/sectiontn/flume/FlumeViewManager.kt | 17 ++- .../java/me/sectiontn/flume/ScrollEvents.kt | 14 +++ .../java/me/sectiontn/flume/ScrollTargets.kt | 7 ++ .../me/sectiontn/flume/ScrollEventsTest.kt | 10 ++ ios/FLMView.mm | 10 +- src/Flume.tsx | 16 ++- src/__tests__/Flume.test.tsx | 8 +- src/specs/FlumeViewNativeComponent.ts | 12 +- 9 files changed, 185 insertions(+), 25 deletions(-) diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 84d578e..0a95725 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -72,6 +72,15 @@ 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 + // 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 +214,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 +226,23 @@ 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 } + if (again != null) { + scrollToken++ + pendingAlign = null + } if (reset) { recycler.stopScroll() pendingAlign = null } applySpans() - retargetJump() + if (again != null) { + commands.begin(commands.pending) + requestJump(again.target, again.animated, again.viewPosition, again.viewOffsetDp) + } else { + retargetJump() + } } adapter.onStickyIndicesChanged = { applySpans() } recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { @@ -244,9 +267,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 +281,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 +351,11 @@ class FlumeView(context: Context) : FrameLayout(context) { removeCallbacks(realignAfterLayout) post(realignAfterLayout) } + if (landOnLayout) { + landOnLayout = false + commands.land() + } + settleCommand() sticky.refresh() updateEmptyLength() updateFooterLength() @@ -396,13 +431,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)) { @@ -435,11 +476,49 @@ 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 + 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 + 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 + 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) @@ -470,7 +549,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() @@ -502,6 +582,7 @@ class FlumeView(context: Context) : FrameLayout(context) { ) } } + scroller.onStopped = { if (token == scrollToken) landCommand() } layoutManager.startSmoothScroll(scroller) return } @@ -509,6 +590,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. @@ -530,6 +612,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. @@ -624,11 +707,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 -> @@ -640,10 +725,20 @@ 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 + 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) @@ -930,6 +1025,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 ff2010d..d10d191 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1810,7 +1810,11 @@ - (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 { if (!_attached) { return; @@ -1820,7 +1824,7 @@ - (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 { if (!_attached || _rows.dataCount == 0) { return; @@ -1844,7 +1848,7 @@ - (void)scrollToOffset:(double)offset animated:(BOOL)animated animated:animated]; } -- (void)scrollToEnd:(BOOL)animated +- (void)scrollToEnd:(NSInteger)requestId animated:(BOOL)animated { if (!_attached || _rows.dataCount == 0) { return; 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; } From 20dac39a928eddeb7297053ca94b7b10e4197b0d Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 17:51:12 +0100 Subject: [PATCH 04/17] feat(ios): report when each scroll command ends Each scroll command now sends onScrollCommandEnd with its id on iOS once the list rests: right after an instant scroll, at the end of a glide or a realign, and at once when nothing moves. A drag, the status bar, anchoring's own scroll and leaving the window end the command early. UIKit ends a glide that a newer scroll interrupts from inside that newer call, so only the end of the command's own glide lands it. --- ios/FLMView.mm | 73 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 4 deletions(-) diff --git a/ios/FLMView.mm b/ios/FLMView.mm index d10d191..7905579 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,8 @@ @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 } + (ComponentDescriptorProvider)componentDescriptorProvider @@ -719,6 +722,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 +819,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 +1107,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 +1136,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 +1184,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) { @@ -1414,6 +1425,10 @@ - (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]; + } } #pragma mark - Presses @@ -1526,17 +1541,21 @@ - (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); [_collectionView setContentOffset:[self pointAt:offset] animated:YES]; _gliding = YES; + // After the call, since UIKit ends a glide it interrupts inside 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 +1690,7 @@ - (void)runJump:(const FLMJump &)jump [self requestSlotsFlush]; if (!_attached || _rows.dataCount == 0) { pool.reclaim(); + [self landCommand]; return; } if (jump.animated) { @@ -1744,6 +1764,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. @@ -1770,11 +1791,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 @@ -1816,7 +1874,9 @@ - (void)scrollToIndex:(NSInteger)requestId 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} @@ -1826,10 +1886,12 @@ - (void)scrollToIndex:(NSInteger)requestId // The content start lands on measured rows; further offsets stay on the estimates. - (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; @@ -1850,7 +1912,10 @@ - (void)scrollToOffset:(NSInteger)requestId offset:(double)offset animated:(BOOL - (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} From ecc0e41a494bfe3d77720acd44b3012f03f98ecd Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 19:04:51 +0100 Subject: [PATCH 05/17] fix(ios): end a scroll whose glide replaces a running one An animated scroll sent while another glide ran never reported its end and jumped to its target instead of gliding. UIKit ends the replaced glide from inside the new setContentOffset call, and that callback re-landed on the new target, which stopped the new glide. The callback now ignores the glide being replaced, so the new one carries on and its own end lands the command. --- ios/FLMView.mm | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 7905579..5b48525 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -207,6 +207,7 @@ @implementation FLMView { 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 @@ -1412,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; @@ -1546,9 +1551,11 @@ - (void)scrollTo:(CGFloat)offset animated:(BOOL)animated } if (animated) { _scrollEvents.scrolledProgrammatically(true); + _replacingGlide = YES; [_collectionView setContentOffset:[self pointAt:offset] animated:YES]; + _replacingGlide = NO; _gliding = YES; - // After the call, since UIKit ends a glide it interrupts inside it. + // The end of this glide lands the command that started it. _commandGlides = _commands.pending() != 0; return; } From 9323cfdeceab3b413d7812127660c0b71de564c8 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 19:10:27 +0100 Subject: [PATCH 06/17] feat: return a Promise from the scroll methods scrollToIndex, scrollToOffset and scrollToEnd now return a Promise that resolves once the list rests after the scroll, or when a drag, a newer scroll or an unmount ends it first. A scroll sent in the same frame as new data is sent again after that data reaches native, under a new id the Promise follows, so setData and scrollToIndex from one handler land on the new rows. On iOS the first one could stop 1.5 rows past the index. The out-of-range warning now checks the index against the data at the end of that frame. --- src/Flume.tsx | 86 +++++++++++++------ src/__tests__/Flume.test.tsx | 150 +++++++++++++++++++++++++++++++++ src/__tests__/commands.test.ts | 105 +++++++++++++++++++++++ src/commands.ts | 36 ++++++++ src/types.ts | 7 +- 5 files changed, 353 insertions(+), 31 deletions(-) create mode 100644 src/__tests__/commands.test.ts create mode 100644 src/commands.ts diff --git a/src/Flume.tsx b/src/Flume.tsx index 0b99684..dd6e4db 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -19,6 +19,7 @@ import { import { type StyleProp, View, type ViewStyle } from 'react-native'; import { createSerializable } from 'react-native-worklets'; import { cellKinds, itemComponentCell, type ResolvedCell, resolveCell } from './cells'; +import { createScrollCommands } from './commands'; import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; import { FlumeSlot } from './FlumeSlot'; import { hostProps } from './foreign'; @@ -60,6 +61,9 @@ import type { ViewToken, } from './types'; +type NativeView = ComponentRef; +type RecentCommand = { send: (native: NativeView, id: number) => void; index?: number }; + // FlatList's rule for the list components: an element renders as given, a component through createElement. // A given style wraps it in a View, as FlatList and FlashList do. function componentElement( @@ -125,9 +129,11 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { const released = useRef(false); 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); + const nativeRef = useRef(null); + // Native reports the end of each scroll command by its id, which settles the command's Promise. + const [commands] = useState(createScrollCommands); + // The last scroll command until the next frame, sent again after data committed meanwhile. + const recent = useRef(null); // 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); @@ -289,7 +295,11 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { commit.diffMs, performance.now() - start, ); - }, [host, storeId, commit, report]); + // A scroll from this frame reached native before this data, so it goes again to land in the new rows. + const command = recent.current; + const native = nativeRef.current; + if (command !== null && native !== null) command.send(native, commands.move()); + }, [host, storeId, commit, report, commands]); useLayoutEffect(() => { const sent = sentSticky.current; @@ -456,38 +466,57 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { ); }); + // The index is checked once the frame ends, against the data a handler committed with the scroll. + const sendCommand = useCallback( + (send: RecentCommand['send'], index?: number): Promise => { + const native = nativeRef.current; + if (native === null) return Promise.resolve(); + const { id, done } = commands.start(); + send(native, id); + const command: RecentCommand = { send, index }; + recent.current = command; + requestAnimationFrame(() => { + if (recent.current !== command) return; + recent.current = null; + if (index !== undefined && (index < 0 || index >= count.current)) { + warn(`scrollToIndex: index ${index} is out of range for ${count.current} items`); + } + }); + return done; + }, + [commands, warn], + ); + const endCommand = useCallback( + (event: { nativeEvent: { id: number } }) => commands.endThrough(event.nativeEvent.id), + [commands], + ); + // StrictMode replays this effect, so the tracker keeps working after endAll. + useEffect( + () => () => { + recent.current = null; + commands.endAll(); + }, + [commands], + ); + // FlatList's defaults: animated, the item at the start edge; native clamps the index. useImperativeHandle( ref, () => ({ - scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) => { - const native = nativeRef.current; - if (native === null) return; - if (index < 0 || index >= count.current) { - warn(`scrollToIndex: index ${index} is out of range for ${count.current} items`); - } - Commands.scrollToIndex( - native, - ++commandId.current, + scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) => + sendCommand( + (native, id) => + Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset), index, - animated, - viewPosition, - viewOffset, - ); - }, - scrollToOffset: ({ offset, animated = true }) => { - const native = nativeRef.current; - if (native !== null) Commands.scrollToOffset(native, ++commandId.current, offset, animated); - }, - scrollToEnd: (params) => { - const native = nativeRef.current; - if (native !== null) - Commands.scrollToEnd(native, ++commandId.current, params?.animated ?? true); - }, + ), + scrollToOffset: ({ offset, animated = true }) => + sendCommand((native, id) => Commands.scrollToOffset(native, id, offset, animated)), + scrollToEnd: (params) => + sendCommand((native, id) => Commands.scrollToEnd(native, id, params?.animated ?? true)), getScrollableNode: () => nativeRef.current, getAnimatableRef: () => nativeRef.current, }), - [warn], + [sendCommand], ); const press = (handler: ((info: PressInfo) => void) | undefined) => @@ -520,6 +549,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { {...hostProps(given)} {...nativeProps(props, warn)} ref={nativeRef} + onScrollCommandEnd={endCommand} storeId={storeId} itemAnimations={itemAnimations} onCellPress={press(onPress)} diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 0db4653..0c6d6a3 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -836,8 +836,158 @@ describe('Flume edges', () => { }); describe('Flume ref', () => { + const frames: Array<() => void> = []; + const nextFrame = () => { + for (const run of frames.splice(0)) run(); + }; + const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + const track = (done: Promise | undefined) => { + const state = { resolved: false }; + void done?.then(() => { + state.resolved = true; + }); + return state; + }; + const endCommand = (tree: ReactTestRenderer, id: number) => + act(() => { + tree.root + .find((node) => String(node.type) === 'FlumeView') + .props.onScrollCommandEnd({ nativeEvent: { id } }); + }); + beforeEach(() => { vi.resetModules(); + frames.length = 0; + vi.stubGlobal('requestAnimationFrame', (run: () => void) => frames.push(run)); + }); + + it('scrollToIndex resolves when native reports its end', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + const state = track(ref.current?.scrollToIndex({ index: 0 })); + await flush(); + expect(state.resolved).toBe(false); + await endCommand(tree, 1); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('resolves at once without a native view', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + await act(async () => { + create(createElement(Flume, { ref, data: [item], renderCell }), { + createNodeMock: () => null, + }); + }); + const state = track(ref.current?.scrollToOffset({ offset: 10 })); + await flush(); + expect(state.resolved).toBe(true); + expect(Commands.scrollToOffset).not.toHaveBeenCalled(); + }); + + it('resolves pending scrolls on unmount', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + const state = track(ref.current?.scrollToEnd()); + await act(async () => tree.unmount()); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('sends a command again under a new id after data of the same frame', async () => { + const host = installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + vi.mocked(Commands.scrollToIndex).mockImplementation((_view, id) => { + host.log.push(`index ${id}`); + }); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToIndex({ index: 1, animated: false }); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + expect(host.log.slice(-3)).toEqual(['index 1', 'data [1]', 'index 2']); + expect(Commands.scrollToIndex).toHaveBeenLastCalledWith(expect.anything(), 2, 1, false, 0, 0); + }); + + it('keeps a scroll sent again pending until its new id ends', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + const state = track(ref.current?.scrollToIndex({ index: 1 })); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + await endCommand(tree, 1); + await flush(); + expect(state.resolved).toBe(false); + await endCommand(tree, 2); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('does not send a scroll again once its frame passed', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToEnd(); + nextFrame(); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + expect(Commands.scrollToEnd).toHaveBeenCalledTimes(1); + }); + + it('does not send a scroll again when native data is unchanged', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToOffset({ offset: 10 }); + await act(async () => tree.update(createElement(Flume, { ref, data: [item], renderCell }))); + expect(Commands.scrollToOffset).toHaveBeenCalledTimes(1); + }); + + it('checks an index against the data of the same frame', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToIndex({ index: 1 }); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + nextFrame(); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('warns about an index past the data once its frame passes', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const ref = createRef(); + await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToIndex({ index: 5 }); + expect(warn).not.toHaveBeenCalled(); + nextFrame(); + expect(warn).toHaveBeenCalledWith( + 'react-native-flume: scrollToIndex: index 5 is out of range for 1 items', + ); + warn.mockRestore(); }); it('sends the commands with FlatList defaults and a growing id', async () => { diff --git a/src/__tests__/commands.test.ts b/src/__tests__/commands.test.ts new file mode 100644 index 0000000..cf90ecd --- /dev/null +++ b/src/__tests__/commands.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest'; +import { createScrollCommands } from '../commands'; + +// Settles a Promise's callbacks queued so far, so a test can read whether it resolved. +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +function track(done: Promise) { + const state = { resolved: false, rejected: false }; + done.then( + () => { + state.resolved = true; + }, + () => { + state.rejected = true; + }, + ); + return state; +} + +describe('createScrollCommands', () => { + it('resolves a command when its end arrives', async () => { + const commands = createScrollCommands(); + const { id, done } = commands.start(); + const state = track(done); + await flush(); + expect(state.resolved).toBe(false); + commands.endThrough(id); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('resolves the older command when a newer one starts', async () => { + const commands = createScrollCommands(); + const first = track(commands.start().done); + const second = track(commands.start().done); + await flush(); + expect(first.resolved).toBe(true); + expect(second.resolved).toBe(false); + }); + + it('keeps the newer command pending when an older end arrives late', async () => { + const commands = createScrollCommands(); + const first = commands.start(); + const second = track(commands.start().done); + commands.endThrough(first.id); + await flush(); + expect(second.resolved).toBe(false); + }); + + it('resolves everything on endAll', async () => { + const commands = createScrollCommands(); + const state = track(commands.start().done); + commands.endAll(); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('never rejects', async () => { + const commands = createScrollCommands(); + const states = [track(commands.start().done), track(commands.start().done)]; + commands.endThrough(99); + commands.endAll(); + await flush(); + expect(states.every((state) => state.resolved && !state.rejected)).toBe(true); + }); + + it('keeps a moved command pending when its old id ends', async () => { + const commands = createScrollCommands(); + const { id, done } = commands.start(); + const state = track(done); + const moved = commands.move(); + commands.endThrough(id); + await flush(); + expect(moved).toBeGreaterThan(id); + expect(state.resolved).toBe(false); + }); + + it('resolves a moved command when its new id ends', async () => { + const commands = createScrollCommands(); + const state = track(commands.start().done); + commands.endThrough(commands.move()); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('gives a fresh id when nothing is pending', () => { + const commands = createScrollCommands(); + const { id } = commands.start(); + commands.endThrough(id); + const moved = commands.move(); + const next = commands.start(); + expect(moved).toBeGreaterThan(id); + expect(next.id).toBeGreaterThan(moved); + }); + + it('keeps working after endAll', async () => { + const commands = createScrollCommands(); + commands.endAll(); + const { id, done } = commands.start(); + const state = track(done); + commands.endThrough(id); + await flush(); + expect(state.resolved).toBe(true); + }); +}); diff --git a/src/commands.ts b/src/commands.ts new file mode 100644 index 0000000..f0cc668 --- /dev/null +++ b/src/commands.ts @@ -0,0 +1,36 @@ +export type ScrollCommands = { + start(): { id: number; done: Promise }; + // A command sent again takes a new id and keeps its Promise; with none pending the id is just fresh. + move(): number; + endThrough(id: number): void; + endAll(): void; +}; + +// Native ends commands in order and a newer one interrupts the one before, so one Promise is pending at most. +export function createScrollCommands(): ScrollCommands { + let last = 0; + let pending: { id: number; resolve: () => void } | null = null; + const endPending = () => { + pending?.resolve(); + pending = null; + }; + return { + start() { + endPending(); + const id = ++last; + const done = new Promise((resolve) => { + pending = { id, resolve }; + }); + return { id, done }; + }, + move() { + last += 1; + if (pending !== null) pending.id = last; + return last; + }, + endThrough(id) { + if (pending !== null && pending.id <= id) endPending(); + }, + endAll: endPending, + }; +} diff --git a/src/types.ts b/src/types.ts index fa56571..ae16a2c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -169,15 +169,16 @@ export type ViewabilityConfig = { }; // scrollToIndex is exact for worklet rows; the last two members serve Animated and Reanimated, which read them by name. +// A scroll resolves once the list rests after it, or when a drag, a newer scroll or an unmount ends it first. export type FlumeRef = { scrollToIndex(params: { index: number; animated?: boolean; viewPosition?: number; viewOffset?: number; - }): void; - scrollToOffset(params: { offset: number; animated?: boolean }): void; - scrollToEnd(params?: { animated?: boolean }): void; + }): Promise; + scrollToOffset(params: { offset: number; animated?: boolean }): Promise; + scrollToEnd(params?: { animated?: boolean }): Promise; getScrollableNode(): unknown; getAnimatableRef(): unknown; }; From d8ff64bb0b555137ca2f6a543e06bbfb06d1612f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 19:50:22 +0100 Subject: [PATCH 07/17] fix(ios): end a scroll that lands while a finger holds the list A scroll command sent while a finger held the list, from a timer or an onScroll handler, landed under the finger and waited for the list to rest. After a release without momentum no layout runs, so nothing ended it, and its Promise stayed pending until the next command (24 s in one run). The end of a drag without momentum now ends it. --- ios/FLMView.mm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 5b48525..143627f 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1396,6 +1396,8 @@ - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL _scrollEvents.didEndDragging(decelerate); if (!decelerate) { [self writeShadowOrigins]; + // A command that landed under the finger ends here, since no layout follows a release without momentum. + [self settleCommand]; } } From 1ea0781e6ea0bd185c121f82d9a90d5e67245a03 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 19:51:01 +0100 Subject: [PATCH 08/17] feat: add the remaining FlatList and LegendList ref methods and props scrollToItem, scrollToTop, scrollIndexIntoView and scrollItemIntoView return a Promise like the other scroll methods, and setNativeProps reaches the list's native view. The into-view methods scroll only when the row is not fully visible, to the edge it is past, as LegendList does. The list also takes the four keyboard event props, progressViewOffset and alignItemsAtEnd. --- .../main/java/me/sectiontn/flume/FlumeView.kt | 20 ++++ .../me/sectiontn/flume/FlumeViewManager.kt | 3 + .../java/me/sectiontn/flume/ScrollCommands.kt | 10 ++ .../me/sectiontn/flume/ScrollCommandsTest.kt | 19 +++ cpp/adapter/ScrollCommands.cpp | 11 ++ cpp/adapter/ScrollCommands.h | 5 + cpp/tests/scroll_commands_test.cpp | 15 +++ ios/FLMView.mm | 35 ++++++ src/Flume.tsx | 60 ++++++++-- src/__tests__/Flume.test.tsx | 111 +++++++++++++++++- src/__tests__/props.test.ts | 16 +++ src/foreign.ts | 6 + src/keyboard.ts | 17 +++ src/props.ts | 13 +- src/specs/FlumeViewNativeComponent.ts | 16 ++- src/types.ts | 31 +++++ 16 files changed, 365 insertions(+), 23 deletions(-) create mode 100644 src/keyboard.ts diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 0a95725..89ec132 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -436,6 +436,26 @@ class FlumeView(context: Context) : FrameLayout(context) { requestJump(JumpTarget.Index(index), animated, viewPosition, viewOffsetDp) } + // A row already fully in view ends the command where the list is. An index past the data lands at the end edge. + fun scrollIndexIntoView(id: Int, index: Int, animated: Boolean, viewOffsetDp: Double) { + commands.begin(id) + val target = JumpTarget.Index(index) + val position = target.position(rows) + val first = layoutManager.findFirstCompletelyVisibleItemPosition() + val last = layoutManager.findLastCompletelyVisibleItemPosition() + val viewPosition = when { + position == null || target.waitsForData(rows) -> 1f + else -> IntoView.target(position, minOf(first, last), maxOf(first, last)) + } + if (viewPosition == null) { + jumps.cancel()?.let { dropJump(it) } + forgetLanding() + landCommand() + return + } + requestJump(target, 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) } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index 211a17f..e3c5317 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -328,6 +328,9 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac override fun scrollToEnd(view: FlumeView, requestId: Int, animated: Boolean) = view.scrollToEnd(requestId, animated) + override fun scrollIndexIntoView(view: FlumeView, requestId: Int, index: Int, animated: Boolean, viewOffset: Double) = + view.scrollIndexIntoView(requestId, index, animated, viewOffset) + override fun setNativeRefreshing(view: FlumeView, refreshing: Boolean) = view.setNativeRefreshing(refreshing) companion object { diff --git a/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt index a627926..2df423b 100644 --- a/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt +++ b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt @@ -36,3 +36,13 @@ class ScrollCommands { landed = false } } + +// The viewPosition that brings a row into view: 0 before the fully visible rows, 1 after them, null when it is one. +object IntoView { + fun target(position: Int, firstFull: Int, lastFull: Int): Float? = when { + firstFull < 0 || lastFull < firstFull -> 0f + position < firstFull -> 0f + position > lastFull -> 1f + else -> null + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt index a41e0c2..9f2ded9 100644 --- a/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt +++ b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt @@ -1,6 +1,7 @@ package me.sectiontn.flume import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Test class ScrollCommandsTest { @@ -80,4 +81,22 @@ class ScrollCommandsTest { commands.begin(4) assertEquals(0, commands.settle(rest)) } + + @Test + fun intoViewEndsAtOnceForARowFullyInView() { + assertNull(IntoView.target(5, 3, 8)) + assertNull(IntoView.target(3, 3, 8)) + assertNull(IntoView.target(8, 3, 8)) + } + + @Test + fun intoViewScrollsWithViewPosition0BeforeTheVisibleRowsAnd1AfterThem() { + assertEquals(0f, IntoView.target(2, 3, 8)) + assertEquals(1f, IntoView.target(9, 3, 8)) + } + + @Test + fun intoViewPutsTheRowAtTheStartWhenNoRowIsFullyInView() { + assertEquals(0f, IntoView.target(4, -1, -1)) + } } diff --git a/cpp/adapter/ScrollCommands.cpp b/cpp/adapter/ScrollCommands.cpp index f298d56..63b766b 100644 --- a/cpp/adapter/ScrollCommands.cpp +++ b/cpp/adapter/ScrollCommands.cpp @@ -26,3 +26,14 @@ void ScrollCommands::reset() { } } // namespace flume + +namespace flume { + +std::optional intoViewPosition(int position, int firstFull, int lastFull) { + if (firstFull < 0 || lastFull < firstFull) return 0.f; + if (position < firstFull) return 0.f; + if (position > lastFull) return 1.f; + return std::nullopt; +} + +} // namespace flume diff --git a/cpp/adapter/ScrollCommands.h b/cpp/adapter/ScrollCommands.h index 3c4b5eb..4419b71 100644 --- a/cpp/adapter/ScrollCommands.h +++ b/cpp/adapter/ScrollCommands.h @@ -1,9 +1,14 @@ #pragma once #include +#include namespace flume { +// The viewPosition that brings a row into view: 0 before the fully visible rows, 1 after them, none when it is one. +// Positions count list rows. With no row fully in view, the row goes to the start. +std::optional intoViewPosition(int position, int firstFull, int lastFull); + // The scroll command in flight: its id is reported once, when it settles at rest or is interrupted. class ScrollCommands { public: diff --git a/cpp/tests/scroll_commands_test.cpp b/cpp/tests/scroll_commands_test.cpp index 8f8f6c3..f2a3b2e 100644 --- a/cpp/tests/scroll_commands_test.cpp +++ b/cpp/tests/scroll_commands_test.cpp @@ -76,3 +76,18 @@ TEST_CASE("ScrollCommands a newer command clears the landed mark") { commands.begin(4); CHECK(commands.settle(kRest) == 0); } + +TEST_CASE("IntoView ends at once for a row fully in view") { + CHECK_FALSE(intoViewPosition(5, 3, 8).has_value()); + CHECK_FALSE(intoViewPosition(3, 3, 8).has_value()); + CHECK_FALSE(intoViewPosition(8, 3, 8).has_value()); +} + +TEST_CASE("IntoView scrolls with viewPosition 0 before the visible rows and 1 after them") { + CHECK(intoViewPosition(2, 3, 8) == 0.f); + CHECK(intoViewPosition(9, 3, 8) == 1.f); +} + +TEST_CASE("IntoView puts the row at the start when no row is fully in view") { + CHECK(intoViewPosition(4, -1, -1) == 0.f); +} diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 143627f..b82e7aa 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1931,6 +1931,41 @@ - (void)scrollToEnd:(NSInteger)requestId animated:(BOOL)animated animated:animated]; } +// A row already fully in view ends the command where the list is. An index past the data lands at the end edge. +- (void)scrollIndexIntoView:(NSInteger)requestId + index:(NSInteger)index + animated:(BOOL)animated + viewOffset:(double)viewOffset +{ + [self beginCommand:requestId]; + if (!_attached) { + [self landCommand]; + return; + } + std::optional viewPosition = 1; + if (_rows.dataCount > 0 && index < _rows.dataCount) { + const FLMViewport viewport = [_layout viewportFor:_collectionView.bounds]; + int firstFull = INT_MAX; + int lastFull = -1; + for (const flume::ItemSpan &span : [_layout spansIn:viewport]) { + if (span.start >= -0.5f && span.end <= viewport.length + 0.5f) { + firstFull = std::min(firstFull, span.index); + lastFull = std::max(lastFull, span.index); + } + } + const int position = _rows.position(*flume::clampIndex(static_cast(index), _rows.dataCount)); + viewPosition = flume::intoViewPosition(position, lastFull < 0 ? -1 : firstFull, lastFull); + } + if (!viewPosition) { + [self dropJump]; + _pendingTarget.reset(); + [self landCommand]; + return; + } + [self scrollToTarget:FLMPendingTarget{FLMPendingTarget::Kind::Index, static_cast(index), *viewPosition, viewOffset} + animated:animated]; +} + - (void)setNativeRefreshing:(BOOL)refreshing { [_refresh setRefreshing:refreshing]; diff --git a/src/Flume.tsx b/src/Flume.tsx index dd6e4db..23fdd5e 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -23,6 +23,7 @@ import { createScrollCommands } from './commands'; import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; import { FlumeSlot } from './FlumeSlot'; import { hostProps } from './foreign'; +import { useKeyboardEvent } from './keyboard'; import { contentPadding, gapsOf, @@ -117,6 +118,10 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { onStartReached, keyboardShouldPersistTaps, } = props; + useKeyboardEvent('keyboardWillShow', props.onKeyboardWillShow); + useKeyboardEvent('keyboardWillHide', props.onKeyboardWillHide); + useKeyboardEvent('keyboardDidShow', props.onKeyboardDidShow); + useKeyboardEvent('keyboardDidHide', props.onKeyboardDidHide); const refresh = refreshOf(props); const { onRefresh } = refresh; const host = getHost(); @@ -468,7 +473,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { // The index is checked once the frame ends, against the data a handler committed with the scroll. const sendCommand = useCallback( - (send: RecentCommand['send'], index?: number): Promise => { + (send: RecentCommand['send'], index?: number, method = 'scrollToIndex'): Promise => { const native = nativeRef.current; if (native === null) return Promise.resolve(); const { id, done } = commands.start(); @@ -479,7 +484,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { if (recent.current !== command) return; recent.current = null; if (index !== undefined && (index < 0 || index >= count.current)) { - warn(`scrollToIndex: index ${index} is out of range for ${count.current} items`); + warn(`${method}: index ${index} is out of range for ${count.current} items`); } }); return done; @@ -500,24 +505,53 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { ); // FlatList's defaults: animated, the item at the start edge; native clamps the index. - useImperativeHandle( - ref, - () => ({ + useImperativeHandle(ref, () => { + const toIndex = ( + index: number, + animated: boolean, + viewPosition: number, + viewOffset: number, + method?: string, + ) => + sendCommand( + (native, id) => + Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset), + index, + method, + ); + const intoView = (index: number, animated: boolean, viewOffset: number, method: string) => + sendCommand( + (native, id) => Commands.scrollIndexIntoView(native, id, index, animated, viewOffset), + index, + method, + ); + // FlatList finds the item by identity in the data it rendered last. + const found = (item: unknown, scroll: (index: number) => Promise) => { + const index = dataRef.current.indexOf(item); + return index < 0 ? Promise.resolve() : scroll(index); + }; + return { scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) => - sendCommand( - (native, id) => - Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset), - index, - ), + toIndex(index, animated, viewPosition, viewOffset), scrollToOffset: ({ offset, animated = true }) => sendCommand((native, id) => Commands.scrollToOffset(native, id, offset, animated)), scrollToEnd: (params) => sendCommand((native, id) => Commands.scrollToEnd(native, id, params?.animated ?? true)), + scrollToItem: ({ item, animated = true, viewPosition = 0, viewOffset = 0 }) => + found(item, (index) => toIndex(index, animated, viewPosition, viewOffset, 'scrollToItem')), + scrollToTop: (params) => + sendCommand((native, id) => + Commands.scrollToOffset(native, id, 0, params?.animated ?? true), + ), + scrollIndexIntoView: ({ index, animated = true, viewOffset = 0 }) => + intoView(index, animated, viewOffset, 'scrollIndexIntoView'), + scrollItemIntoView: ({ item, animated = true, viewOffset = 0 }) => + found(item, (index) => intoView(index, animated, viewOffset, 'scrollItemIntoView')), + setNativeProps: (nativeProps) => nativeRef.current?.setNativeProps(nativeProps), getScrollableNode: () => nativeRef.current, getAnimatableRef: () => nativeRef.current, - }), - [sendCommand], - ); + }; + }, [sendCommand]); const press = (handler: ((info: PressInfo) => void) | undefined) => handler === undefined diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 0c6d6a3..ef89c2b 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -29,12 +29,17 @@ vi.mock('../specs/FlumeViewNativeComponent', () => ({ scrollToIndex: vi.fn(), scrollToOffset: vi.fn(), scrollToEnd: vi.fn(), + scrollIndexIntoView: vi.fn(), setNativeRefreshing: vi.fn(), }, })); vi.mock('../specs/FlumeSlotViewNativeComponent', () => ({ default: 'FlumeSlotView' })); vi.mock('react-native', () => ({ - Keyboard: { isVisible: vi.fn(() => true), dismiss: vi.fn() }, + Keyboard: { + isVisible: vi.fn(() => true), + dismiss: vi.fn(), + addListener: vi.fn(() => ({ remove: vi.fn() })), + }, View: 'View', })); @@ -990,6 +995,64 @@ describe('Flume ref', () => { warn.mockRestore(); }); + it("scrollToItem scrolls to the item's index", async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const second = { id: 'b' }; + await mount(createElement(Flume, { ref, data: [item, second], renderCell })); + ref.current?.scrollToItem({ item: second, viewPosition: 0.5 }); + expect(Commands.scrollToIndex).toHaveBeenCalledWith(expect.anything(), 1, 1, true, 0.5, 0); + }); + + it('scrollToItem resolves at once for an item not in data', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + await mount(createElement(Flume, { ref, data: [item], renderCell })); + const state = track(ref.current?.scrollToItem({ item: { id: 'a' } })); + await flush(); + expect(state.resolved).toBe(true); + expect(Commands.scrollToIndex).not.toHaveBeenCalled(); + }); + + it('scrollToTop scrolls to offset 0', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToTop({ animated: false }); + expect(Commands.scrollToOffset).toHaveBeenCalledWith(expect.anything(), 1, 0, false); + }); + + it("scrollItemIntoView sends the item's index", async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const second = { id: 'b' }; + await mount(createElement(Flume, { ref, data: [item, second], renderCell })); + ref.current?.scrollItemIntoView({ item: second, viewOffset: 8 }); + expect(Commands.scrollIndexIntoView).toHaveBeenCalledWith(expect.anything(), 1, 1, true, 8); + }); + + it('setNativeProps forwards to the native view', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const ref = createRef(); + const setNativeProps = vi.fn(); + await act(async () => { + create(createElement(Flume, { ref, data: [item], renderCell }), { + createNodeMock: () => ({ setNativeProps }), + }); + }); + ref.current?.setNativeProps({ scrollEnabled: false }); + expect(setNativeProps).toHaveBeenCalledWith({ scrollEnabled: false }); + }); + it('sends the commands with FlatList defaults and a growing id', async () => { installHost(); const { Flume } = await import('../Flume'); @@ -1005,6 +1068,52 @@ describe('Flume ref', () => { }); }); +describe('Flume keyboard events', () => { + beforeEach(() => { + vi.resetModules(); + }); + + it.each([ + ['onKeyboardWillShow', 'keyboardWillShow'], + ['onKeyboardWillHide', 'keyboardWillHide'], + ['onKeyboardDidShow', 'keyboardDidShow'], + ['onKeyboardDidHide', 'keyboardDidHide'], + ] as const)('calls %s from the Keyboard event', async (prop, name) => { + installHost(); + const { Flume } = await import('../Flume'); + const { Keyboard } = await import('react-native'); + const handler = vi.fn(); + await mount(createElement(Flume, { data: [item], renderCell, [prop]: handler })); + const calls = vi.mocked(Keyboard.addListener).mock.calls; + expect(calls.map((call) => call[0])).toEqual([name]); + const event = { endCoordinates: { screenY: 300, height: 320 } }; + (calls[0] as unknown as [string, (event: unknown) => void])[1](event); + expect(handler).toHaveBeenCalledWith(event); + }); + + it('subscribes to no keyboard event without a handler', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Keyboard } = await import('react-native'); + await mount(createElement(Flume, { data: [item], renderCell })); + expect(Keyboard.addListener).not.toHaveBeenCalled(); + }); + + it('removes the keyboard subscription on unmount', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Keyboard } = await import('react-native'); + const tree = await mount( + createElement(Flume, { data: [item], renderCell, onKeyboardDidShow: () => {} }), + ); + const subscription = vi.mocked(Keyboard.addListener).mock.results[0]?.value as { + remove: () => void; + }; + await act(async () => tree.unmount()); + expect(subscription.remove).toHaveBeenCalled(); + }); +}); + describe('Flume stats', () => { beforeEach(() => { vi.resetModules(); diff --git a/src/__tests__/props.test.ts b/src/__tests__/props.test.ts index 66c401b..b355f3a 100644 --- a/src/__tests__/props.test.ts +++ b/src/__tests__/props.test.ts @@ -536,3 +536,19 @@ describe('flexGrow and justifyContent', () => { expect(warn).toHaveBeenCalledWith(expect.stringContaining('justifyContent')); }); }); + +describe('nativeProps wrapper props', () => { + it('passes progressViewOffset to the refresh control', () => { + const props = nativeProps({ data: [], onRefresh: () => {}, progressViewOffset: 30 }, vi.fn()); + expect(props.refreshProgressViewOffset).toBe(30); + }); + + it('alignItemsAtEnd places short content at the end', () => { + const warn = vi.fn(); + expect(nativeProps({ data: [], alignItemsAtEnd: true }, warn)).toMatchObject({ + contentJustify: 'end', + growFooter: false, + }); + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/src/foreign.ts b/src/foreign.ts index 047a6c2..a82ab50 100644 --- a/src/foreign.ts +++ b/src/foreign.ts @@ -166,6 +166,7 @@ export const OWN_KEYS = [ 'refreshing', 'onRefresh', 'refreshControl', + 'progressViewOffset', 'scrollEnabled', 'nestedScrollEnabled', 'overScrollMode', @@ -179,6 +180,11 @@ export const OWN_KEYS = [ 'alwaysBounceVertical', 'keyboardDismissMode', 'keyboardShouldPersistTaps', + 'onKeyboardWillShow', + 'onKeyboardWillHide', + 'onKeyboardDidShow', + 'onKeyboardDidHide', + 'alignItemsAtEnd', 'maintainVisibleContentPosition', 'onLayout', 'testID', diff --git a/src/keyboard.ts b/src/keyboard.ts new file mode 100644 index 0000000..76cc7cc --- /dev/null +++ b/src/keyboard.ts @@ -0,0 +1,17 @@ +import { useEffect, useRef } from 'react'; +import { Keyboard, type KeyboardEvent, type KeyboardEventName } from 'react-native'; + +// Subscribes only while a handler is given, and calls the latest one without subscribing again. +export function useKeyboardEvent( + name: KeyboardEventName, + handler: ((event: KeyboardEvent) => void) | null | undefined, +): void { + const latest = useRef(handler); + latest.current = handler; + const given = handler != null; + useEffect(() => { + if (!given) return undefined; + const subscription = Keyboard.addListener(name, (event) => latest.current?.(event)); + return () => subscription.remove(); + }, [name, given]); +} diff --git a/src/props.ts b/src/props.ts index 113a028..93499a3 100644 --- a/src/props.ts +++ b/src/props.ts @@ -324,7 +324,7 @@ export function refreshOf(props: FlumeProps): Refresh { refreshing: props.refreshing === true, colors: control?.colors, tintColor: control?.tintColor, - progressViewOffset: control?.progressViewOffset ?? 0, + progressViewOffset: props.progressViewOffset ?? control?.progressViewOffset ?? 0, enabled: true, }; } @@ -393,18 +393,15 @@ function contentGrowth( const content: Record = {}; flatten(props.contentContainerStyle, content); const grows = typeof content.flexGrow === 'number' && content.flexGrow > 0; - if (!grows) return { contentJustify: 'start', growFooter: false }; + // LegendList's alignItemsAtEnd places short content without growing it, so a footer keeps its length. + if (!grows) return { contentJustify: props.alignItemsAtEnd ? 'end' : 'start', growFooter: false }; const footer: Record = {}; flatten(props.ListFooterComponentStyle, footer); // Yoga takes an explicit flexGrow, 0 included, before the flex shorthand. const grow = typeof footer.flexGrow === 'number' ? footer.flexGrow : footer.flex; + const justify = content.justifyContent ?? (props.alignItemsAtEnd ? 'flex-end' : undefined); return { - contentJustify: - content.justifyContent === 'center' - ? 'center' - : content.justifyContent === 'flex-end' - ? 'end' - : 'start', + contentJustify: justify === 'center' ? 'center' : justify === 'flex-end' ? 'end' : 'start', growFooter: props.ListFooterComponent != null && typeof grow === 'number' && grow > 0, }; } diff --git a/src/specs/FlumeViewNativeComponent.ts b/src/specs/FlumeViewNativeComponent.ts index 0f45794..5676e9e 100644 --- a/src/specs/FlumeViewNativeComponent.ts +++ b/src/specs/FlumeViewNativeComponent.ts @@ -180,12 +180,26 @@ interface NativeCommands { requestId: CodegenTypes.Int32, animated: boolean, ) => void; + // Scrolls only when the row is not fully in view, to the edge it is past. + scrollIndexIntoView: ( + viewRef: React.ElementRef, + requestId: CodegenTypes.Int32, + index: CodegenTypes.Int32, + animated: boolean, + viewOffset: CodegenTypes.Double, + ) => 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; } export const Commands: NativeCommands = codegenNativeCommands({ - supportedCommands: ['scrollToIndex', 'scrollToOffset', 'scrollToEnd', 'setNativeRefreshing'], + supportedCommands: [ + 'scrollToIndex', + 'scrollToOffset', + 'scrollToEnd', + 'scrollIndexIntoView', + 'setNativeRefreshing', + ], }); export default codegenNativeComponent('FlumeView', { diff --git a/src/types.ts b/src/types.ts index ae16a2c..2aed4de 100644 --- a/src/types.ts +++ b/src/types.ts @@ -2,6 +2,7 @@ import type { ComponentType, ReactElement, ReactNode } from 'react'; import type { ColorValue, Insets, + KeyboardEvent, LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent, @@ -179,6 +180,27 @@ export type FlumeRef = { }): Promise; scrollToOffset(params: { offset: number; animated?: boolean }): Promise; scrollToEnd(params?: { animated?: boolean }): Promise; + // The item is found by identity in the current data. One that is not there resolves at once. + scrollToItem(params: { + item: unknown; + animated?: boolean; + viewOffset?: number; + viewPosition?: number; + }): Promise; + scrollToTop(params?: { animated?: boolean }): Promise; + // LegendList's: scrolls only when the row is not fully in view, to the edge it is past. + scrollIndexIntoView(params: { + index: number; + animated?: boolean; + viewOffset?: number; + }): Promise; + scrollItemIntoView(params: { + item: unknown; + animated?: boolean; + viewOffset?: number; + }): Promise; + // Reaches the list's own native props, such as scrollEnabled. + setNativeProps(props: object): void; getScrollableNode(): unknown; getAnimatableRef(): unknown; }; @@ -322,6 +344,8 @@ export type FlumeOwnProps = { | ReactElement | { tintColor?: ColorValue; colors?: ReadonlyArray; progressViewOffset?: number } | null; + // FlatList's: the spinner's offset for the refresh control onRefresh makes. + progressViewOffset?: number; scrollEnabled?: boolean; nestedScrollEnabled?: boolean; overScrollMode?: 'auto' | 'always' | 'never'; @@ -337,6 +361,13 @@ export type FlumeOwnProps = { // interactive is iOS only. keyboardDismissMode?: 'none' | 'on-drag' | 'interactive'; keyboardShouldPersistTaps?: 'always' | 'never' | 'handled'; + // As on ScrollView, from React Native's Keyboard events while a handler is given. + onKeyboardWillShow?: ((event: KeyboardEvent) => void) | null; + onKeyboardWillHide?: ((event: KeyboardEvent) => void) | null; + onKeyboardDidShow?: ((event: KeyboardEvent) => void) | null; + onKeyboardDidHide?: ((event: KeyboardEvent) => void) | null; + // LegendList's: content shorter than the list sits at its end, as justifyContent flex-end places it. + alignItemsAtEnd?: boolean; // false turns anchoring off. FlatList and LegendList objects map onto the same switch and top threshold. maintainVisibleContentPosition?: | boolean From 3ba4dfbbf4ac229f40e10622f7139b452e0dddcd Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 20:18:35 +0100 Subject: [PATCH 09/17] feat: add scrollTo, flashScrollIndicators and the scroll responder Reanimated's scrollTo and code written against a ScrollView ref now reach the list. The native scrollTo and flashScrollIndicators commands take ScrollView's names and arguments, and scrollTo ends the scroll in flight and moves along the list's axis from the content start. getScrollResponder returns a ScrollView-shaped object, which scrollViewRef and refScrollView also receive, and getNativeScrollRef returns the host view. --- .../me/sectiontn/flume/FlumeRecyclerView.kt | 5 ++ .../main/java/me/sectiontn/flume/FlumeView.kt | 8 ++++ .../me/sectiontn/flume/FlumeViewManager.kt | 4 ++ example/src/screens/ScrollScreen.tsx | 45 +++++++++++++++--- ios/FLMView.mm | 12 +++++ src/Flume.tsx | 32 +++++++++++-- src/__tests__/Flume.test.tsx | 47 +++++++++++++++++++ src/foreign.ts | 2 + src/index.ts | 1 + src/specs/FlumeViewNativeComponent.ts | 10 ++++ src/types.ts | 17 ++++++- 11 files changed, 173 insertions(+), 10 deletions(-) diff --git a/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt b/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt index 1342b4f..241e6d7 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt @@ -125,6 +125,11 @@ class FlumeRecyclerView(context: Context) : RecyclerView(context) { invalidate() } + // ScrollView's flashScrollIndicators: the scroll bars show, then fade as after a scroll. + fun flashScrollIndicators() { + awakenScrollBars() + } + // Under the decorations, so a separator line draws over it. override fun onDraw(c: Canvas) { if (Color.alpha(contentBackground) != 0) drawContentBackground(c) diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 89ec132..c811bcc 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -760,6 +760,14 @@ class FlumeView(context: Context) : FrameLayout(context) { requestJump(JumpTarget.End, animated, 1f, 0.0) } + // ScrollView's scrollTo carries no command id: it ends the command in flight, then moves along the list's axis. + fun scrollToPoint(xDp: Double, yDp: Double, animated: Boolean) { + endScrollCommand() + scrollToOffset(0, if (geometry.horizontal) xDp else yDp, animated) + } + + fun flashScrollIndicators() = recycler.flashScrollIndicators() + fun setListOverScrollMode(value: String?) { recycler.overScrollMode = OverScroll.mode(value) } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index e3c5317..3eb6782 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -331,6 +331,10 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac override fun scrollIndexIntoView(view: FlumeView, requestId: Int, index: Int, animated: Boolean, viewOffset: Double) = view.scrollIndexIntoView(requestId, index, animated, viewOffset) + override fun scrollTo(view: FlumeView, x: Double, y: Double, animated: Boolean) = view.scrollToPoint(x, y, animated) + + override fun flashScrollIndicators(view: FlumeView) = view.flashScrollIndicators() + override fun setNativeRefreshing(view: FlumeView, refreshing: Boolean) = view.setNativeRefreshing(refreshing) companion object { diff --git a/example/src/screens/ScrollScreen.tsx b/example/src/screens/ScrollScreen.tsx index f98e2f4..931a0f7 100644 --- a/example/src/screens/ScrollScreen.tsx +++ b/example/src/screens/ScrollScreen.tsx @@ -2,11 +2,13 @@ import { type FunctionComponent, useCallback, useMemo, useState } from 'react'; import { Button, Platform, Text, TextInput, ToastAndroid, View } from 'react-native'; import { type CellNode, cell, Flume, type FlumeProps } from 'react-native-flume'; import Animated, { + scrollTo, + useAnimatedRef, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, } from 'react-native-reanimated'; -import { scheduleOnRN } from 'react-native-worklets'; +import { scheduleOnRN, scheduleOnUI } from 'react-native-worklets'; type Row = { id: string; title: string; body: string }; @@ -50,6 +52,15 @@ const renderRow = (item: Row): CellNode => { ]); }; +// The same row as a column, for the horizontal list. +const renderColumn = (item: Row): CellNode => { + 'worklet'; + return cell.view({ width: 160, padding: 12, gap: 4 }, [ + cell.text(item.title, { fontSize: 16, fontWeight: '600', color: '#111111' }), + cell.text(item.body, { fontSize: 13, color: '#555555' }), + ]); +}; + const toast = (message: string) => { if (Platform.OS === 'android') ToastAndroid.show(message, ToastAndroid.SHORT); }; @@ -61,7 +72,7 @@ const INSETS = { top: 40, bottom: 120 }; export default function ScrollScreen() { const rows = useMemo(() => makeRows(), []); - const [status, setStatus] = useState({ offset: 0, first: -1 }); + const [status, setStatus] = useState({ offset: 0, x: 0, first: -1 }); const [taps, setTaps] = useState(0); const [dismiss, setDismiss] = useState(0); const [insets, setInsets] = useState(false); @@ -79,16 +90,28 @@ export default function ScrollScreen() { }, []); const offset = useSharedValue(0); const reportOffset = useCallback( - (value: number) => setStatus((s) => ({ ...s, offset: value })), + (y: number, x: number) => setStatus((s) => ({ ...s, offset: y, x })), [], ); const onScroll = useAnimatedScrollHandler((e) => { offset.value = e.contentOffset.y; - scheduleOnRN(reportOffset, Math.round(e.contentOffset.y)); + scheduleOnRN(reportOffset, Math.round(e.contentOffset.y), Math.round(e.contentOffset.x)); }); const headerStyle = useAnimatedStyle(() => ({ transform: [{ translateY: -Math.min(Math.max(offset.value, 0), HEADER_HEIGHT) }], })); + const [horizontal, setHorizontal] = useState(false); + const [inverted, setInverted] = useState(false); + // Reanimated's scrollTo runs on the UI runtime and reaches the list as ScrollView's command. + const listRef = useAnimatedRef(); + const scrollTo400 = () => { + const x = horizontal ? 400 : 0; + const y = horizontal ? 0 : 400; + scheduleOnUI(() => { + 'worklet'; + scrollTo(listRef, x, y, true); + }); + }; return ( setFast((v) => !v)} />