From b135650993c4f09a0ab41a4c25a48e51978b1a88 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sun, 29 Nov 2026 00:29:06 +0100 Subject: [PATCH 1/3] feat(android): feed the offset model the rows RecyclerView lays out --- .../java/me/sectiontn/flume/FlumeAdapter.kt | 11 +- .../java/me/sectiontn/flume/FlumeCellView.kt | 3 + .../me/sectiontn/flume/FlumeLayoutManagers.kt | 16 +++ .../java/me/sectiontn/flume/FlumeSlots.kt | 19 +--- .../main/java/me/sectiontn/flume/FlumeView.kt | 104 ++++++++++++++++-- .../me/sectiontn/flume/FlumeViewManager.kt | 1 + .../main/java/me/sectiontn/flume/ModelFeed.kt | 27 +++++ .../java/me/sectiontn/flume/SizeEstimator.kt | 24 ---- .../java/me/sectiontn/flume/LengthFeedTest.kt | 42 +++++++ .../me/sectiontn/flume/SizeEstimatorTest.kt | 28 ----- 10 files changed, 197 insertions(+), 78 deletions(-) create mode 100644 android/src/main/java/me/sectiontn/flume/ModelFeed.kt delete mode 100644 android/src/main/java/me/sectiontn/flume/SizeEstimator.kt create mode 100644 android/src/test/java/me/sectiontn/flume/LengthFeedTest.kt delete mode 100644 android/src/test/java/me/sectiontn/flume/SizeEstimatorTest.kt diff --git a/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt b/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt index b334148..692e658 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt @@ -12,6 +12,7 @@ class FlumeAdapter( private val measurer: FlumeTextMeasurer, private val recycler: RecyclerView, private val slots: FlumeSlots, + private val model: OffsetModel, ) : RecyclerView.Adapter(), FlumeStoreListener, ListNotifier { class Holder(val view: View) : RecyclerView.ViewHolder(view) { val cell: FlumeCellView? get() = view as? FlumeCellView @@ -62,6 +63,7 @@ class FlumeAdapter( private fun rebindAll() { onRebindAll?.invoke() + model.invalidateLengths() measurer.invalidate() if (storeId != 0) FlumeJni.invalidateMeasures(storeId) // React grid cells take their width from JS, which learns it from the slot snapshot. @@ -79,6 +81,8 @@ class FlumeAdapter( // The holders and their trees survive a detach; a re-attach reloads the rows from the engine's current order. fun attach(storeId: Int) { if (this.storeId != 0 && this.storeId != storeId) detach() + val previousStore = this.storeId + val previousCount = rows.dataCount val reload = attached.onAttach(storeId) val attachedCount = FlumeJni.attach(storeId, this, measurer, density) sendRowShape() @@ -87,6 +91,7 @@ class FlumeAdapter( stickyIndices = sticky if (reload || attachedCount != rows.dataCount) { setCount(attachedCount) + if (ModelOps.resetsOnAttach(previousStore, storeId, previousCount, attachedCount)) model.reset(storeId, rows) else model.invalidateLengths() notifyDataSetChanged() onDataChanged?.invoke(true) } else if (stickyChanged) { @@ -116,10 +121,11 @@ class FlumeAdapter( return } // The empty row comes and goes with the data, which the store's operations do not know about. - val reload = reset || rows.hasEmptyRow != rows.copy(dataCount = count).hasEmptyRow + val reload = ModelOps.reloads(reset, rows, rows.copy(dataCount = count)) val before = if (reload) null else anchorState() val anchorLost = !reload && AnchorPolicy.losesEveryRow(laidOutDataIndices(), removed) setCount(count) + if (reload) model.reset(storeId, rows) else model.apply(storeId, rows, false, removed, inserted, moved, changed, rows.fullSpanPositions(sticky)) ListOpsApplier.apply(reload, removed, inserted, moved, changed, this) refreshDecorations() reindexSlots() @@ -240,6 +246,7 @@ class FlumeAdapter( val after = before.copy(header = header, footer = footer, emptyComponent = empty) if (after == before) return rows = after + if (storeId != 0) model.reset(storeId, rows) if (before.header != after.header) if (after.header) notifyItemInserted(0) else notifyItemRemoved(0) if (before.hasEmptyRow != after.hasEmptyRow) { if (after.hasEmptyRow) notifyItemInserted(after.headerCount) else notifyItemRemoved(after.headerCount) @@ -299,7 +306,7 @@ class FlumeAdapter( holder.slot?.let { slot -> if (slot.horizontal != geometry.horizontal) orient(slot) val request = slotRequest(position, holder.itemViewType) - slots.bind(slot, request.group, request.kind, request.key, request.index) + slots.bind(slot, request.group, request.kind, request.key, request.index, model.itemLengthPx(position)) return } val cell = holder.cell ?: return diff --git a/android/src/main/java/me/sectiontn/flume/FlumeCellView.kt b/android/src/main/java/me/sectiontn/flume/FlumeCellView.kt index 16adf3f..f101aad 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeCellView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeCellView.kt @@ -66,6 +66,9 @@ class FlumeCellView(context: Context, private val measurer: FlumeTextMeasurer) : private var naturalHeightPx = 0 private var stretchedPx = 0 + // Its own length along the axis, not the grid row's it stretches to, which is what the offset model holds. + fun naturalLengthPx(horizontal: Boolean): Int = if (horizontal) tree.rootWidthPx else naturalHeightPx + // A bind lays the root out at its own height, so the next measure stretches it again. fun apply(batch: FlumeBatch) { tree.apply(batch) diff --git a/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt b/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt index 8fe428f..14fe1b6 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt @@ -23,6 +23,7 @@ class FlumeLinearLayoutManager(context: Context, orientation: Int, reverse: Bool LinearLayoutManager(context, orientation, reverse) { var drawDistancePx = -1 var onLaidOut: (() -> Unit)? = null + var onScrolledBy: (() -> Unit)? = null var justify = ContentJustify.Start override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) { @@ -37,12 +38,20 @@ class FlumeLinearLayoutManager(context: Context, orientation: Int, reverse: Bool super.onLayoutCompleted(state) onLaidOut?.invoke() } + + // Each scroll step lays out the rows it brings in, whose lengths the offset model then takes. + override fun scrollVerticallyBy(dy: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int = + super.scrollVerticallyBy(dy, recycler, state).also { onScrolledBy?.invoke() } + + override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int = + super.scrollHorizontallyBy(dx, recycler, state).also { onScrolledBy?.invoke() } } class FlumeGridLayoutManager(context: Context, spanCount: Int, orientation: Int, reverse: Boolean) : GridLayoutManager(context, spanCount, orientation, reverse) { var drawDistancePx = -1 var onLaidOut: (() -> Unit)? = null + var onScrolledBy: (() -> Unit)? = null var justify = ContentJustify.Start override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) { @@ -64,6 +73,13 @@ class FlumeGridLayoutManager(context: Context, spanCount: Int, orientation: Int, super.onLayoutCompleted(state) onLaidOut?.invoke() } + + // Each scroll step lays out the rows it brings in, whose lengths the offset model then takes. + override fun scrollVerticallyBy(dy: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int = + super.scrollVerticallyBy(dy, recycler, state).also { onScrolledBy?.invoke() } + + override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int = + super.scrollHorizontallyBy(dx, recycler, state).also { onScrolledBy?.invoke() } } // The positions that take every span of a grid row, the sticky headers; rows and columns follow from them in O(log n). diff --git a/android/src/main/java/me/sectiontn/flume/FlumeSlots.kt b/android/src/main/java/me/sectiontn/flume/FlumeSlots.kt index f036419..83df8f7 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeSlots.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeSlots.kt @@ -29,16 +29,14 @@ class SlotParking(context: Context) : ViewGroup(context), ReactPointerEventsView // The host's Fabric children and the holders that show them; JS renders the slots the pool lists. class FlumeSlots(private val host: FlumeView) { - private companion object { + companion object { const val ESTIMATE_FLOOR_DP = 50f } val parking = SlotParking(host.context) val pool = SlotPool() - val estimator = SizeEstimator((ESTIMATE_FLOOR_DP * host.resources.displayMetrics.density).roundToInt()) private val children = FabricChildren { (it as? FlumeSlotView)?.slot ?: 0 } private val holders = HashMap() - private val recorded = HashMap() var cellWidthDp = -1f private var sentCellWidthDp = Float.NaN var widthDp = -1f @@ -62,7 +60,6 @@ class FlumeSlots(private val host: FlumeView) { } view.onMeasured = { measured -> holderShowing(measured)?.let { holder -> - recordLength(holder) holder.refresh() } onRendered?.invoke(measured.slot) @@ -76,21 +73,19 @@ class FlumeSlots(private val host: FlumeView) { val child = children.removeAt(index) (child as? FlumeSlotView)?.let { view -> view.onMeasured = null - recorded.remove(view.slot) holderShowing(view)?.show(null) } (child.parent as? ViewGroup)?.removeView(child) } - fun bind(holder: FlumeSlotHolder, group: SlotGroup, kind: Int, key: String, index: Int) { + fun bind(holder: FlumeSlotHolder, group: SlotGroup, kind: Int, key: String, index: Int, estimatePx: Int) { if (holder.slot != 0 && pool.entry(holder.slot)?.key != key) release(holder) val slot = pool.acquire(holder.owner, group, kind, key, index) holder.slot = slot holder.group = group - holder.estimatePx = estimator.estimatePx(group) + holder.estimatePx = estimatePx holders[slot] = holder holder.show(children.bySlot(slot) as? FlumeSlotView) - recordLength(holder) flush() } @@ -211,14 +206,6 @@ class FlumeSlots(private val host: FlumeView) { } private fun holderShowing(view: FlumeSlotView): FlumeSlotHolder? = holders[view.slot]?.takeIf { it.view === view } - - // Each new length of a shown slot feeds its group's estimate once. - private fun recordLength(holder: FlumeSlotHolder) { - val view = holder.view?.takeIf { it.measured } ?: return - val group = holder.group ?: return - val length = view.lengthPx(holder.horizontal) - if (recorded.put(view.slot, length) != length) estimator.record(group, length) - } } class FlumeSlotsEvent( diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 21672df..9839d73 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -38,7 +38,11 @@ class FlumeView(context: Context) : FrameLayout(context) { private var didLayout = false private var refreshProgressViewOffsetDp = 0.0 val slots = FlumeSlots(this) - private val adapter = FlumeAdapter(context, measurer, recycler, slots) + // Mirrors what RecyclerView lays out, in px, so offsets come from row lengths instead of its average. + private val model: OffsetModel = NativeOffsetModel() + private val adapter = FlumeAdapter(context, measurer, recycler, slots, model) + private var estimatedPx = -1 + private var lengthPairs = IntArray(64) private var layoutManager: LinearLayoutManager = FlumeLinearLayoutManager(context, RecyclerView.VERTICAL, false) // Null until the first build replaces the unhooked layout manager above. private var shape: LayoutShape? = null @@ -108,7 +112,7 @@ class FlumeView(context: Context) : FrameLayout(context) { set(value) { if (value == field) return field = value - if (isAttachedToWindow && value != 0) adapter.attach(value) + if (isAttachedToWindow && value != 0) attachStore() } // Change animations stay off so a rebind never flickers; false removes the animator entirely. @@ -308,8 +312,14 @@ class FlumeView(context: Context) : FrameLayout(context) { // Layout completion drives the pinned header and, later, the scroll targets; a grid also needs the span lookup. private fun hookLayoutManager() { when (val lm = layoutManager) { - is FlumeLinearLayoutManager -> lm.onLaidOut = { onLaidOut() } - is FlumeGridLayoutManager -> lm.onLaidOut = { onLaidOut() } + is FlumeLinearLayoutManager -> { + lm.onLaidOut = { onLaidOut() } + lm.onScrolledBy = { pushLengths() } + } + is FlumeGridLayoutManager -> { + lm.onLaidOut = { onLaidOut() } + lm.onScrolledBy = { pushLengths() } + } } applyFullSpan() } @@ -347,9 +357,11 @@ class FlumeView(context: Context) : FrameLayout(context) { sticky.indices = positions adapter.onStickyChanged(previous, stickySet) sticky.refresh(force = true) + pushModelConfig() } private fun onLaidOut() { + pushLengths() animator.still = false if (reclaimOnLayout) { reclaimOnLayout = false @@ -401,6 +413,73 @@ class FlumeView(context: Context) : FrameLayout(context) { origins.writeSlot(view, pinned.left + pinned.translationX.roundToInt(), pinned.top + pinned.translationY.roundToInt()) } + // The model takes its geometry before the store's rows, so their estimates are in px. + private fun attachStore() { + pushModelConfig() + adapter.attach(storeId) + } + + // Every length RecyclerView lays out with, in px, so the model's rows land where RecyclerView puts them. + private fun pushModelConfig() { + val padding = resolvedPaddingPx() + val h = horizontal + model.configure( + OffsetModelConfig( + horizontal = h, + inverted = inverted, + lanes = if (h) 1 else numColumns, + paddingStartPx = if (h) padding[0] else padding[1], + paddingEndPx = if (h) padding[2] else padding[3], + paddingCrossStartPx = if (h) padding[1] else padding[0], + paddingCrossEndPx = if (h) padding[3] else padding[2], + estimatedPx = estimatedPx, + floorPx = (FlumeSlots.ESTIMATE_FLOOR_DP * density).roundToInt(), + separatorPx = (separatorSizeDp * density).roundToInt().coerceAtLeast(0), + mainGapPx = gapsPx[0], + gridRowGapPx = gapsPx[1], + crossGapPx = gapsPx[2], + laneInsetStartPx = gapsPx[3], + laneInsetEndPx = gapsPx[4], + stackFromEnd = shape?.stackFromEnd == true, + justify = contentJustify, + growFooter = growFooter && !inverted, + ), + rows.fullSpanPositions(adapter.stickyIndices), + ) + } + + // The lengths of the laid-out rows after each layout pass and scroll step. Unchanged ones cost nothing in the model. + private fun pushLengths() { + if (storeId == 0) return + val samples = childSamples() + if (lengthPairs.size < 2 * samples.size) lengthPairs = IntArray(4 * samples.size) + val count = LengthFeed.pairs(samples, lengthPairs) + if (count > 0) model.push(lengthPairs, count) + } + + // Each child's own start and natural length; a React row that has not rendered has no length yet. + private fun childSamples(): List { + val horizontal = geometry.horizontal + val out = ArrayList(recycler.childCount) + for (i in 0 until recycler.childCount) { + val child = recycler.getChildAt(i) ?: continue + val holder = recycler.getChildViewHolder(child) as? FlumeAdapter.Holder ?: continue + val position = holder.absoluteAdapterPosition + val leaving = position == RecyclerView.NO_POSITION || (child.layoutParams as RecyclerView.LayoutParams).isItemRemoved + val start = if (horizontal) child.left else child.top + val cell = holder.cell + val slot = holder.slot + val view = slot?.view + val length = when { + cell != null -> cell.naturalLengthPx(horizontal) + slot != null && slot.ready && view != null && view.measured -> view.lengthPx(horizontal) + else -> -1 + } + out += ChildSample(position, start, maxOf(0, length), length >= 0, leaving) + } + return out + } + // Offset, range and extent along the scroll axis, as RecyclerView estimates them from the laid-out rows. private fun scrollMetrics(): ScrollRange = if (geometry.horizontal) { ScrollRange(recycler.computeHorizontalScrollOffset(), recycler.computeHorizontalScrollRange(), recycler.computeHorizontalScrollExtent()) @@ -581,7 +660,7 @@ class FlumeView(context: Context) : FrameLayout(context) { return 0 } layoutManager.findViewByPosition(position)?.let { return if (geometry.horizontal) it.width else it.height } - return slots.estimator.estimatePx(SlotGroup(viewTypeAt(position))) + return model.itemLengthPx(position) } private fun startScroll(position: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { @@ -674,7 +753,7 @@ class FlumeView(context: Context) : FrameLayout(context) { val holder = (recycler.findViewHolderForAdapterPosition(position) as? FlumeAdapter.Holder)?.slot val view = holder?.view if (holder != null && view != null && holder.ready) return view.lengthPx(geometry.horizontal) - return slots.estimator.estimatePx(SlotGroup(viewType)) + return model.itemLengthPx(position) } val index = rows.dataIndex(position).takeIf { it >= 0 } ?: return 0 val batch = FlumeJni.bind(storeId, measureHolderId, index, geometry.cellWidthDp(adapter.fullSpans.contains(position)), geometry.cellHeightDp()) ?: return 0 @@ -688,6 +767,7 @@ class FlumeView(context: Context) : FrameLayout(context) { if (field == value) return field = value applyDrawDistance() + pushModelConfig() recycler.requestLayout() } @@ -695,6 +775,7 @@ class FlumeView(context: Context) : FrameLayout(context) { set(value) { if (field == value) return field = value + pushModelConfig() updateFooterLength() } @@ -852,6 +933,7 @@ class FlumeView(context: Context) : FrameLayout(context) { } separator?.let { recycler.addItemDecoration(it) } recycler.invalidateItemDecorations() + pushModelConfig() } // Edges are 0 left, 1 top, 2 right, 3 bottom, in dp. @@ -874,6 +956,7 @@ class FlumeView(context: Context) : FrameLayout(context) { recycler.setPadding(resolved[0], resolved[1], resolved[2], resolved[3]) adapter.configure(horizontal, numColumns, inverted, resolved, lanes()) sticky.refresh(force = true) + pushModelConfig() } // Kinds are 0 main, 1 grid row, 2 column, 3 lane inset start and 4 lane inset end, in dp. @@ -887,6 +970,7 @@ class FlumeView(context: Context) : FrameLayout(context) { gaps = if (on) gaps ?: GapDecoration(gapsPx) { rows }.also { recycler.addItemDecoration(it) } else null recycler.invalidateItemDecorations() sticky.refresh(force = true) + pushModelConfig() } private fun lanes() = Lanes(insetStartPx = gapsPx[3], insetEndPx = gapsPx[4], gapPx = gapsPx[2]) @@ -909,6 +993,7 @@ class FlumeView(context: Context) : FrameLayout(context) { kept?.let { layoutManager.scrollToPositionWithOffset(it.firstVisiblePosition, it.firstVisibleOffsetPx) } adapter.configure(horizontal, numColumns, inverted, resolvedPaddingPx(), lanes()) sticky.refresh(force = true) + pushModelConfig() layoutWithProps = true } @@ -984,7 +1069,7 @@ class FlumeView(context: Context) : FrameLayout(context) { override fun onAttachedToWindow() { super.onAttachedToWindow() - if (storeId != 0) adapter.attach(storeId) + if (storeId != 0) attachStore() } private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop @@ -1119,6 +1204,9 @@ class FlumeView(context: Context) : FrameLayout(context) { } fun setEstimatedItemSize(dp: Double) { - slots.estimator.estimatedPx = if (dp < 0) -1 else (dp * density).roundToInt() + estimatedPx = if (dp < 0) -1 else (dp * density).roundToInt() + pushModelConfig() } + + fun dropModel() = model.drop() } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index 3eb6782..6135598 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -39,6 +39,7 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac override fun onDropViewInstance(view: FlumeView) { view.endScrollCommand() + view.dropModel() // A view dropped while detached registered its mount listener after its own detach cleanup. view.dropMountListener() view.setStateWrapper(null) diff --git a/android/src/main/java/me/sectiontn/flume/ModelFeed.kt b/android/src/main/java/me/sectiontn/flume/ModelFeed.kt new file mode 100644 index 0000000..e7995f9 --- /dev/null +++ b/android/src/main/java/me/sectiontn/flume/ModelFeed.kt @@ -0,0 +1,27 @@ +package me.sectiontn.flume + +// A laid-out child as the offset model sees it: its own start and natural length along the axis, never its decorated ones. +data class ChildSample(val position: Int, val startPx: Int, val lengthPx: Int, val measured: Boolean, val leaving: Boolean) + +object LengthFeed { + // Position and length pairs of the children the model can take, written into out. Returns the pair count. + fun pairs(samples: List, out: IntArray): Int { + var count = 0 + for (sample in samples) { + if (!sample.measured || sample.leaving || sample.position < 0 || 2 * count + 1 >= out.size) continue + out[2 * count] = sample.position + out[2 * count + 1] = sample.lengthPx + count++ + } + return count + } +} + +object ModelOps { + // A reset, or the empty row coming or going, reloads rows the store's operations do not describe. + fun reloads(reset: Boolean, before: ListRows, after: ListRows): Boolean = reset || before.hasEmptyRow != after.hasEmptyRow + + // A re-attach of the same store at the same count (a tab switch) keeps the lengths, as iOS learned with bug-131. + fun resetsOnAttach(previousStore: Int, store: Int, previousCount: Int, count: Int): Boolean = + previousStore != store || previousCount != count +} diff --git a/android/src/main/java/me/sectiontn/flume/SizeEstimator.kt b/android/src/main/java/me/sectiontn/flume/SizeEstimator.kt deleted file mode 100644 index 4ed9d53..0000000 --- a/android/src/main/java/me/sectiontn/flume/SizeEstimator.kt +++ /dev/null @@ -1,24 +0,0 @@ -package me.sectiontn.flume - -// The length a React holder takes before its slot measures: estimatedItemSize, else its group's mean above the floor. -class SizeEstimator(private val floorPx: Int) { - private class Mean { - var sum = 0L - var count = 0 - } - - var estimatedPx = -1 - private val means = HashMap() - - fun record(group: SlotGroup, lengthPx: Int) { - val mean = means.getOrPut(group) { Mean() } - mean.sum += lengthPx - mean.count++ - } - - fun estimatePx(group: SlotGroup): Int { - if (estimatedPx >= 0) return estimatedPx - val mean = means[group]?.takeIf { it.count > 0 } ?: return floorPx - return maxOf(floorPx, (mean.sum / mean.count).toInt()) - } -} diff --git a/android/src/test/java/me/sectiontn/flume/LengthFeedTest.kt b/android/src/test/java/me/sectiontn/flume/LengthFeedTest.kt new file mode 100644 index 0000000..17aef30 --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/LengthFeedTest.kt @@ -0,0 +1,42 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class LengthFeedTest { + private fun sample(position: Int, length: Int, measured: Boolean = true, leaving: Boolean = false) = + ChildSample(position, startPx = 0, lengthPx = length, measured = measured, leaving = leaving) + + @Test + fun pushesMeasuredChildren() { + val out = IntArray(8) + val count = LengthFeed.pairs(listOf(sample(4, 80), sample(5, 120), sample(6, 80)), out) + assertEquals(3, count) + assertArrayEquals(intArrayOf(4, 80, 5, 120, 6, 80), out.copyOf(6)) + } + + @Test + fun skipsAnUnrenderedReactRowAndALeavingRow() { + val out = IntArray(8) + val count = LengthFeed.pairs(listOf(sample(4, 80), sample(5, 0, measured = false), sample(6, 80, leaving = true)), out) + assertEquals(1, count) + assertArrayEquals(intArrayOf(4, 80), out.copyOf(2)) + } + + @Test + fun aReloadResetsTheModelWithTheNewRows() { + assertTrue(ModelOps.reloads(true, ListRows(dataCount = 3), ListRows(dataCount = 3))) + assertTrue(ModelOps.reloads(false, ListRows(dataCount = 1, emptyComponent = true), ListRows(dataCount = 0, emptyComponent = true))) + assertFalse(ModelOps.reloads(false, ListRows(dataCount = 3), ListRows(dataCount = 4))) + } + + @Test + fun aReAttachOfTheSameStoreKeepsTheLengths() { + assertFalse(ModelOps.resetsOnAttach(previousStore = 7, store = 7, previousCount = 40, count = 40)) + assertTrue(ModelOps.resetsOnAttach(previousStore = 7, store = 8, previousCount = 40, count = 40)) + assertTrue(ModelOps.resetsOnAttach(previousStore = 7, store = 7, previousCount = 40, count = 41)) + } +} diff --git a/android/src/test/java/me/sectiontn/flume/SizeEstimatorTest.kt b/android/src/test/java/me/sectiontn/flume/SizeEstimatorTest.kt deleted file mode 100644 index 6428c70..0000000 --- a/android/src/test/java/me/sectiontn/flume/SizeEstimatorTest.kt +++ /dev/null @@ -1,28 +0,0 @@ -package me.sectiontn.flume - -import org.junit.Assert.assertEquals -import org.junit.Test - -class SizeEstimatorTest { - private val rows = SlotGroup(1) - private val cards = SlotGroup(3) - - @Test - fun estimatedItemSizeWins() { - val estimator = SizeEstimator(floorPx = 100) - estimator.estimatedPx = 60 - estimator.record(rows, 300) - assertEquals(60, estimator.estimatePx(rows)) - } - - @Test - fun aGroupTakesTheMeanOfItsMeasuredCellsAboveTheFloor() { - val estimator = SizeEstimator(floorPx = 100) - assertEquals(100, estimator.estimatePx(rows)) - estimator.record(rows, 300) - estimator.record(rows, 500) - assertEquals(400, estimator.estimatePx(rows)) - estimator.record(cards, 20) - assertEquals(100, estimator.estimatePx(cards)) - } -} From 3bd21353c057051fd88c4eee0a1f35f48909ef0e Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sun, 29 Nov 2026 00:37:47 +0100 Subject: [PATCH 2/3] feat(android): check in debug builds that the offset model matches the layout --- .../main/java/me/sectiontn/flume/FlumeView.kt | 45 ++++++++++++++-- .../main/java/me/sectiontn/flume/ModelFeed.kt | 36 +++++++++++++ .../me/sectiontn/flume/ModelAgreementTest.kt | 52 +++++++++++++++++++ 3 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 android/src/test/java/me/sectiontn/flume/ModelAgreementTest.kt diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 9839d73..57ec118 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -1,12 +1,14 @@ package me.sectiontn.flume import android.content.Context +import android.content.pm.ApplicationInfo import android.graphics.Canvas import android.view.MotionEvent import android.view.View import android.view.VelocityTracker import android.view.ViewConfiguration import android.content.res.Configuration +import android.util.Log import android.os.SystemClock import android.widget.FrameLayout import androidx.recyclerview.widget.GridLayoutManager @@ -361,7 +363,7 @@ class FlumeView(context: Context) : FrameLayout(context) { } private fun onLaidOut() { - pushLengths() + checkModel(pushLengths()) animator.still = false if (reclaimOnLayout) { reclaimOnLayout = false @@ -449,12 +451,49 @@ class FlumeView(context: Context) : FrameLayout(context) { } // The lengths of the laid-out rows after each layout pass and scroll step. Unchanged ones cost nothing in the model. - private fun pushLengths() { - if (storeId == 0) return + private fun pushLengths(): List { + if (storeId == 0) return emptyList() val samples = childSamples() if (lengthPairs.size < 2 * samples.size) lengthPairs = IntArray(4 * samples.size) val count = LengthFeed.pairs(samples, lengthPairs) if (count > 0) model.push(lengthPairs, count) + return samples + } + + private val checksModel = (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0 + private var modelCheckOn = false + private var modelCheckLogged = false + + // Debug builds only: one log per list the first time RecyclerView and the model disagree. + private fun checkModel(samples: List) { + if (!checksModel || modelCheckLogged || storeId == 0 || samples.isEmpty() || recycler.itemAnimator?.isRunning == true) return + if (!modelCheckOn) { + modelCheckOn = true + Log.i("Flume", "offset model check on") + } + val horizontal = geometry.horizontal + val axis = if (horizontal) "x" else "y" + val viewport = if (horizontal) recycler.width else recycler.height + ModelAgreement.firstMismatch(samples, { model.startPx(it, viewport) })?.let { + modelCheckLogged = true + Log.w("Flume", "offset model: position ${it.position} starts at ${it.actualPx} px on screen and ${it.modelPx} px in the model ()") + return + } + val first = samples.firstOrNull { it.position == 0 } ?: return + val padding = resolvedPaddingPx() + val drift = ModelAgreement.startDrift( + first, + model.startPx(0, viewport), + inverted, + if (horizontal) padding[0] else padding[1], + if (horizontal) padding[2] else padding[3], + viewport, + model.contentLengthPx(viewport), + ) ?: return + if (kotlin.math.abs(drift) > 1.0) { + modelCheckLogged = true + Log.w("Flume", "offset model: position 0 is $drift px off the content start ()") + } } // Each child's own start and natural length; a React row that has not rendered has no length yet. diff --git a/android/src/main/java/me/sectiontn/flume/ModelFeed.kt b/android/src/main/java/me/sectiontn/flume/ModelFeed.kt index e7995f9..b3afdf5 100644 --- a/android/src/main/java/me/sectiontn/flume/ModelFeed.kt +++ b/android/src/main/java/me/sectiontn/flume/ModelFeed.kt @@ -1,5 +1,7 @@ package me.sectiontn.flume +import kotlin.math.abs + // A laid-out child as the offset model sees it: its own start and natural length along the axis, never its decorated ones. data class ChildSample(val position: Int, val startPx: Int, val lengthPx: Int, val measured: Boolean, val leaving: Boolean) @@ -25,3 +27,37 @@ object ModelOps { fun resetsOnAttach(previousStore: Int, store: Int, previousCount: Int, count: Int): Boolean = previousStore != store || previousCount != count } + +data class Mismatch(val position: Int, val modelPx: Double, val actualPx: Int) + +// Debug builds compare where RecyclerView placed the rows with where the model puts them, after each layout pass. +object ModelAgreement { + // Each start relative to the first child's, so the scroll offset cancels out. + fun firstMismatch(samples: List, startPx: (Int) -> Double, tolerancePx: Double = 1.0): Mismatch? { + val first = samples.firstOrNull { !it.leaving && it.position >= 0 } ?: return null + val firstModel = startPx(first.position) + for (sample in samples) { + if (sample.leaving || sample.position < 0) continue + val model = startPx(sample.position) - firstModel + first.startPx + if (abs(model - sample.startPx) > tolerancePx) return Mismatch(sample.position, model, sample.startPx) + } + return null + } + + // A constant error (padding, slack, a header) escapes the relative check and moves the offset at the top off 0. + // Null unless position 0 rests at the content start, the visual bottom when inverted. + fun startDrift( + first: ChildSample, + modelStartPx: Double, + inverted: Boolean, + paddingStartPx: Int, + paddingEndPx: Int, + viewportPx: Int, + contentLengthPx: Double, + ): Double? { + if (first.position != 0 || first.leaving) return null + if (!inverted) return if (first.startPx < paddingStartPx) null else modelStartPx - first.startPx + if (first.startPx + first.lengthPx > viewportPx - paddingEndPx) return null + return modelStartPx - (contentLengthPx - viewportPx) - first.startPx + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ModelAgreementTest.kt b/android/src/test/java/me/sectiontn/flume/ModelAgreementTest.kt new file mode 100644 index 0000000..2c01bb3 --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/ModelAgreementTest.kt @@ -0,0 +1,52 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ModelAgreementTest { + private fun sample(position: Int, start: Int, length: Int = 100, leaving: Boolean = false) = + ChildSample(position, startPx = start, lengthPx = length, measured = true, leaving = leaving) + + private fun starts(vararg values: Double): (Int) -> Double = { values[it] } + + @Test + fun agreesWhenStartsMatch() { + assertNull(ModelAgreement.firstMismatch(listOf(sample(0, 16), sample(1, 96), sample(2, 216)), starts(16.0, 96.0, 216.0))) + } + + @Test + fun reportsTheFirstDrift() { + assertEquals(Mismatch(1, 98.0, 96), ModelAgreement.firstMismatch(listOf(sample(0, 16), sample(1, 96), sample(2, 216)), starts(16.0, 98.0, 216.0))) + } + + @Test + fun ignoresLeavingChildren() { + assertNull(ModelAgreement.firstMismatch(listOf(sample(0, 16), sample(1, 500, leaving = true)), starts(16.0, 96.0))) + } + + @Test + fun cellsOfOneGridRowShareAStart() { + assertNull(ModelAgreement.firstMismatch(listOf(sample(2, 216), sample(3, 216)), starts(0.0, 0.0, 216.0, 216.0))) + } + + @Test + fun startDriftIsZeroAtTheTopWithSlack() { + assertEquals(0.0, ModelAgreement.startDrift(sample(0, 116), 116.0, false, 16, 16, 400, 400.0)!!, 0.0) + } + + @Test + fun startDriftShowsAPaddingError() { + assertEquals(8.0, ModelAgreement.startDrift(sample(0, 116), 124.0, false, 16, 16, 400, 400.0)!!, 0.0) + } + + @Test + fun noStartDriftOncePositionZeroIsCut() { + assertNull(ModelAgreement.startDrift(sample(0, 6), 16.0, false, 16, 16, 400, 1032.0)) + } + + @Test + fun startDriftMirrorsAnInvertedList() { + assertEquals(0.0, ModelAgreement.startDrift(sample(0, 284), 916.0, true, 16, 16, 400, 1032.0)!!, 0.0) + } +} From bf259245bbd8fc1cf8c65c39ae9e0f79053f964d Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sun, 29 Nov 2026 00:42:58 +0100 Subject: [PATCH 3/3] fix(android): run the offset model check when a scroll comes to rest --- android/src/main/java/me/sectiontn/flume/FlumeView.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 57ec118..61b308a 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -293,6 +293,8 @@ class FlumeView(context: Context) : FrameLayout(context) { if (newState == RecyclerView.SCROLL_STATE_IDLE && throttle.flush() && emitScrollEvents) emitScroll(ScrollKind.SCROLL) if (newState == RecyclerView.SCROLL_STATE_IDLE) { realign() + // A list whose layout passes all ran item animations gets checked at rest instead. + checkModel(childSamples()) // Inline, so the state is queued before a touch the next looper turn delivers. writeOrigins() if (landOnIdle && movedSinceScroll) {