diff --git a/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt b/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt index 14fe1b6..a7bc3aa 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt @@ -13,6 +13,8 @@ object ExtraLayoutSpace { private fun LinearLayoutManager.viewportPx(): Int = if (orientation == RecyclerView.VERTICAL) height - paddingTop - paddingBottom else width - paddingLeft - paddingRight +private fun OffsetSource?.live(): OffsetSource? = this?.takeIf { it.active } + private fun LinearLayoutManager.fillExtraSpace(drawDistancePx: Int, extraLayoutSpace: IntArray) { val extra = ExtraLayoutSpace.of(drawDistancePx, viewportPx()) extraLayoutSpace[0] = extra @@ -24,6 +26,7 @@ class FlumeLinearLayoutManager(context: Context, orientation: Int, reverse: Bool var drawDistancePx = -1 var onLaidOut: (() -> Unit)? = null var onScrolledBy: (() -> Unit)? = null + var offsets: OffsetSource? = null var justify = ContentJustify.Start override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) { @@ -45,6 +48,19 @@ class FlumeLinearLayoutManager(context: Context, orientation: Int, reverse: Bool override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int = super.scrollHorizontallyBy(dx, recycler, state).also { onScrolledBy?.invoke() } + + // The model's exact offsets, which scroll events, edges, pull to refresh and the scroll bars read. + override fun computeVerticalScrollOffset(state: RecyclerView.State): Int = offsets.live()?.offsetPx() ?: super.computeVerticalScrollOffset(state) + + override fun computeVerticalScrollRange(state: RecyclerView.State): Int = offsets.live()?.rangePx() ?: super.computeVerticalScrollRange(state) + + override fun computeVerticalScrollExtent(state: RecyclerView.State): Int = offsets.live()?.extentPx() ?: super.computeVerticalScrollExtent(state) + + override fun computeHorizontalScrollOffset(state: RecyclerView.State): Int = offsets.live()?.offsetPx() ?: super.computeHorizontalScrollOffset(state) + + override fun computeHorizontalScrollRange(state: RecyclerView.State): Int = offsets.live()?.rangePx() ?: super.computeHorizontalScrollRange(state) + + override fun computeHorizontalScrollExtent(state: RecyclerView.State): Int = offsets.live()?.extentPx() ?: super.computeHorizontalScrollExtent(state) } class FlumeGridLayoutManager(context: Context, spanCount: Int, orientation: Int, reverse: Boolean) : @@ -52,6 +68,7 @@ class FlumeGridLayoutManager(context: Context, spanCount: Int, orientation: Int, var drawDistancePx = -1 var onLaidOut: (() -> Unit)? = null var onScrolledBy: (() -> Unit)? = null + var offsets: OffsetSource? = null var justify = ContentJustify.Start override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) { @@ -80,6 +97,19 @@ class FlumeGridLayoutManager(context: Context, spanCount: Int, orientation: Int, override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int = super.scrollHorizontallyBy(dx, recycler, state).also { onScrolledBy?.invoke() } + + // The model's exact offsets, which scroll events, edges, pull to refresh and the scroll bars read. + override fun computeVerticalScrollOffset(state: RecyclerView.State): Int = offsets.live()?.offsetPx() ?: super.computeVerticalScrollOffset(state) + + override fun computeVerticalScrollRange(state: RecyclerView.State): Int = offsets.live()?.rangePx() ?: super.computeVerticalScrollRange(state) + + override fun computeVerticalScrollExtent(state: RecyclerView.State): Int = offsets.live()?.extentPx() ?: super.computeVerticalScrollExtent(state) + + override fun computeHorizontalScrollOffset(state: RecyclerView.State): Int = offsets.live()?.offsetPx() ?: super.computeHorizontalScrollOffset(state) + + override fun computeHorizontalScrollRange(state: RecyclerView.State): Int = offsets.live()?.rangePx() ?: super.computeHorizontalScrollRange(state) + + override fun computeHorizontalScrollExtent(state: RecyclerView.State): Int = offsets.live()?.extentPx() ?: super.computeHorizontalScrollExtent(state) } // 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/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 61b308a..6432a39 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -45,6 +45,17 @@ class FlumeView(context: Context) : FrameLayout(context) { private val adapter = FlumeAdapter(context, measurer, recycler, slots, model) private var estimatedPx = -1 private var lengthPairs = IntArray(64) + private val offsetReader = OffsetReader( + model, + object : OffsetFrame { + override val attached get() = storeId != 0 + override val viewportPx get() = if (geometry.horizontal) recycler.width else recycler.height + override val paddingStartPx get() = if (geometry.horizontal) recycler.paddingLeft else recycler.paddingTop + override val paddingEndPx get() = if (geometry.horizontal) recycler.paddingRight else recycler.paddingBottom + + override fun samples() = childSamples() + }, + ) 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 @@ -64,6 +75,7 @@ class FlumeView(context: Context) : FrameLayout(context) { private val measureHolderId = adapter.allocateHolderId() private var throttle = ScrollThrottle(16) private val velocity = ScrollVelocity() + private val offsetWatch = OffsetWatch() private var finger: VelocityTracker? = null private var scrollState = RecyclerView.SCROLL_STATE_IDLE private var pendingAlign: PendingAlign? = null @@ -81,12 +93,8 @@ class FlumeView(context: Context) : FrameLayout(context) { private val commands = ScrollCommands() // The jump of the command in flight once it has run, which new data sends again at its target. private var landing: Jump? = null - // The offset of the command's glide in flight, which a data reset sends again. - private var landingOffsetDp: Double? = null - // An instant scroll lands with the next layout pass, an offset glide at its first idle state after it moved. + // An instant scroll lands with the next layout pass. 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 @@ -236,12 +244,9 @@ class FlumeView(context: Context) : FrameLayout(context) { viewability.invalidate() // A command still on its way lands on its target in the new rows, not where anchoring keeps the old ones. val again = landing?.takeIf { commands.pending != 0 && jumps.pending == null } - // Only a reset stops an offset glide, so only a reset sends it again. - val againOffset = landingOffsetDp?.takeIf { reset && commands.pending != 0 } - if (again != null || againOffset != null) { + if (again != null) { scrollToken++ pendingAlign = null - landOnIdle = false // Begun again before stopScroll, whose idle state would end a command its scroller had landed. commands.begin(commands.pending) } @@ -252,8 +257,6 @@ class FlumeView(context: Context) : FrameLayout(context) { applySpans() if (again != null) { requestJump(again.target, again.animated, again.viewPosition, again.viewOffsetDp) - } else if (againOffset != null) { - scrollToOffset(commands.pending, againOffset, true) } else { retargetJump() } @@ -268,7 +271,9 @@ class FlumeView(context: Context) : FrameLayout(context) { // ScrollView samples its velocity on every change, before the throttle. val now = SystemClock.uptimeMillis() val metrics = scrollMetrics() - velocity.scrolled(ScrollMetrics.fromContentStart(metrics.offsetPx, metrics.rangePx, metrics.extentPx, inverted), now) + val offsetPx = ScrollMetrics.fromContentStart(metrics.offsetPx, metrics.rangePx, metrics.extentPx, inverted) + velocity.scrolled(offsetPx, now) + offsetWatch.scrolled(offsetPx) if (throttle.shouldEmit(now)) emitScroll(ScrollKind.SCROLL, metrics = metrics) } evaluateViewability() @@ -281,7 +286,6 @@ 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) } @@ -297,10 +301,6 @@ class FlumeView(context: Context) : FrameLayout(context) { checkModel(childSamples()) // 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) { @@ -319,10 +319,12 @@ class FlumeView(context: Context) : FrameLayout(context) { is FlumeLinearLayoutManager -> { lm.onLaidOut = { onLaidOut() } lm.onScrolledBy = { pushLengths() } + lm.offsets = offsetReader } is FlumeGridLayoutManager -> { lm.onLaidOut = { onLaidOut() } lm.onScrolledBy = { pushLengths() } + lm.offsets = offsetReader } } applyFullSpan() @@ -383,6 +385,12 @@ class FlumeView(context: Context) : FrameLayout(context) { sticky.refresh() updateEmptyLength() updateFooterLength() + if (emitScrollEvents) { + val metrics = scrollMetrics() + if (offsetWatch.laidOut(ScrollMetrics.fromContentStart(metrics.offsetPx, metrics.rangePx, metrics.extentPx, inverted))) { + emitScroll(ScrollKind.SCROLL, metrics = metrics) + } + } evaluateViewability() evaluateEdges() requestOrigins() @@ -521,7 +529,7 @@ class FlumeView(context: Context) : FrameLayout(context) { return out } - // Offset, range and extent along the scroll axis, as RecyclerView estimates them from the laid-out rows. + // Offset, range and extent along the scroll axis, which the layout manager reads from the offset model. private fun scrollMetrics(): ScrollRange = if (geometry.horizontal) { ScrollRange(recycler.computeHorizontalScrollOffset(), recycler.computeHorizontalScrollRange(), recycler.computeHorizontalScrollExtent()) } else { @@ -592,7 +600,7 @@ class FlumeView(context: Context) : FrameLayout(context) { private fun requestJump(target: JumpTarget, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { jumps.cancel()?.let { dropJump(it) } forgetLanding() - if (target.position(rows) == null && !target.waitsForData(rows)) { + if (landingOf(target, viewOffsetDp) == null && !target.waitsForData(rows)) { landCommand() return } @@ -609,8 +617,8 @@ class FlumeView(context: Context) : FrameLayout(context) { // 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 at = landingOf(jump.target, jump.viewOffsetDp) ?: return emptySet() + val window = jumpWindow(at.position, jump.animated, jump.viewPosition, at.deeperPx) val requests = window.filter { isReactRow(it) }.map { adapter.slotRequest(it, viewTypeAt(it)) } return slots.reserve(jump.owner, requests) } @@ -629,18 +637,27 @@ class FlumeView(context: Context) : FrameLayout(context) { private fun runJump(jump: Jump) { removeCallbacks(jumpDue) slots.lend(jump.owner) - val position = jump.target.position(rows) ?: return landCommand() + val at = landingOf(jump.target, jump.viewOffsetDp) ?: return landCommand() if (jump.animated) reclaimOnIdle = true else reclaimOnLayout = true landing = jump - startScroll(position, jump.animated, jump.viewPosition, jump.viewOffsetDp) + startScroll(at.position, jump.animated, jump.viewPosition, at.viewOffsetPx) + } + + // Where a jump lands in the current rows. An offset lands its row a remainder deeper, which the reserved rows reach too. + private class JumpLanding(val position: Int, val viewOffsetPx: Int, val deeperPx: Int) + + private fun landingOf(target: JumpTarget, viewOffsetDp: Double): JumpLanding? = when (target) { + is JumpTarget.Offset -> model.landing(target.contentOffsetPx, axisLengthPx()).takeIf { it.position >= 0 }?.let { + JumpLanding(it.position, ScrollTargets.landingViewOffsetPx(it, contentStartPaddingPx()), it.remainderPx.roundToInt().coerceAtLeast(0)) + } + is JumpTarget.Index, is JumpTarget.Position, JumpTarget.End -> + target.position(rows)?.let { JumpLanding(it, (viewOffsetDp * density).roundToInt(), 0) } } // A new scroll replaces the landing of the one before it. private fun forgetLanding() { landing = null - landingOffsetDp = null landOnLayout = false - landOnIdle = false scrollToken++ } @@ -660,7 +677,6 @@ class FlumeView(context: Context) : FrameLayout(context) { ) if (ended != 0) { landing = null - landingOffsetDp = null dispatch(FlumeScrollCommandEndEvent(UIManagerHelper.getSurfaceId(this), id, ended)) } } @@ -668,9 +684,7 @@ class FlumeView(context: Context) : FrameLayout(context) { // A drag, leaving the window, anchoring's own scroll or a dropped view ends the command in flight. fun endScrollCommand() { landing = null - landingOffsetDp = null landOnLayout = false - landOnIdle = false val ended = commands.end() if (ended != 0) dispatch(FlumeScrollCommandEndEvent(UIManagerHelper.getSurfaceId(this), id, ended)) } @@ -681,9 +695,9 @@ class FlumeView(context: Context) : FrameLayout(context) { } // An instant jump shows one screen around its target; an animated one also its landing screen and the rows it glides over. - private fun jumpWindow(target: Int, animated: Boolean, viewPosition: Float): IntRange { + private fun jumpWindow(target: Int, animated: Boolean, viewPosition: Float, deeperPx: Int): IntRange { val viewportPx = if (geometry.horizontal) geometry.innerWidthPx else geometry.innerHeightPx - val window = ScrollTargets.jumpWindow(target, viewPosition, viewportPx, rows.itemCount, ::windowLengthPx) + val window = ScrollTargets.jumpWindow(target, viewPosition, viewportPx + deeperPx, rows.itemCount, ::windowLengthPx) if (!animated) return window val first = layoutManager.findFirstVisibleItemPosition() if (first == RecyclerView.NO_POSITION) return window @@ -704,12 +718,11 @@ class FlumeView(context: Context) : FrameLayout(context) { return model.itemLengthPx(position) } - private fun startScroll(position: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { + private fun startScroll(position: Int, animated: Boolean, viewPosition: Float, viewOffsetPx: Int) { val target = ScrollTargets.clampIndex(position, rows.itemCount) ?: return landCommand() val token = scrollToken viewability.interacted = true recycler.stopScroll() - val viewOffsetPx = (viewOffsetDp * density).roundToInt() val anchoredAtEnd = layoutManager.stackFromEnd val realigns = ScrollTargets.realigns(isReactRow(target), viewPosition, anchoredAtEnd) pendingAlign = null @@ -864,7 +877,7 @@ class FlumeView(context: Context) : FrameLayout(context) { slots.setMinMain(holder, emptyListGrowSharePx() / density) } - // Offsets count from the content start; the visual delta flips for an inverted list. + // Offsets count from the content start. The jump finds the row that holds the offset each time it reads it, so it follows new data. fun scrollToOffset(id: Int, offsetDp: Double, animated: Boolean) { commands.begin(id) viewability.interacted = true @@ -873,25 +886,17 @@ class FlumeView(context: Context) : FrameLayout(context) { jumps.cancel()?.let { dropJump(it) } forgetLanding() recycler.stopScroll() - val targetPx = (offsetDp * density).roundToInt() - ScrollTargets.startRow(targetPx)?.let { row -> - requestJump(JumpTarget.Position(row), animated, 0f, 0.0) - return - } - val (offsetPx, rangePx, extentPx) = scrollMetrics() - val delta = targetPx - ScrollMetrics.fromContentStart(offsetPx, rangePx, extentPx, inverted) - val visual = if (inverted) -delta else delta - val dx = if (geometry.horizontal) visual else 0 - val dy = if (geometry.horizontal) 0 else visual - if (visual != 0 && animated) { - movedSinceScroll = false - landOnIdle = true - landingOffsetDp = offsetDp - recycler.smoothScrollBy(dx, dy) - return - } - if (visual != 0) recycler.scrollBy(dx, dy) - landCommand() + val viewportPx = axisLengthPx() + val lastPx = maxOf(0.0, model.contentLengthPx(viewportPx) - viewportPx) + requestJump(JumpTarget.Offset((offsetDp * density).coerceIn(0.0, lastPx)), animated, 0f, 0.0) + } + + private fun axisLengthPx(): Int = if (geometry.horizontal) recycler.width else recycler.height + + // The padding at the content start, the visual end when inverted, where a landing's view offset counts from. + private fun contentStartPaddingPx(): Int = when { + geometry.horizontal -> if (inverted) recycler.paddingRight else recycler.paddingLeft + else -> if (inverted) recycler.paddingBottom else recycler.paddingTop } fun scrollToEnd(id: Int, animated: Boolean) { diff --git a/android/src/main/java/me/sectiontn/flume/JumpTarget.kt b/android/src/main/java/me/sectiontn/flume/JumpTarget.kt index ef3334b..bfc1f7b 100644 --- a/android/src/main/java/me/sectiontn/flume/JumpTarget.kt +++ b/android/src/main/java/me/sectiontn/flume/JumpTarget.kt @@ -9,11 +9,15 @@ sealed interface JumpTarget { data object End : JumpTarget - // The adapter position to land on, or null with no rows. + // A content offset in px. Which row holds it depends on row lengths, so FlumeView resolves it with the offset model. + data class Offset(val contentOffsetPx: Double) : JumpTarget + + // The adapter position to land on, or null with no rows or for an offset. 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) + is Offset -> null } // An index past the data waits for the data to grow, as when new data and the scroll come from one handler. diff --git a/android/src/main/java/me/sectiontn/flume/ModelOffsets.kt b/android/src/main/java/me/sectiontn/flume/ModelOffsets.kt new file mode 100644 index 0000000..34f40aa --- /dev/null +++ b/android/src/main/java/me/sectiontn/flume/ModelOffsets.kt @@ -0,0 +1,65 @@ +package me.sectiontn.flume + +import kotlin.math.max +import kotlin.math.roundToInt + +// Scroll offset, range and extent in RecyclerView's frame: from the visual top, inside the padding. +interface OffsetSource { + val active: Boolean + + fun offsetPx(): Int + + fun rangePx(): Int + + fun extentPx(): Int +} + +// The list along its scroll axis and its laid-out children at the moment of a read. +interface OffsetFrame { + val attached: Boolean + val viewportPx: Int + val paddingStartPx: Int + val paddingEndPx: Int + + fun samples(): List +} + +// Reads the offset from where the model puts the topmost laid-out child, in place of RecyclerView's average-length estimate. +class OffsetReader(private val model: OffsetModel, private val frame: OffsetFrame) : OffsetSource { + private var lastOffsetPx = 0 + + override val active: Boolean get() = frame.attached + + override fun rangePx(): Int = + model.contentLengthPx(frame.viewportPx).roundToInt() - frame.paddingStartPx - frame.paddingEndPx + + override fun extentPx(): Int = frame.viewportPx - frame.paddingStartPx - frame.paddingEndPx + + // The last offset stands while no child has a position, as during a change that removes every laid-out row. + override fun offsetPx(): Int { + var top: ChildSample? = null + for (sample in frame.samples()) { + if (sample.leaving || sample.position < 0) continue + if (top == null || sample.startPx < top.startPx) top = sample + } + if (top == null) return lastOffsetPx + val offset = (model.startPx(top.position, frame.viewportPx) - top.startPx).roundToInt() + lastOffsetPx = offset.coerceIn(0, max(0, rangePx() - extentPx())) + return lastOffsetPx + } +} + +// A layout pass that moves the offset without a scroll, as when rows above the viewport measure, reports it as UIKit does. +class OffsetWatch { + private var lastOffsetPx = 0 + + fun scrolled(offsetPx: Int) { + lastOffsetPx = offsetPx + } + + fun laidOut(offsetPx: Int): Boolean { + if (offsetPx == lastOffsetPx) return false + lastOffsetPx = offsetPx + return true + } +} diff --git a/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt b/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt index 9a1d9ca..0f59ac0 100644 --- a/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt +++ b/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt @@ -11,8 +11,8 @@ import kotlin.math.roundToInt // viewPosition is in content order: 0 puts the item's start edge at the list's start edge, 1 its end at the end. object ScrollTargets { - // An offset at or before the content start is the first row, which a position scroll reaches exactly; a further offset is an estimate. - fun startRow(targetPx: Int): Int? = if (targetPx <= 0) 0 else null + // The view offset that puts a landing row where its content offset sits, from the padded content-start edge. + fun landingViewOffsetPx(landing: OffsetLanding, contentStartPaddingPx: Int): Int = (-landing.remainderPx).roundToInt() - contentStartPaddingPx fun clampIndex(index: Int, count: Int): Int? = if (count <= 0) null else index.coerceIn(0, count - 1) diff --git a/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt b/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt index 0a6fad4..efaa7a5 100644 --- a/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt +++ b/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt @@ -9,6 +9,11 @@ import org.junit.Test class JumpTargetTest { private val rows = ListRows(header = true, dataCount = 10, footer = true) + @Test + fun anOffsetTargetWaitsForNoData() { + assertFalse(JumpTarget.Offset(300.0).waitsForData(rows)) + } + @Test fun anIndexLandsOnItsDataRow() { assertEquals(4, JumpTarget.Index(3).position(rows)) diff --git a/android/src/test/java/me/sectiontn/flume/OffsetReaderTest.kt b/android/src/test/java/me/sectiontn/flume/OffsetReaderTest.kt new file mode 100644 index 0000000..045c130 --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/OffsetReaderTest.kt @@ -0,0 +1,80 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class OffsetReaderTest { + // Rows of 100 px inside padding of 16 and 16, in the visual frame, so an inverted list starts its last row at the top. + private class RowsModel(private val count: Int, private val inverted: Boolean = false) : OffsetModel { + override fun configure(config: OffsetModelConfig, fullSpanPositions: IntArray) = Unit + override fun reset(storeId: Int, rows: ListRows) = Unit + override fun apply( + storeId: Int, + rows: ListRows, + reset: Boolean, + removed: IntArray, + inserted: IntArray, + moved: IntArray, + changed: IntArray, + fullSpanPositions: IntArray, + ) = Unit + override fun push(pairs: IntArray, count: Int): Int = 0 + override fun invalidateLengths() = Unit + override fun startPx(position: Int, viewportPx: Int): Double = 16.0 + 100.0 * (if (inverted) count - 1 - position else position) + override fun itemLengthPx(position: Int): Int = 100 + override fun contentLengthPx(viewportPx: Int): Double = 32.0 + 100.0 * count + override fun estimatePx(viewType: Int): Int = 100 + override fun landing(contentOffsetPx: Double, viewportPx: Int): OffsetLanding = OffsetLanding(-1, 0.0) + override fun drop() = Unit + } + + private class Frame(var children: List) : OffsetFrame { + override val attached = true + override val viewportPx = 400 + override val paddingStartPx = 16 + override val paddingEndPx = 16 + override fun samples(): List = children + } + + private fun sample(position: Int, start: Int, leaving: Boolean = false) = + ChildSample(position, startPx = start, lengthPx = 100, measured = true, leaving = leaving) + + @Test + fun topRowAtThePaddingReadsZero() { + val reader = OffsetReader(RowsModel(10), Frame((0..3).map { sample(it, 16 + 100 * it) })) + assertEquals(0, reader.offsetPx()) + assertEquals(1000, reader.rangePx()) + assertEquals(368, reader.extentPx()) + } + + @Test + fun midListReadsTheExactOffset() { + val reader = OffsetReader(RowsModel(10), Frame(listOf(sample(3, 40), sample(4, 140), sample(5, 240)))) + assertEquals(276, reader.offsetPx()) + } + + @Test + fun invertedWithPaddingCountsFromTheContentStart() { + val reader = OffsetReader(RowsModel(10, inverted = true), Frame((0..4).map { sample(it, 316 - 100 * it) })) + val offset = reader.offsetPx() + assertEquals(600, offset) + assertEquals(32, ScrollMetrics.fromContentStart(offset, reader.rangePx(), reader.extentPx(), true)) + } + + @Test + fun keepsTheLastOffsetWhileNoChildHasAPosition() { + val frame = Frame(listOf(sample(3, 40))) + val reader = OffsetReader(RowsModel(10), frame) + assertEquals(276, reader.offsetPx()) + frame.children = listOf(sample(3, 90, leaving = true), sample(-1, 0)) + assertEquals(276, reader.offsetPx()) + } + + @Test + fun shortContentNeverScrolls() { + val reader = OffsetReader(RowsModel(2), Frame(listOf(sample(0, 16), sample(1, 116)))) + assertTrue(reader.rangePx() - reader.extentPx() < 0) + assertEquals(0, reader.offsetPx()) + } +} diff --git a/android/src/test/java/me/sectiontn/flume/OffsetWatchTest.kt b/android/src/test/java/me/sectiontn/flume/OffsetWatchTest.kt new file mode 100644 index 0000000..aaa8adc --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/OffsetWatchTest.kt @@ -0,0 +1,22 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OffsetWatchTest { + @Test + fun aScrollThenTheSameLayoutSendsNothing() { + val watch = OffsetWatch() + watch.scrolled(100) + assertFalse(watch.laidOut(100)) + } + + @Test + fun aCorrectionSendsOneEvent() { + val watch = OffsetWatch() + watch.scrolled(100) + assertTrue(watch.laidOut(124)) + assertFalse(watch.laidOut(124)) + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ScrollTargetsTest.kt b/android/src/test/java/me/sectiontn/flume/ScrollTargetsTest.kt index 760cc53..c6f38b4 100644 --- a/android/src/test/java/me/sectiontn/flume/ScrollTargetsTest.kt +++ b/android/src/test/java/me/sectiontn/flume/ScrollTargetsTest.kt @@ -37,10 +37,13 @@ class ScrollTargetsTest { } @Test - fun aTargetAtOrBeforeTheStartIsTheFirstRow() { - assertEquals(0, ScrollTargets.startRow(0)) - assertEquals(0, ScrollTargets.startRow(-40)) - assertNull(ScrollTargets.startRow(1)) + fun landingAtTheTopKeepsRowZeroAtThePadding() { + assertEquals(0, ScrollTargets.landingViewOffsetPx(OffsetLanding(0, -16.0), 16)) + } + + @Test + fun landingMidRow() { + assertEquals(-50, ScrollTargets.landingViewOffsetPx(OffsetLanding(2, 34.0), 16)) } @Test