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
64 changes: 64 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ class FlumeLinearLayoutManager(context: Context, orientation: Int, reverse: Bool
LinearLayoutManager(context, orientation, reverse) {
var drawDistancePx = -1
var onLaidOut: (() -> Unit)? = null
var justify = ContentJustify.Start

override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
super.onLayoutChildren(recycler, state)
if (justify != ContentJustify.Start) placeShortContent(this, state, justify)
}

override fun calculateExtraLayoutSpace(state: RecyclerView.State, extraLayoutSpace: IntArray) =
fillExtraSpace(drawDistancePx, extraLayoutSpace)
Expand All @@ -37,6 +43,12 @@ class FlumeGridLayoutManager(context: Context, spanCount: Int, orientation: Int,
GridLayoutManager(context, spanCount, orientation, reverse) {
var drawDistancePx = -1
var onLaidOut: (() -> Unit)? = null
var justify = ContentJustify.Start

override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
super.onLayoutChildren(recycler, state)
if (justify != ContentJustify.Start) placeShortContent(this, state, justify)
}
val fullSpanLookup = FlumeSpanSizeLookup { this.spanCount }

init {
Expand Down Expand Up @@ -121,3 +133,55 @@ data class LayoutShape(val horizontal: Boolean, val numColumns: Int, val inverte
previous != null && previous.inverted == next.inverted && previous.stackFromEnd == next.stackFromEnd
}
}

// FlatList's flexGrow content with justifyContent: short upright content moves to its place after every layout.
internal fun placeShortContent(lm: LinearLayoutManager, state: RecyclerView.State, justify: ContentJustify) {
if (state.isPreLayout || lm.childCount == 0 || lm.reverseLayout) return
val horizontal = lm.orientation == RecyclerView.HORIZONTAL
var first = Int.MAX_VALUE
var last = Int.MIN_VALUE
var hasFirst = false
var hasLast = false
for (i in 0 until lm.childCount) {
val child = lm.getChildAt(i) ?: continue
first = minOf(first, if (horizontal) lm.getDecoratedLeft(child) else lm.getDecoratedTop(child))
last = maxOf(last, if (horizontal) lm.getDecoratedRight(child) else lm.getDecoratedBottom(child))
val position = lm.getPosition(child)
if (position == 0) hasFirst = true
if (position == state.itemCount - 1) hasLast = true
}
if (!hasFirst || !hasLast) return
val start = if (horizontal) lm.paddingLeft else lm.paddingTop
val end = if (horizontal) lm.width - lm.paddingRight else lm.height - lm.paddingBottom
val shift = ContentPlacement.shift(justify, first, last, start, end)
if (shift == 0) return
if (horizontal) lm.offsetChildrenHorizontal(shift) else lm.offsetChildrenVertical(shift)
}

// contentContainerStyle justifyContent with flexGrow, as the share of the free space that goes before short content.
enum class ContentJustify(val lead: Float) {
Start(0f),
Center(0.5f),
End(1f);

companion object {
fun of(value: String?): ContentJustify = when (value) {
"center" -> Center
"end" -> End
else -> Start
}
}
}

object ContentPlacement {
// The move that puts short content at its place in the viewport, 0 once it is there or when it fills the viewport.
fun shift(justify: ContentJustify, firstStart: Int, lastEnd: Int, viewportStart: Int, viewportEnd: Int): Int {
val content = lastEnd - firstStart
val viewport = viewportEnd - viewportStart
if (content >= viewport) return 0
return viewportStart + ((viewport - content) * justify.lead).toInt() - firstStart
}

// A growing footer takes what the rows above it leave of the viewport.
fun footerMinPx(contentStart: Int, footerStart: Int, viewportPx: Int): Int = maxOf(0, viewportPx - (footerStart - contentStart))
}
58 changes: 58 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package me.sectiontn.flume

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.facebook.react.bridge.ReactContext
import com.facebook.react.uimanager.TouchTargetHelper
Expand Down Expand Up @@ -109,6 +113,54 @@ class FlumeRecyclerView(context: Context) : RecyclerView(context) {
var keyboardShouldPersistTaps = KeyboardTaps.NEVER
private val keyboardGesture = KeyboardGesture()
private val nativeGesture = NativeGestureTracker()
private val backgroundPaint = Paint()

// contentContainerStyle's backgroundColor, 0 for none: the rows and their padding, scrolled with them.
var contentBackground = 0
set(value) {
if (field == value) return
field = value
backgroundPaint.color = value
setWillNotDraw(false)
invalidate()
}

// Under the decorations, so a separator line draws over it.
override fun onDraw(c: Canvas) {
if (Color.alpha(contentBackground) != 0) drawContentBackground(c)
super.onDraw(c)
}

private fun drawContentBackground(c: Canvas) {
val lm = layoutManager as? LinearLayoutManager ?: return
val count = adapter?.itemCount ?: 0
if (childCount == 0 || count == 0) return
Comment thread
SectionTN marked this conversation as resolved.
Resolved
val horizontal = lm.orientation == HORIZONTAL
val firstPosition = if (lm.reverseLayout) count - 1 else 0
val lastPosition = if (lm.reverseLayout) 0 else count - 1
var firstStart = Int.MAX_VALUE
var lastEnd = Int.MIN_VALUE
var hasFirst = false
var hasLast = false
for (i in 0 until childCount) {
val child = getChildAt(i)
val shift = if (horizontal) child.translationX else child.translationY
val start = (if (horizontal) lm.getDecoratedLeft(child) else lm.getDecoratedTop(child)) + shift.toInt()
val end = (if (horizontal) lm.getDecoratedRight(child) else lm.getDecoratedBottom(child)) + shift.toInt()
firstStart = minOf(firstStart, start)
lastEnd = maxOf(lastEnd, end)
val position = getChildAdapterPosition(child)
if (position == firstPosition) hasFirst = true
if (position == lastPosition) hasLast = true
}
val span = ContentBackground.span(
firstStart, lastEnd, hasFirst, hasLast,
if (horizontal) paddingLeft else paddingTop, if (horizontal) paddingRight else paddingBottom,
if (horizontal) width else height,
)
if (horizontal) c.drawRect(span[0].toFloat(), 0f, span[1].toFloat(), height.toFloat(), backgroundPaint)
else c.drawRect(0f, span[0].toFloat(), width.toFloat(), span[1].toFloat(), backgroundPaint)
}

// The keyboard policy sees every gesture here, including the ones a row consumes.
override fun dispatchTouchEvent(e: MotionEvent): Boolean {
Expand Down Expand Up @@ -179,3 +231,9 @@ class FlumeRecyclerView(context: Context) : RecyclerView(context) {
return cell.isClickable || cell.hasPressableAt((x - cell.left - cell.translationX).toInt(), (y - cell.top - cell.translationY).toInt())
}
}

// Along the scroll axis: the padding past the first and last laid-out rows, the view's edge where those rows are off screen.
object ContentBackground {
fun span(firstStart: Int, lastEnd: Int, hasFirst: Boolean, hasLast: Boolean, paddingStart: Int, paddingEnd: Int, viewLength: Int): IntArray =
intArrayOf(if (hasFirst) firstStart - paddingStart else 0, if (hasLast) lastEnd + paddingEnd else viewLength)
}
69 changes: 63 additions & 6 deletions android/src/main/java/me/sectiontn/flume/FlumeView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class FlumeView(context: Context) : FrameLayout(context) {
// Null until the first build replaces the unhooked layout manager above.
private var shape: LayoutShape? = null
private val paddingPx = IntArray(4)
private val paddingPercent = FloatArray(4)
private var initialScrollPending = false
private var separator: SeparatorDecoration? = null
private val gapsPx = IntArray(5)
Expand Down Expand Up @@ -319,6 +320,7 @@ class FlumeView(context: Context) : FrameLayout(context) {
}
sticky.refresh()
updateEmptyLength()
updateFooterLength()
evaluateViewability()
evaluateEdges()
requestOrigins()
Expand Down Expand Up @@ -543,6 +545,40 @@ class FlumeView(context: Context) : FrameLayout(context) {
return ((if (geometry.horizontal) batch.rootWidth else batch.rootHeight) * density).roundToInt()
}


// contentContainerStyle flexGrow with justifyContent places short content and leaves the opening edge alone.
var contentJustify = ContentJustify.Start
set(value) {
if (field == value) return
field = value
applyDrawDistance()
recycler.requestLayout()
}

var growFooter = false
set(value) {
if (field == value) return
field = value
updateFooterLength()
}

// A growing footer takes what the laid-out rows above it leave of the viewport, an upright list only.
private fun updateFooterLength() {
if (!rows.footer || !geometry.ready) return
val footer = recycler.findViewHolderForAdapterPosition(rows.itemCount - 1) as? FlumeAdapter.Holder ?: return
val slot = footer.slot ?: return
val first = recycler.findViewHolderForAdapterPosition(0)?.itemView
val lm = layoutManager
val horizontal = geometry.horizontal
val px = if (!growFooter || inverted || first == null) {
0
} else {
val start = if (horizontal) lm.getDecoratedLeft(first) else lm.getDecoratedTop(first)
val footerStart = if (horizontal) lm.getDecoratedLeft(footer.itemView) else lm.getDecoratedTop(footer.itemView)
ContentPlacement.footerMinPx(start, footerStart, if (horizontal) geometry.innerWidthPx else geometry.innerHeightPx)
}
slots.setMinMain(slot, px / density)
}
// The empty row fills what the header and footer leave of the viewport, so flex content centers in the visible area.
private fun updateEmptyLength() {
if (!rows.hasEmptyRow || !geometry.ready) return
Expand Down Expand Up @@ -645,8 +681,22 @@ class FlumeView(context: Context) : FrameLayout(context) {
// Edges are 0 left, 1 top, 2 right, 3 bottom, in dp.
fun setContentPadding(edge: Int, dp: Double) {
paddingPx[edge] = (dp * density).roundToInt()
recycler.setPadding(paddingPx[0], paddingPx[1], paddingPx[2], paddingPx[3])
adapter.configure(horizontal, numColumns, inverted, paddingPx, lanes())
applyPadding()
}

// Edges as above, a fraction of the list width as Yoga resolves a percent on every edge.
fun setPaddingPercent(edge: Int, fraction: Double) {
if (paddingPercent[edge] == fraction.toFloat()) return
paddingPercent[edge] = fraction.toFloat()
applyPadding()
}

private fun resolvedPaddingPx() = ListGeometry.paddingPx(paddingPx, paddingPercent, width)

private fun applyPadding() {
val resolved = resolvedPaddingPx()
recycler.setPadding(resolved[0], resolved[1], resolved[2], resolved[3])
adapter.configure(horizontal, numColumns, inverted, resolved, lanes())
sticky.refresh(force = true)
}

Expand All @@ -655,7 +705,7 @@ class FlumeView(context: Context) : FrameLayout(context) {
val px = (dp.coerceAtLeast(0.0) * density).roundToInt()
if (gapsPx[kind] == px) return
gapsPx[kind] = px
if (kind >= 2) adapter.configure(horizontal, numColumns, inverted, paddingPx, lanes())
if (kind >= 2) adapter.configure(horizontal, numColumns, inverted, resolvedPaddingPx(), lanes())
val on = gapsPx.any { it > 0 }
gaps?.takeIf { !on }?.let { recycler.removeItemDecoration(it) }
gaps = if (on) gaps ?: GapDecoration(gapsPx) { rows }.also { recycler.addItemDecoration(it) } else null
Expand All @@ -681,15 +731,21 @@ class FlumeView(context: Context) : FrameLayout(context) {
hookLayoutManager()
recycler.layoutManager = layoutManager
kept?.let { layoutManager.scrollToPositionWithOffset(it.firstVisiblePosition, it.firstVisibleOffsetPx) }
adapter.configure(horizontal, numColumns, inverted, paddingPx, lanes())
adapter.configure(horizontal, numColumns, inverted, resolvedPaddingPx(), lanes())
sticky.refresh(force = true)
}

private fun applyDrawDistance() {
val px = if (drawDistanceDp < 0) -1 else (drawDistanceDp * density).roundToInt()
when (val lm = layoutManager) {
is FlumeLinearLayoutManager -> lm.drawDistancePx = px
is FlumeGridLayoutManager -> lm.drawDistancePx = px
is FlumeLinearLayoutManager -> {
lm.drawDistancePx = px
lm.justify = contentJustify
}
is FlumeGridLayoutManager -> {
lm.drawDistancePx = px
lm.justify = contentJustify
}
}
}

Expand Down Expand Up @@ -806,6 +862,7 @@ class FlumeView(context: Context) : FrameLayout(context) {

override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
if (w != oldw && paddingPercent.any { it != 0f }) applyPadding()
if (adapter.onViewportChanged(w, h, resources.configuration.fontScale)) sticky.refresh(force = true)
}

Expand Down
27 changes: 27 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,33 @@ class FlumeViewManager : ViewGroupManager<FlumeView>(), FlumeViewManagerInterfac
@ReactProp(name = "contentPaddingRight")
override fun setContentPaddingRight(view: FlumeView, value: Double) = view.setContentPadding(2, value)

@ReactProp(name = "paddingPercentTop")
override fun setPaddingPercentTop(view: FlumeView, value: Double) = view.setPaddingPercent(1, value)

@ReactProp(name = "paddingPercentLeft")
override fun setPaddingPercentLeft(view: FlumeView, value: Double) = view.setPaddingPercent(0, value)

@ReactProp(name = "paddingPercentBottom")
override fun setPaddingPercentBottom(view: FlumeView, value: Double) = view.setPaddingPercent(3, value)

@ReactProp(name = "paddingPercentRight")
override fun setPaddingPercentRight(view: FlumeView, value: Double) = view.setPaddingPercent(2, value)

@ReactProp(name = "contentJustify")
override fun setContentJustify(view: FlumeView, value: String?) {
view.contentJustify = ContentJustify.of(value)
}

@ReactProp(name = "growFooter")
override fun setGrowFooter(view: FlumeView, value: Boolean) {
view.growFooter = value
}

@ReactProp(name = "contentBackgroundColor", customType = "Color")
override fun setContentBackgroundColor(view: FlumeView, value: Int?) {
view.recycler.contentBackground = value ?: 0
}

@ReactProp(name = "mainGap")
override fun setMainGap(view: FlumeView, value: Double) = view.setGap(0, value)

Expand Down
8 changes: 8 additions & 0 deletions android/src/main/java/me/sectiontn/flume/ListGeometry.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package me.sectiontn.flume

import kotlin.math.roundToInt

// A grid's lane insets and column gap.
data class Lanes(val insetStartPx: Int = 0, val insetEndPx: Int = 0, val gapPx: Int = 0)

Expand Down Expand Up @@ -60,6 +62,12 @@ class ListGeometry(private val density: Float) {

private fun bindAxisPx(widthPx: Int, heightPx: Int) = if (horizontal) heightPx else widthPx

companion object {
// Points in px plus a fraction of the list width, Yoga's base for a percent on every edge.
fun paddingPx(pointsPx: IntArray, fractions: FloatArray, widthPx: Int): IntArray =
IntArray(4) { pointsPx[it] + (fractions[it] * widthPx.coerceAtLeast(0)).roundToInt() }
}

private fun bindPadding(horizontal: Boolean, paddingPx: IntArray) =
if (horizontal) paddingPx[1] + paddingPx[3] else paddingPx[0] + paddingPx[2]
}
34 changes: 34 additions & 0 deletions android/src/test/java/me/sectiontn/flume/ContentPlacementTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package me.sectiontn.flume

import org.junit.Assert.assertEquals
import org.junit.Test

// Three rows of 100 in a viewport of 600.
class ContentPlacementTest {
@Test
fun shortContentMovesToTheCenterOnceAndStays() {
assertEquals(150, ContentPlacement.shift(ContentJustify.Center, firstStart = 0, lastEnd = 300, viewportStart = 0, viewportEnd = 600))
assertEquals(0, ContentPlacement.shift(ContentJustify.Center, firstStart = 150, lastEnd = 450, viewportStart = 0, viewportEnd = 600))
assertEquals(0, ContentPlacement.shift(ContentJustify.Center, firstStart = 0, lastEnd = 900, viewportStart = 0, viewportEnd = 600))
}

@Test
fun shortContentMovesToTheEndOnceAndStays() {
assertEquals(300, ContentPlacement.shift(ContentJustify.End, firstStart = 0, lastEnd = 300, viewportStart = 0, viewportEnd = 600))
assertEquals(0, ContentPlacement.shift(ContentJustify.End, firstStart = 300, lastEnd = 600, viewportStart = 0, viewportEnd = 600))
assertEquals(0, ContentPlacement.shift(ContentJustify.End, firstStart = 0, lastEnd = 900, viewportStart = 0, viewportEnd = 600))
}

@Test
fun justifyContentNamesMapToPlacements() {
assertEquals(ContentJustify.End, ContentJustify.of("end"))
assertEquals(ContentJustify.Center, ContentJustify.of("center"))
assertEquals(ContentJustify.Start, ContentJustify.of(null))
}

@Test
fun aGrowingFooterTakesWhatTheRowsAboveLeave() {
assertEquals(300, ContentPlacement.footerMinPx(contentStart = 0, footerStart = 300, viewportPx = 600))
assertEquals(0, ContentPlacement.footerMinPx(contentStart = 0, footerStart = 700, viewportPx = 600))
}
}
Loading