Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {
Expand All @@ -45,13 +48,27 @@ 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) :
GridLayoutManager(context, spanCount, orientation, reverse) {
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) {
Expand Down Expand Up @@ -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).
Expand Down
109 changes: 57 additions & 52 deletions android/src/main/java/me/sectiontn/flume/FlumeView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
}
Expand All @@ -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()
}
Expand All @@ -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()
Expand All @@ -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) }
Expand All @@ -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) {
Expand All @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand All @@ -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<Int> {
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)
}
Expand All @@ -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++
}

Expand All @@ -660,17 +677,14 @@ class FlumeView(context: Context) : FrameLayout(context) {
)
if (ended != 0) {
landing = null
landingOffsetDp = null
dispatch(FlumeScrollCommandEndEvent(UIManagerHelper.getSurfaceId(this), id, ended))
}
}

// A drag, leaving the window, anchoring's own scroll or a dropped view ends the command in flight.
fun endScrollCommand() {
landing = null
landingOffsetDp = null
landOnLayout = false
landOnIdle = false
val ended = commands.end()
if (ended != 0) dispatch(FlumeScrollCommandEndEvent(UIManagerHelper.getSurfaceId(this), id, ended))
}
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down
6 changes: 5 additions & 1 deletion android/src/main/java/me/sectiontn/flume/JumpTarget.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading