diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index ac7df1e..710bc14 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,34 +396,49 @@ 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 } - jumps.request(jump, waiting, SystemClock.uptimeMillis()) + jumps.request(jump, waiting, SystemClock.uptimeMillis(), target.waitsForData(rows)) removeCallbacks(jumpDue) 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) + val waitsForData = jump.target.waitsForData(rows) + jumps.retarget(jump, slotsLeft, waitsForData) + if (slotsLeft.isEmpty() && !waitsForData) 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 +633,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 +644,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 +805,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..fa29dba 100644 --- a/android/src/main/java/me/sectiontn/flume/JumpGate.kt +++ b/android/src/main/java/me/sectiontn/flume/JumpGate.kt @@ -5,19 +5,31 @@ class JumpGate(private val waitMs: Long = ScrollTargets.JUMP_WAIT_MS) { var pending: J? = null private set private val waiting = HashSet() + private var waitsForData = false private var deadlineMs = 0L - // Returns the jump this one replaced, whose slots the caller releases. - fun request(jump: J, slots: Set, nowMs: Long): J? { + // Returns the jump this one replaced, whose slots the caller releases. A jump that waits for data runs on no render. + fun request(jump: J, slots: Set, nowMs: Long, waitsForData: Boolean = false): J? { val replaced = take() pending = jump waiting.addAll(slots) + this.waitsForData = waitsForData deadlineMs = nowMs + waitMs 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, waitsForData: Boolean = false): J? { + val replaced = pending ?: return null + pending = jump + waiting.clear() + waiting.addAll(slots) + this.waitsForData = waitsForData + return replaced + } + fun rendered(slot: Int): J? { - if (pending == null || !waiting.remove(slot) || waiting.isNotEmpty()) return null + if (pending == null || !waiting.remove(slot) || waiting.isNotEmpty() || waitsForData) return null return take() } @@ -29,6 +41,7 @@ class JumpGate(private val waitMs: Long = ScrollTargets.JUMP_WAIT_MS) { val jump = pending pending = null waiting.clear() + waitsForData = false return jump } } 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..840dbae 100644 --- a/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt +++ b/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt @@ -48,4 +48,55 @@ 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)) + } + + @Test + fun aJumpPastTheDataDoesNotRunWhenItsSlotsRender() { + val gate = JumpGate(waitMs = 1000) + gate.request("a", setOf(1), nowMs = 0, waitsForData = true) + assertNull(gate.rendered(1)) + gate.retarget("b", setOf(2), waitsForData = true) + assertNull(gate.rendered(2)) + assertEquals("b", gate.due(nowMs = 1000)) + } + + @Test + fun aJumpRetargetedOntoDataThatArrivedRunsWhenItsSlotsRender() { + val gate = JumpGate() + gate.request("a", setOf(1), nowMs = 0, waitsForData = true) + gate.retarget("b", setOf(2)) + assertEquals("b", gate.rendered(2)) + } } 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..6bb989d 100644 --- a/cpp/adapter/JumpGate.h +++ b/cpp/adapter/JumpGate.h @@ -15,17 +15,27 @@ class JumpGate { public: explicit JumpGate(int64_t waitMs = kJumpWaitMs) : waitMs_(waitMs) {} - // Returns the jump this one replaced, whose slots the caller releases. - std::optional request(Jump jump, std::unordered_set slots, int64_t nowMs) { + // Returns the jump this one replaced, whose slots the caller releases. A jump that waits for data runs on no render. + std::optional request(Jump jump, std::unordered_set slots, int64_t nowMs, bool waitsForData = false) { std::optional replaced = take(); pending_ = std::move(jump); waiting_ = std::move(slots); + waitsForData_ = waitsForData; deadlineMs_ = nowMs + waitMs_; 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, bool waitsForData = false) { + if (!pending_) return std::nullopt; + std::optional replaced = std::exchange(pending_, std::move(jump)); + waiting_ = std::move(slots); + waitsForData_ = waitsForData; + return replaced; + } + std::optional rendered(int slot) { - if (!pending_ || waiting_.erase(slot) == 0 || !waiting_.empty()) return std::nullopt; + if (!pending_ || waiting_.erase(slot) == 0 || !waiting_.empty() || waitsForData_) return std::nullopt; return take(); } @@ -40,12 +50,14 @@ class JumpGate { std::optional jump = std::move(pending_); pending_.reset(); waiting_.clear(); + waitsForData_ = false; return jump; } int64_t waitMs_; std::optional pending_; std::unordered_set waiting_; + bool waitsForData_ = false; int64_t deadlineMs_ = 0; }; diff --git a/cpp/tests/jump_gate_test.cpp b/cpp/tests/jump_gate_test.cpp index 13d528e..487b127 100644 --- a/cpp/tests/jump_gate_test.cpp +++ b/cpp/tests/jump_gate_test.cpp @@ -44,3 +44,48 @@ 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"); +} + +TEST_CASE("a jump past the data does not run when its slots render") { + JumpGate gate(1000); + gate.request("a", {1}, 0, true); + CHECK_FALSE(gate.rendered(1)); + gate.retarget("b", {2}, true); + CHECK_FALSE(gate.rendered(2)); + CHECK(gate.due(1000) == "b"); +} + +TEST_CASE("a jump retargeted onto data that arrived runs when its slots render") { + JumpGate gate; + gate.request("a", {1}, 0, true); + gate.retarget("b", {2}); + CHECK(gate.rendered(2) == "b"); +} diff --git a/ios/FLMView.mm b/ios/FLMView.mm index a564f08..11b2082 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,13 +1560,13 @@ - (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; } - _jumps.request(jump, waiting, static_cast(FLMNowMs())); + _jumps.request(jump, waiting, static_cast(FLMNowMs()), [self waitsForData:target]); __weak FLMView *weakSelf = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (flume::kJumpWaitMs + 1) * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ [weakSelf jumpDue]; @@ -1676,12 +1678,58 @@ - (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 waitsForData = [self waitsForData:jump.target]; + const BOOL ready = waiting.empty() && !waitsForData; + _jumps.retarget(jump, std::move(waiting), waitsForData); + [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 +1813,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]; }