diff --git a/android/src/main/cpp/AndroidStoreListener.h b/android/src/main/cpp/AndroidStoreListener.h index d69167a..24e50fc 100644 --- a/android/src/main/cpp/AndroidStoreListener.h +++ b/android/src/main/cpp/AndroidStoreListener.h @@ -39,8 +39,9 @@ struct JFlumeStoreListener : jni::JavaClass { javaClassStatic() ->getMethod("onListChanged"); + // A separator neighbor rebinds in place like a changed row. method(self(), ops.reset, rangeArray(ops.removed).get(), rangeArray(ops.inserted).get(), pairArray(ops.moved).get(), - intArray(ops.changed).get(), count, intArray(ops.sticky).get()); + intArray(rebound(ops)).get(), count, intArray(ops.sticky).get()); } }; diff --git a/android/src/main/cpp/FlumeJni.cpp b/android/src/main/cpp/FlumeJni.cpp index f7d5cdb..97d9675 100644 --- a/android/src/main/cpp/FlumeJni.cpp +++ b/android/src/main/cpp/FlumeJni.cpp @@ -85,6 +85,12 @@ struct JFlumeJni : jni::JavaClass { return JFlumeBatch::create(batch); } + static jni::local_ref relayout(jni::alias_ref, jint storeId, jint holderId, jfloat mainDp) { + flume::OpBatch batch; + if (!flume::Engine::instance().relayout(storeId, holderId, mainDp, batch)) return nullptr; + return JFlumeBatch::create(batch); + } + static void releaseHolder(jni::alias_ref, jint storeId, jint holderId) { flume::Engine::instance().releaseHolder(storeId, holderId); } @@ -95,6 +101,14 @@ struct JFlumeJni : jni::JavaClass { static void refresh(jni::alias_ref, jint storeId) { flume::Engine::instance().refresh(storeId); } + static jboolean applyNow(jni::alias_ref, jint storeId) { + return flume::Engine::instance().applyNow(storeId) ? JNI_TRUE : JNI_FALSE; + } + + static void setRowShape(jni::alias_ref, jint storeId, jboolean horizontal, jboolean inverted, jint lanes) { + flume::Engine::instance().setRowShape(storeId, {horizontal == JNI_TRUE, inverted == JNI_TRUE, lanes}); + } + static void setStatsEnabled(jni::alias_ref, jboolean enabled) { flume::Engine::instance().setStatsEnabled(enabled); } @@ -115,9 +129,12 @@ struct JFlumeJni : jni::JavaClass { makeNativeMethod("keyAt", JFlumeJni::keyAt), makeNativeMethod("stickyIndices", JFlumeJni::stickyIndices), makeNativeMethod("bind", JFlumeJni::bind), + makeNativeMethod("relayout", JFlumeJni::relayout), makeNativeMethod("releaseHolder", JFlumeJni::releaseHolder), makeNativeMethod("invalidateMeasures", JFlumeJni::invalidateMeasures), makeNativeMethod("refresh", JFlumeJni::refresh), + makeNativeMethod("applyNow", JFlumeJni::applyNow), + makeNativeMethod("setRowShape", JFlumeJni::setRowShape), makeNativeMethod("setStatsEnabled", JFlumeJni::setStatsEnabled), }); } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt b/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt index 1e21b75..4d929f4 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt @@ -44,9 +44,18 @@ class FlumeAdapter( return changed } - // Orientation, columns and padding come from the host; a change of the cell size rebinds every row. - fun configure(horizontal: Boolean, numColumns: Int, inverted: Boolean, paddingPx: IntArray) { - if (geometry.configure(horizontal, numColumns, inverted, paddingPx)) rebindAll() + // Orientation, columns, lanes and padding come from the host. A change of the cell size rebinds every row. + fun configure(horizontal: Boolean, numColumns: Int, inverted: Boolean, paddingPx: IntArray, lanes: Lanes) { + if (!geometry.configure(horizontal, numColumns, inverted, paddingPx, lanes)) return + sendRowShape() + rebindAll() + } + + // The engine composes worklet separators with the shape the rows are laid out with. + private fun sendRowShape() { + if (storeId == 0) return + val lanes = if (geometry.horizontal) 1 else geometry.numColumns + FlumeJni.setRowShape(storeId, geometry.horizontal, geometry.inverted, lanes) } private fun rebindAll() { @@ -69,6 +78,7 @@ class FlumeAdapter( if (this.storeId != 0 && this.storeId != storeId) detach() val reload = attached.onAttach(storeId) val attachedCount = FlumeJni.attach(storeId, this, measurer, density) + sendRowShape() val sticky = FlumeJni.stickyIndices(storeId) val stickyChanged = !sticky.contentEquals(stickyIndices) stickyIndices = sticky @@ -108,6 +118,7 @@ class FlumeAdapter( val anchorLost = !reload && AnchorPolicy.losesEveryRow(laidOutDataIndices(), removed) setCount(count) ListOpsApplier.apply(reload, removed, inserted, moved, changed, this) + refreshDecorations() reindexSlots() anchor(before, inserted, count, anchorLost) onDataChanged?.invoke(reload) @@ -231,6 +242,12 @@ class FlumeAdapter( if (after.hasEmptyRow) notifyItemInserted(after.headerCount) else notifyItemRemoved(after.headerCount) } if (before.footer != after.footer) if (after.footer) notifyItemInserted(after.itemCount - 1) else notifyItemRemoved(after.itemCount) + refreshDecorations() + } + + // RecyclerView keeps a row's offsets until it rebinds, so a row that became or stopped being the last keeps a stale line or gap. + private fun refreshDecorations() { + if (recycler.itemDecorationCount > 0) recycler.invalidateItemDecorations() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { @@ -288,6 +305,7 @@ class FlumeAdapter( cell.rowsPressable = rowsPressable val start = if (BindStats.enabled) SystemClock.elapsedRealtimeNanos() else 0L val batch = FlumeJni.bind(storeId, cell.cellId, index, geometry.cellWidthDp(fullSpans.contains(position)), geometry.cellHeightDp()) ?: return + cell.storeId = storeId cell.apply(batch) batch.stats?.let { BindStats.record(SystemClock.elapsedRealtimeNanos() - start, it) } } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeCellView.kt b/android/src/main/java/me/sectiontn/flume/FlumeCellView.kt index 15d7ad2..16adf3f 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeCellView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeCellView.kt @@ -1,9 +1,12 @@ package me.sectiontn.flume import android.content.Context +import android.graphics.Canvas +import android.graphics.Outline import android.graphics.drawable.GradientDrawable import android.view.View import android.view.ViewGroup +import android.view.ViewOutlineProvider import android.view.accessibility.AccessibilityNodeInfo import android.widget.Button import kotlin.math.min @@ -27,7 +30,21 @@ class FlumeCellView(context: Context, private val measurer: FlumeTextMeasurer) : isLongClickable = value } + // The root's box, background and border: drawn in its Yoga frame, which can be smaller than the cell. + private var rootPaint: GradientDrawable? = null + init { + outlineProvider = object : ViewOutlineProvider() { + override fun getOutline(view: View, outline: Outline) { + val paint = rootPaint + if (paint != null) { + paint.getOutline(outline) + } else { + outline.setRect(0, 0, view.width, view.height) + outline.alpha = 0f + } + } + } setOnClickListener { onPress?.invoke(null, false) } setOnLongClickListener { onPress?.invoke(null, true) @@ -44,11 +61,26 @@ class FlumeCellView(context: Context, private val measurer: FlumeTextMeasurer) : val rootWidthPx: Int get() = tree.rootWidthPx val rootHeightPx: Int get() = tree.rootHeightPx + // A list's own cell, which can stretch to its grid row. The pinned copy and the measuring holder keep 0. + var storeId = 0 + private var naturalHeightPx = 0 + private var stretchedPx = 0 + + // A bind lays the root out at its own height, so the next measure stretches it again. fun apply(batch: FlumeBatch) { tree.apply(batch) + naturalHeightPx = tree.rootHeightPx + stretchedPx = 0 requestLayout() } + private fun stretchTo(targetPx: Int) { + if (storeId == 0 || targetPx == stretchedPx) return + val batch = FlumeJni.relayout(storeId, cellId, if (targetPx > 0) targetPx / density else Float.NaN) ?: return + tree.apply(batch) + stretchedPx = targetPx + } + override fun create(kind: Int): View = when (kind) { 1 -> FlumeTextView(context) 2 -> FlumeImages.create(context) @@ -81,11 +113,18 @@ class FlumeCellView(context: Context, private val measurer: FlumeTextMeasurer) : override fun viewStyle(view: View, backgroundColor: Int, borderColor: Int, opacity: Float, radiiPx: FloatArray, borderWidthPx: Float, elevationPx: Float) { val drawn = backgroundColor != 0 || borderWidthPx > 0f || radiiPx.any { it > 0f } - view.background = if (drawn) GradientDrawable().apply { + val paint = if (drawn) GradientDrawable().apply { setColor(backgroundColor) cornerRadii = floatArrayOf(radiiPx[0], radiiPx[0], radiiPx[1], radiiPx[1], radiiPx[2], radiiPx[2], radiiPx[3], radiiPx[3]) if (borderWidthPx > 0f) setStroke(borderWidthPx.roundToInt(), borderColor) } else null + if (view === this) { + rootPaint = paint + placeRootPaint() + invalidate() + } else { + view.background = paint + } view.elevation = elevationPx view.alpha = opacity (view as? FlumePressable)?.baseOpacity = opacity @@ -137,17 +176,40 @@ class FlumeCellView(context: Context, private val measurer: FlumeTextMeasurer) : return false } + // GridLayoutManager measures a row's shorter cells again at the row's height, exactly, and they stretch to it. override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { - if (horizontal) setMeasuredDimension(tree.rootWidthPx, MeasureSpec.getSize(heightMeasureSpec)) - else setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), tree.rootHeightPx) + if (horizontal) { + setMeasuredDimension(tree.rootWidthPx, MeasureSpec.getSize(heightMeasureSpec)) + return + } + val exact = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY + stretchTo(CellStretch.target(exact, MeasureSpec.getSize(heightMeasureSpec), naturalHeightPx)) + setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), if (stretchedPx > 0) stretchedPx else naturalHeightPx) } // Every descendant is placed here from its Yoga frame; FlumeGroup containers do no layout of their own. override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { + // The tallest cell of a row skips the exact pass, so its final height decides whether it stays stretched. + if (!horizontal) stretchTo(CellStretch.target(true, b - t, naturalHeightPx)) tree.frames { view, left, top, width, height -> view.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)) view.layout(left, top, left + width, top + height) } + placeRootPaint() + } + + // A grid tile with its own height or width paints that box inside a longer row or a wider column, as React Native. + private fun placeRootPaint() { + val bounds = rootPaint?.bounds + if (bounds != null && (bounds.right != tree.rootWidthPx || bounds.bottom != tree.rootHeightPx)) { + rootPaint?.setBounds(0, 0, tree.rootWidthPx, tree.rootHeightPx) + } + invalidateOutline() + } + + override fun dispatchDraw(canvas: Canvas) { + rootPaint?.draw(canvas) + super.dispatchDraw(canvas) } private object ButtonDelegate : View.AccessibilityDelegate() { @@ -157,3 +219,8 @@ class FlumeCellView(context: Context, private val measurer: FlumeTextMeasurer) : } } } + +// The length a cell's root is laid out at: a longer exact spec stretches it, anything else gives its own, as 0. +object CellStretch { + fun target(exact: Boolean, specPx: Int, naturalPx: Int): Int = if (exact && specPx > naturalPx) specPx else 0 +} diff --git a/android/src/main/java/me/sectiontn/flume/FlumeJni.kt b/android/src/main/java/me/sectiontn/flume/FlumeJni.kt index bb49b95..6c290df 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeJni.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeJni.kt @@ -33,6 +33,9 @@ object FlumeJni { // Null when the store is gone. @JvmStatic external fun bind(storeId: Int, holderId: Int, index: Int, widthDp: Float, heightDp: Float): FlumeBatch? + // The holder's bound tree laid out again at a main length in dp, NaN for its own, with no worklet call. + @JvmStatic external fun relayout(storeId: Int, holderId: Int, mainDp: Float): FlumeBatch? + @JvmStatic external fun releaseHolder(storeId: Int, holderId: Int) // Drops the measure cache so the next binds measure at the current width and font scale. @@ -41,6 +44,12 @@ object FlumeJni { // Applies data JS deferred until its pre-rendered cells mounted. @JvmStatic external fun refresh(storeId: Int) + // UI thread: applies deferred data now, in the frame of the mount that brought its cells. False when none was pending. + @JvmStatic external fun applyNow(storeId: Int): Boolean + + // UI thread: the shape the rows are laid out with, before any bind that uses it. + @JvmStatic external fun setRowShape(storeId: Int, horizontal: Boolean, inverted: Boolean, lanes: Int) + // Binds read the clock and return stats only while this is on. @JvmStatic external fun setStatsEnabled(enabled: Boolean) } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt b/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt index a569066..2b40c2a 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeLayoutManagers.kt @@ -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) @@ -37,10 +43,18 @@ 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 { spanSizeLookup = fullSpanLookup + // A stretched cell keeps its row's height as its measure, so a row that lost its tallest cell must measure again. + isMeasurementCacheEnabled = false } override fun calculateExtraLayoutSpace(state: RecyclerView.State, extraLayoutSpace: IntArray) = @@ -119,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)) +} diff --git a/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt b/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt index 344458a..1342b4f 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt @@ -1,6 +1,9 @@ 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 @@ -8,6 +11,7 @@ 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 @@ -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 + 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 { @@ -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) +} diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 3bd9413..911c264 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -14,10 +14,14 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.facebook.react.bridge.ReactContext +import com.facebook.react.bridge.UIManager +import com.facebook.react.bridge.UIManagerListener +import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.uimanager.StateWrapper import com.facebook.react.uimanager.UIManagerHelper import com.facebook.react.uimanager.events.Event import com.facebook.react.uimanager.events.NativeGestureUtil +import com.facebook.react.uimanager.common.UIManagerType import kotlin.math.roundToInt class FlumeView(context: Context) : FrameLayout(context) { @@ -39,8 +43,11 @@ 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) + private var gaps: GapDecoration? = null private val sticky = StickyHeaderHost( this, FlumeCellView(context, measurer), @@ -190,6 +197,8 @@ class FlumeView(context: Context) : FrameLayout(context) { recycler.adapter = adapter recycler.itemAnimator = animator recycler.clipToPadding = false + // A row composed with its separator draws its shadow from a child view, which a clipping cell would cut. + recycler.clipChildren = false adapter.onPress = { position, pressId, long -> val index = rows.dataIndex(position) if (index >= 0) emitPress(index, FlumeJni.keyAt(storeId, index), pressId, long) @@ -311,6 +320,7 @@ class FlumeView(context: Context) : FrameLayout(context) { } sticky.refresh() updateEmptyLength() + updateFooterLength() evaluateViewability() evaluateEdges() requestOrigins() @@ -535,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 @@ -637,11 +681,40 @@ 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) + 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) + } + + // Kinds are 0 main, 1 grid row, 2 column, 3 lane inset start and 4 lane inset end, in dp. + fun setGap(kind: Int, dp: Double) { + val px = (dp.coerceAtLeast(0.0) * density).roundToInt() + if (gapsPx[kind] == px) return + gapsPx[kind] = px + 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 + recycler.invalidateItemDecorations() sticky.refresh(force = true) } + private fun lanes() = Lanes(insetStartPx = gapsPx[3], insetEndPx = gapsPx[4], gapPx = gapsPx[2]) + // A grid only reverses; stackFromEnd is unsupported there, so an inverted grid with little content starts at the top. private fun rebuildLayoutManager() { val next = LayoutShape.of(horizontal, numColumns, inverted, anchorConfig.startRenderingFromBottom) @@ -658,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) + 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 + } } } @@ -783,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) } @@ -792,6 +872,7 @@ class FlumeView(context: Context) : FrameLayout(context) { } override fun onDetachedFromWindow() { + dropMountListener() adapter.detach() super.onDetachedFromWindow() } @@ -805,11 +886,37 @@ class FlumeView(context: Context) : FrameLayout(context) { } private val dataRefresh = Runnable { if (storeId != 0) FlumeJni.refresh(storeId) } + @OptIn(UnstableReactNativeAPI::class) private var mountListener: UIManagerListener? = null - // Data JS deferred for its pre-rendered cells applies after the mount batch that registers them, once they measured. + // Data JS deferred for its pre-rendered cells applies right after the mount batch that registers them, in the frame + // that shows the rows it re-rendered with them. The post only covers a batch Fabric never reports. + @OptIn(UnstableReactNativeAPI::class) fun refreshData() { removeCallbacks(dataRefresh) post(dataRefresh) + if (mountListener != null) return + val uiManager = UIManagerHelper.getUIManager(context as ReactContext, UIManagerType.FABRIC) ?: return + val listener = object : UIManagerListener { + override fun willDispatchViewUpdates(uiManager: UIManager) = Unit + override fun willMountItems(uiManager: UIManager) = Unit + override fun didDispatchMountItems(uiManager: UIManager) = Unit + override fun didScheduleMountItems(uiManager: UIManager) = Unit + // A batch that lands before the deferred data keeps the listener and the posted fallback. + override fun didMountItems(uiManager: UIManager) { + if (storeId == 0 || !FlumeJni.applyNow(storeId)) return + dropMountListener() + removeCallbacks(dataRefresh) + } + } + mountListener = listener + uiManager.addUIManagerEventListener(listener) + } + + @OptIn(UnstableReactNativeAPI::class) + private fun dropMountListener() { + val listener = mountListener ?: return + mountListener = null + UIManagerHelper.getUIManager(context as ReactContext, UIManagerType.FABRIC)?.removeUIManagerEventListener(listener) } fun setEstimatedItemSize(dp: Double) { diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index ddaf121..2a2a302 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -97,6 +97,48 @@ class FlumeViewManager : ViewGroupManager(), 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) + + @ReactProp(name = "gridRowGap") + override fun setGridRowGap(view: FlumeView, value: Double) = view.setGap(1, value) + + @ReactProp(name = "crossGap") + override fun setCrossGap(view: FlumeView, value: Double) = view.setGap(2, value) + + @ReactProp(name = "laneInsetStart") + override fun setLaneInsetStart(view: FlumeView, value: Double) = view.setGap(3, value) + + @ReactProp(name = "laneInsetEnd") + override fun setLaneInsetEnd(view: FlumeView, value: Double) = view.setGap(4, value) + @ReactProp(name = "drawDistance", defaultDouble = -1.0) override fun setDrawDistance(view: FlumeView, value: Double) { view.drawDistanceDp = value diff --git a/android/src/main/java/me/sectiontn/flume/ListGeometry.kt b/android/src/main/java/me/sectiontn/flume/ListGeometry.kt index e7fd2a3..1083eb3 100644 --- a/android/src/main/java/me/sectiontn/flume/ListGeometry.kt +++ b/android/src/main/java/me/sectiontn/flume/ListGeometry.kt @@ -1,5 +1,10 @@ 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) + // Orientation, columns, padding, viewport and font scale of one list; cells bind at the size computed here. class ListGeometry(private val density: Float) { var horizontal = false @@ -8,6 +13,8 @@ class ListGeometry(private val density: Float) { private set var inverted = false private set + var lanes = Lanes() + private set var paddingPx = IntArray(4) private set var widthPx = 0 @@ -32,24 +39,35 @@ class ListGeometry(private val density: Float) { return changed } - // True when cells must rebind: the orientation, the columns or the padding along the bind axis changed. - fun configure(horizontal: Boolean, numColumns: Int, inverted: Boolean, paddingPx: IntArray): Boolean { - val changed = horizontal != this.horizontal || numColumns != this.numColumns || + // True when cells must rebind: the orientation, the columns, the lanes or the padding along the bind axis changed. + fun configure(horizontal: Boolean, numColumns: Int, inverted: Boolean, paddingPx: IntArray, lanes: Lanes = Lanes()): Boolean { + val changed = horizontal != this.horizontal || numColumns != this.numColumns || lanes != this.lanes || bindPadding(horizontal, paddingPx) != bindPadding(this.horizontal, this.paddingPx) this.horizontal = horizontal this.numColumns = numColumns this.inverted = inverted this.paddingPx = paddingPx.copyOf() + this.lanes = lanes return changed } - fun cellWidthDp(fullSpan: Boolean): Float = - if (horizontal) Float.NaN else innerWidthPx / (if (fullSpan) 1f else numColumns.toFloat()) / density + // A data row's width: inside the lane insets, a grid column also leaves the gaps between columns. + fun cellWidthDp(fullSpan: Boolean): Float { + if (horizontal) return Float.NaN + val row = (innerWidthPx - lanes.insetStartPx - lanes.insetEndPx).toFloat() + return (if (fullSpan) row else (row - lanes.gapPx * (numColumns - 1)) / numColumns) / density + } fun cellHeightDp(): Float = if (horizontal) innerHeightPx / density else Float.NaN 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] } diff --git a/android/src/main/java/me/sectiontn/flume/Separators.kt b/android/src/main/java/me/sectiontn/flume/Separators.kt index e12caac..42a879a 100644 --- a/android/src/main/java/me/sectiontn/flume/Separators.kt +++ b/android/src/main/java/me/sectiontn/flume/Separators.kt @@ -10,6 +10,7 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlin.math.max import kotlin.math.min +import kotlin.math.roundToInt enum class Edge { TOP, BOTTOM, LEFT, RIGHT } @@ -25,6 +26,74 @@ object SeparatorGeometry { if (rows.kind(position) != RowKind.DATA) return null return edge(rowOf(position), rowOf(rows.position(rows.dataCount - 1)), horizontal, inverted) } + + // Left, top, right and bottom: next to the row on its edge, across the decorated cell inside the clip. + fun line(edge: Edge, child: IntArray, decorated: IntArray, sizePx: Int, clipStart: Int, clipEnd: Int, out: IntArray = IntArray(4)): IntArray { + when (edge) { + Edge.BOTTOM, Edge.TOP -> { + out[0] = max(decorated[0], clipStart) + out[2] = min(decorated[2], clipEnd) + out[1] = if (edge == Edge.BOTTOM) child[3] else child[1] - sizePx + out[3] = out[1] + sizePx + } + Edge.RIGHT, Edge.LEFT -> { + out[1] = max(decorated[1], clipStart) + out[3] = min(decorated[3], clipEnd) + out[0] = if (edge == Edge.RIGHT) child[2] else child[0] - sizePx + out[2] = out[0] + sizePx + } + } + return out + } +} + +// Along the scroll axis a row's line comes first, then its gaps. +object GapGeometry { + fun after(row: Int, lastRow: Int, dataGap: Boolean, mainGapPx: Int, gridRowGapPx: Int): Int = + (if (row < lastRow) mainGapPx else 0) + (if (dataGap) gridRowGapPx else 0) + + // Left and right offsets that put lane k at insetStart + k * (width + gap) in its equal share of the inner width. + fun laneOffsets(lane: Int, lanes: Int, innerPx: Int, insetStartPx: Int, insetEndPx: Int, gapPx: Int): IntArray { + val share = innerPx.toFloat() / lanes + val width = (innerPx - insetStartPx - insetEndPx - gapPx * (lanes - 1)).toFloat() / lanes + val sum = (share - width).roundToInt() + val left = (insetStartPx + lane * (width + gapPx) - lane * share).roundToInt() + return intArrayOf(left, sum - left) + } +} + +// Spaces rows after their line and places a grid's columns inside the lane insets. gapsPx is main, grid row, column, inset start, inset end. +class GapDecoration(private val gapsPx: IntArray, private val rows: () -> ListRows) : RecyclerView.ItemDecoration() { + override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { + outRect.setEmpty() + val lm = parent.layoutManager as? LinearLayoutManager ?: return + val position = parent.getChildAdapterPosition(view) + val rows = rows() + if (position == RecyclerView.NO_POSITION || rows.itemCount == 0) return + val grid = lm as? GridLayoutManager + val rowOf: (Int) -> Int = if (grid != null) { p -> grid.spanSizeLookup.getSpanGroupIndex(p, grid.spanCount) } else { p -> p } + val horizontal = lm.orientation == RecyclerView.HORIZONTAL + val inverted = lm.reverseLayout + val dataGap = SeparatorGeometry.edgeAt(position, rows, rowOf, horizontal, inverted) != null + val main = GapGeometry.after(rowOf(position), rowOf(rows.itemCount - 1), dataGap, gapsPx[0], gapsPx[1]) + when { + horizontal && inverted -> outRect.left = main + horizontal -> outRect.right = main + inverted -> outRect.top = main + else -> outRect.bottom = main + } + if (grid == null || horizontal || rows.kind(position) != RowKind.DATA) return + if (grid.spanSizeLookup.getSpanSize(position) >= grid.spanCount) { + outRect.left = gapsPx[3] + outRect.right = gapsPx[4] + return + } + val lane = grid.spanSizeLookup.getSpanIndex(position, grid.spanCount) + val inner = parent.width - parent.paddingLeft - parent.paddingRight + val offsets = GapGeometry.laneOffsets(lane, grid.spanCount, inner, gapsPx[3], gapsPx[4], gapsPx[2]) + outRect.left = offsets[0] + outRect.right = offsets[1] + } } // Reserves the gap through item offsets and paints it, inset along the cross axis from the padded edges. @@ -58,28 +127,32 @@ class SeparatorDecoration( return SeparatorGeometry.edgeAt(position, rows(), rowOf, lm.orientation == RecyclerView.HORIZONTAL, lm.reverseLayout) } + private val childBounds = IntArray(4) + private val decoratedBounds = IntArray(4) + private val lineBounds = IntArray(4) + + // The decorated cell spans its column's gaps and the lane insets, so a grid row's line runs unbroken. override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { if (transparent) return val lm = parent.layoutManager ?: return for (i in 0 until parent.childCount) { val child = parent.getChildAt(i) val edge = edgeFor(child, parent, state) ?: continue + childBounds[0] = child.left + childBounds[1] = child.top + childBounds[2] = child.right + childBounds[3] = child.bottom + decoratedBounds[0] = lm.getDecoratedLeft(child) + decoratedBounds[1] = lm.getDecoratedTop(child) + decoratedBounds[2] = lm.getDecoratedRight(child) + decoratedBounds[3] = lm.getDecoratedBottom(child) + val across = edge == Edge.BOTTOM || edge == Edge.TOP + val clipStart = (if (across) parent.paddingLeft else parent.paddingTop) + insetStartPx + val clipEnd = (if (across) parent.width - parent.paddingRight else parent.height - parent.paddingBottom) - insetEndPx + val line = SeparatorGeometry.line(edge, childBounds, decoratedBounds, sizePx, clipStart, clipEnd, lineBounds) val tx = child.translationX val ty = child.translationY - when (edge) { - Edge.BOTTOM, Edge.TOP -> { - val left = max(child.left, parent.paddingLeft + insetStartPx) + tx - val right = min(child.right, parent.width - parent.paddingRight - insetEndPx) + tx - if (edge == Edge.BOTTOM) canvas.drawRect(left, child.bottom + ty, right, lm.getDecoratedBottom(child) + ty, paint) - else canvas.drawRect(left, lm.getDecoratedTop(child) + ty, right, child.top + ty, paint) - } - Edge.RIGHT, Edge.LEFT -> { - val top = max(child.top, parent.paddingTop + insetStartPx) + ty - val bottom = min(child.bottom, parent.height - parent.paddingBottom - insetEndPx) + ty - if (edge == Edge.RIGHT) canvas.drawRect(child.right + tx, top, lm.getDecoratedRight(child) + tx, bottom, paint) - else canvas.drawRect(lm.getDecoratedLeft(child) + tx, top, child.left + tx, bottom, paint) - } - } + canvas.drawRect(line[0] + tx, line[1] + ty, line[2] + tx, line[3] + ty, paint) } } } diff --git a/android/src/main/java/me/sectiontn/flume/StickyHeaders.kt b/android/src/main/java/me/sectiontn/flume/StickyHeaders.kt index 8edf073..6781814 100644 --- a/android/src/main/java/me/sectiontn/flume/StickyHeaders.kt +++ b/android/src/main/java/me/sectiontn/flume/StickyHeaders.kt @@ -190,16 +190,21 @@ class StickyHeaderHost( val recycler = view.recycler val geometry = view.geometry pinnedView.forceLayout() - val widthSpec = if (horizontal) View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) else View.MeasureSpec.makeMeasureSpec(geometry.innerWidthPx, View.MeasureSpec.EXACTLY) + val laneWidthPx = geometry.innerWidthPx - geometry.lanes.insetStartPx - geometry.lanes.insetEndPx + val widthSpec = if (horizontal) View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) else View.MeasureSpec.makeMeasureSpec(laneWidthPx, View.MeasureSpec.EXACTLY) val heightSpec = if (horizontal) View.MeasureSpec.makeMeasureSpec(geometry.innerHeightPx, View.MeasureSpec.EXACTLY) else View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) pinnedView.measure(widthSpec, heightSpec) val (left, top) = margins(horizontal) pinnedView.layout(left, top, left + pinnedView.measuredWidth, top + pinnedView.measuredHeight) } + // A sticky row is a data row, so it keeps a grid's lane insets. private fun margins(horizontal: Boolean): IntArray { val recycler = view.recycler - return StickyPlacement.margins(horizontal, recycler.paddingLeft, recycler.paddingTop, recycler.paddingRight, recycler.paddingBottom) + val lanes = view.geometry.lanes + return StickyPlacement.margins( + horizontal, recycler.paddingLeft + lanes.insetStartPx, recycler.paddingTop, recycler.paddingRight + lanes.insetEndPx, recycler.paddingBottom, + ) } // A copy sits at the viewport's leading edge, inside the content padding across the scroll axis, full width or full height. diff --git a/android/src/test/java/me/sectiontn/flume/CellStretchTest.kt b/android/src/test/java/me/sectiontn/flume/CellStretchTest.kt new file mode 100644 index 0000000..a4cfbfe --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/CellStretchTest.kt @@ -0,0 +1,17 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertEquals +import org.junit.Test + +class CellStretchTest { + // GridLayoutManager measures the shorter cells of a row of 100, 150 and 120 again at 150, exactly. + @Test + fun aShorterCellStretchesToTheRowOnAnExactSpec() { + assertEquals(listOf(150, 0, 150), listOf(100, 150, 120).map { CellStretch.target(exact = true, specPx = 150, naturalPx = it) }) + } + + @Test + fun aStretchedCellStillReportsItsOwnLengthToAFreeMeasure() { + assertEquals(0, CellStretch.target(exact = false, specPx = 150, naturalPx = 100)) + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ContentPlacementTest.kt b/android/src/test/java/me/sectiontn/flume/ContentPlacementTest.kt new file mode 100644 index 0000000..4d79b1a --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/ContentPlacementTest.kt @@ -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)) + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ListGeometryTest.kt b/android/src/test/java/me/sectiontn/flume/ListGeometryTest.kt index 6affdf5..0829ce5 100644 --- a/android/src/test/java/me/sectiontn/flume/ListGeometryTest.kt +++ b/android/src/test/java/me/sectiontn/flume/ListGeometryTest.kt @@ -1,5 +1,6 @@ package me.sectiontn.flume +import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue @@ -55,4 +56,34 @@ class ListGeometryTest { assertFalse(g.configure(horizontal = false, numColumns = 2, inverted = false, paddingPx = IntArray(4))) assertTrue(g.update(1080, 500, 1.3f)) } + + @Test + fun gridCellsLeaveTheLaneInsetsAndTheColumnGaps() { + val g = ListGeometry(1f).apply { update(300, 500, 1f) } + g.configure(horizontal = false, numColumns = 3, inverted = false, paddingPx = IntArray(4), lanes = Lanes(insetStartPx = 16, insetEndPx = 16, gapPx = 8)) + assertEquals(84f, g.cellWidthDp(fullSpan = false), 0f) + assertEquals(268f, g.cellWidthDp(fullSpan = true), 0f) + } + + @Test + fun aLaneChangeRebinds() { + val g = geometry() + val lanes = Lanes(insetStartPx = 16, insetEndPx = 16, gapPx = 8) + assertTrue(g.configure(horizontal = false, numColumns = 3, inverted = false, paddingPx = IntArray(4), lanes = lanes)) + assertFalse(g.configure(horizontal = false, numColumns = 3, inverted = false, paddingPx = IntArray(4), lanes = lanes.copy())) + assertTrue(g.configure(horizontal = false, numColumns = 3, inverted = false, paddingPx = IntArray(4), lanes = lanes.copy(gapPx = 4))) + } + + @Test + fun percentPaddingResolvesAgainstTheListWidthOnEveryEdge() { + assertArrayEquals(intArrayOf(20, 20, 20, 20), ListGeometry.paddingPx(IntArray(4), FloatArray(4) { 0.05f }, widthPx = 400)) + assertArrayEquals(intArrayOf(12, 20, 0, 0), ListGeometry.paddingPx(intArrayOf(12, 0, 0, 0), floatArrayOf(0f, 0.05f, 0f, 0f), widthPx = 400)) + } + + // Three rows of 50 inside padding of 10 and 20, laid out from the top of the view. + @Test + fun theBackgroundSpansTheLaidOutContentAndItsPadding() { + assertArrayEquals(intArrayOf(0, 180), ContentBackground.span(firstStart = 10, lastEnd = 160, hasFirst = true, hasLast = true, paddingStart = 10, paddingEnd = 20, viewLength = 1000)) + assertArrayEquals(intArrayOf(0, 1000), ContentBackground.span(firstStart = -40, lastEnd = 1200, hasFirst = false, hasLast = false, paddingStart = 10, paddingEnd = 20, viewLength = 1000)) + } } diff --git a/android/src/test/java/me/sectiontn/flume/SeparatorGeometryTest.kt b/android/src/test/java/me/sectiontn/flume/SeparatorGeometryTest.kt index 4945376..70b38b9 100644 --- a/android/src/test/java/me/sectiontn/flume/SeparatorGeometryTest.kt +++ b/android/src/test/java/me/sectiontn/flume/SeparatorGeometryTest.kt @@ -1,5 +1,6 @@ package me.sectiontn.flume +import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test @@ -23,4 +24,44 @@ class SeparatorGeometryTest { (0 until 5).map { SeparatorGeometry.edgeAt(it, rows, { p -> p }, horizontal = false, inverted = false) }, ) } + + // 300 px across three columns, 16 in from each side, 8 between columns: 84 wide at 16, 108 and 200. + @Test + fun gridColumnsSitInsideTheLaneInsetsWithTheirGaps() { + assertArrayEquals(intArrayOf(16, 0), GapGeometry.laneOffsets(lane = 0, lanes = 3, innerPx = 300, insetStartPx = 16, insetEndPx = 16, gapPx = 8)) + assertArrayEquals(intArrayOf(8, 8), GapGeometry.laneOffsets(lane = 1, lanes = 3, innerPx = 300, insetStartPx = 16, insetEndPx = 16, gapPx = 8)) + assertArrayEquals(intArrayOf(0, 16), GapGeometry.laneOffsets(lane = 2, lanes = 3, innerPx = 300, insetStartPx = 16, insetEndPx = 16, gapPx = 8)) + } + + @Test + fun everyColumnLeavesTheSameWidthWhenThePixelsDoNotDivide() { + val sums = (0 until 3).map { GapGeometry.laneOffsets(it, 3, 301, 15, 15, 7).sum() } + assertEquals(1, sums.distinct().size) + } + + // A header, three rows and a footer. + @Test + fun theMainGapFollowsEveryRowButTheLastOneHeaderAndFooterIncluded() { + assertEquals( + listOf(8, 8, 8, 8, 0), + (0..4).map { GapGeometry.after(row = it, lastRow = 4, dataGap = it in 1..2, mainGapPx = 8, gridRowGapPx = 0) }, + ) + } + + @Test + fun gridRowsAddTheGridRowGapWhereTheyCarryALine() { + assertEquals(12, GapGeometry.after(row = 0, lastRow = 2, dataGap = true, mainGapPx = 0, gridRowGapPx = 12)) + assertEquals(0, GapGeometry.after(row = 1, lastRow = 2, dataGap = false, mainGapPx = 0, gridRowGapPx = 12)) + } + + // The line touches its row and the gap sits beyond it. Across the axis it spans the decorated cell inside the clip. + @Test + fun theLineSitsNextToItsRowNotAcrossTheGap() { + val child = intArrayOf(16, 0, 100, 50) + val decorated = intArrayOf(0, 0, 100, 59) + assertArrayEquals(intArrayOf(0, 50, 100, 51), SeparatorGeometry.line(Edge.BOTTOM, child, decorated, sizePx = 1, clipStart = 0, clipEnd = 300)) + assertArrayEquals(intArrayOf(10, -1, 100, 0), SeparatorGeometry.line(Edge.TOP, child, decorated, sizePx = 1, clipStart = 10, clipEnd = 300)) + assertArrayEquals(intArrayOf(100, 0, 101, 40), SeparatorGeometry.line(Edge.RIGHT, child, decorated, sizePx = 1, clipStart = 0, clipEnd = 40)) + assertArrayEquals(intArrayOf(15, 0, 16, 59), SeparatorGeometry.line(Edge.LEFT, child, decorated, sizePx = 1, clipStart = 0, clipEnd = 300)) + } } diff --git a/cpp/adapter/BatchUpdates.cpp b/cpp/adapter/BatchUpdates.cpp index 4b11ce7..f76bb93 100644 --- a/cpp/adapter/BatchUpdates.cpp +++ b/cpp/adapter/BatchUpdates.cpp @@ -41,7 +41,7 @@ BatchUpdates toBatchUpdates(const ListOps& ops, int previousCount) { } } std::sort(batch.deletes.begin(), batch.deletes.end()); - batch.reconfigures = ops.changed; + batch.reconfigures = rebound(ops); return batch; } diff --git a/cpp/adapter/ListLayout.cpp b/cpp/adapter/ListLayout.cpp index f32d0f4..59c584b 100644 --- a/cpp/adapter/ListLayout.cpp +++ b/cpp/adapter/ListLayout.cpp @@ -79,7 +79,10 @@ std::vector ListLayout::apply(const ListOps& ops, int count, const TypeOf& LengthChange ListLayout::setLength(int index, float length, int anchor, float viewportLength) { if (index < 0 || index >= count()) return LengthChange{0, 0}; const bool hasAnchor = anchor >= 0 && anchor < count(); - const float before = hasAnchor ? anchorEdge(rowOf_[anchor], viewportLength) : 0; + // Justified short content moves with its slack, which the offset must not chase. Stacking from the end wins. + const bool recenters = justified() && !config_.stackFromEnd; + const auto edge = [&] { return anchorEdge(rowOf_[anchor], viewportLength) - (recenters ? slack(viewportLength) : 0); }; + const float before = hasAnchor ? edge() : 0; const float contentBefore = contentLength(viewportLength); Item& item = items_[index]; Mean& mean = means_[item.type]; @@ -92,7 +95,7 @@ LengthChange ListLayout::setLength(int index, float length, int anchor, float vi item.length = length; item.measured = true; updateRow(rowOf_[index]); - const float moved = hasAnchor ? anchorEdge(rowOf_[anchor], viewportLength) - before : 0; + const float moved = hasAnchor ? edge() - before : 0; return LengthChange{moved, contentLength(viewportLength) - contentBefore}; } @@ -117,16 +120,26 @@ float ListLayout::estimate(int type) const { float ListLayout::contentLength(float viewportLength) const { const float length = config_.paddingStart + rowStart(static_cast(rows_.size())) + config_.paddingEnd; - return bottomAnchored() ? std::max(viewportLength, length) : length; + return bottomAnchored() || justified() ? std::max(viewportLength, length) : length; +} + +std::pair ListLayout::contentSpan(float viewportLength) const { + const float length = config_.paddingStart + rowStart(static_cast(rows_.size())) + config_.paddingEnd; + if (!config_.inverted) return {slack(viewportLength), slack(viewportLength) + length}; + const float end = contentLength(viewportLength); + return {end - length, end}; } float ListLayout::crossLength(int index, float listCrossLength) const { if (!fullSpan(index)) return laneLength(listCrossLength); - return std::max(0.f, listCrossLength - config_.paddingCrossStart - config_.paddingCrossEnd); + const float insets = isData(index) ? config_.laneInsetStart + config_.laneInsetEnd : 0; + return std::max(0.f, listCrossLength - config_.paddingCrossStart - config_.paddingCrossEnd - insets); } float ListLayout::laneLength(float listCrossLength) const { - return std::max(0.f, listCrossLength - config_.paddingCrossStart - config_.paddingCrossEnd) / config_.lanes; + const float row = listCrossLength - config_.paddingCrossStart - config_.paddingCrossEnd - config_.laneInsetStart - + config_.laneInsetEnd - config_.crossGap * static_cast(config_.lanes - 1); + return std::max(0.f, row) / config_.lanes; } ItemRect ListLayout::rectOf(int index, float listCrossLength, float viewportLength) const { @@ -134,8 +147,10 @@ ItemRect ListLayout::rectOf(int index, float listCrossLength, float viewportLeng const int row = rowOf_[index]; const float main = startOf(row, viewportLength); const float cross = crossLength(index, listCrossLength); - const float crossAt = config_.paddingCrossStart + cross * static_cast(index - rows_[row].first); - const float length = items_[index].length; + const float lane = static_cast(index - rows_[row].first); + const float crossAt = + config_.paddingCrossStart + (isData(index) ? config_.laneInsetStart : 0) + (cross + config_.crossGap) * lane; + const float length = rows_[row].length; // a grid row's cells all take its longest if (config_.horizontal) return ItemRect{main, crossAt, length, cross}; return ItemRect{crossAt, main, cross, length}; } @@ -173,8 +188,8 @@ std::vector ListLayout::itemsIn(float start, float end, float viewportLengt const int b = rowAt(end, viewportLength); for (int row = std::min(a, b); row <= std::max(a, b); row++) { // An inverted row's separator sits above it; either way a row whose separator shows is listed. - const float rowFrom = startOf(row, viewportLength) - (config_.inverted ? stride(row) - rows_[row].length : 0); - if (rowFrom >= end || rowFrom + stride(row) <= start) continue; + const float rowFrom = startOf(row, viewportLength) - (config_.inverted ? rowStride(row) - rows_[row].length : 0); + if (rowFrom >= end || rowFrom + rowStride(row) <= start) continue; for (int i = 0; i < rows_[row].count; i++) out.push_back(rows_[row].first + i); } return out; @@ -196,7 +211,11 @@ std::optional ListLayout::pinned(const std::vector& sticky, float v if (config_.inverted ? s < *index && (!pusher || s > *pusher) : s > *index && (!pusher || s < *pusher)) pusher = s; } float start = viewportStart; - if (pusher) start = std::min(start, startOf(rowOf_[*pusher], viewportLength) - items_[*index].length); + if (pusher) { + // The pinned row ends at the pusher with the line between them, which is its own upright and the pusher's inverted. + const float line = lineAfter(rowOf_[config_.inverted ? *pusher : *index]); + start = std::min(start, startOf(rowOf_[*pusher], viewportLength) - line - items_[*index].length); + } return Pinned{*index, start}; } @@ -206,21 +225,30 @@ std::optional ListLayout::separatorRect(int index, float listCrossLeng if (!gapAfter(row)) return std::nullopt; const ItemRect item = rectOf(index, listCrossLength, 0); const float crossAt = config_.horizontal ? item.y : item.x; - const float cross = config_.horizontal ? item.height : item.width; - const float from = std::max(0.f, config_.paddingCrossStart + config_.separatorInsetStart - crossAt); - const float to = std::min(cross, listCrossLength - config_.paddingCrossEnd - config_.separatorInsetEnd - crossAt); + // Each cell draws its share of the padded width, so the row's line runs across the column gaps and lane insets. + const float padded = std::max(0.f, listCrossLength - config_.paddingCrossStart - config_.paddingCrossEnd); + const bool alone = fullSpan(index); + const float slot = alone ? padded : padded / config_.lanes; + const float slotAt = config_.paddingCrossStart + slot * static_cast(alone ? 0 : index - rows_[row].first); + const float from = std::max(slotAt, config_.paddingCrossStart + config_.separatorInsetStart) - crossAt; + const float to = + std::min(slotAt + slot, listCrossLength - config_.paddingCrossEnd - config_.separatorInsetEnd) - crossAt; if (to <= from) return std::nullopt; const float main = config_.inverted ? -config_.separator : rows_[row].length; if (config_.horizontal) return ItemRect{main, from, config_.separator, to - from}; return ItemRect{from, main, to - from, config_.separator}; } -float ListLayout::emptyMinLength(float viewportLength) const { - if (config_.emptyIndex < 0 || config_.emptyIndex >= count()) return 0; - float used = config_.paddingStart + config_.paddingEnd; - for (int row = 0; row < static_cast(rows_.size()); row++) { - if (row != rowOf_[config_.emptyIndex]) used += stride(row); - } +float ListLayout::emptyMinLength(float viewportLength) const { return minLengthOf(config_.emptyIndex, viewportLength); } + +float ListLayout::growMinLength(float viewportLength) const { + return config_.growFooter && config_.afterData > 0 ? minLengthOf(count() - 1, viewportLength) : 0; +} + +float ListLayout::minLengthOf(int index, float viewportLength) const { + if (index < 0 || index >= count()) return 0; + const float used = config_.paddingStart + config_.paddingEnd + rowStart(static_cast(rows_.size())) - + rows_[rowOf_[index]].length; return std::max(0.f, viewportLength - used); } @@ -259,17 +287,29 @@ bool ListLayout::gapAfter(int row) const { return rows_[row].first >= config_.dataStart && rows_[row].first + rows_[row].count < count() - config_.afterData; } -float ListLayout::stride(int row) const { return rows_[row].length + (gapAfter(row) ? config_.separator : 0); } +bool ListLayout::isData(int index) const { + return index >= config_.dataStart && index < count() - config_.afterData && index != config_.emptyIndex; +} + +float ListLayout::lineAfter(int row) const { return gapAfter(row) ? config_.separator : 0; } + +// Along the scroll axis: the row, its line, the grid row gap, then the main gap before the next row. +float ListLayout::rowStride(int row) const { + const float data = gapAfter(row) ? config_.separator + config_.gridRowGap : 0; + const float main = row + 1 < static_cast(rows_.size()) ? config_.mainGap : 0; + return rows_[row].length + data + main; +} float ListLayout::rowStart(int row) const { - for (; dirtyFrom_ < row; dirtyFrom_++) starts_[dirtyFrom_ + 1] = starts_[dirtyFrom_] + stride(dirtyFrom_); + for (; dirtyFrom_ < row; dirtyFrom_++) starts_[dirtyFrom_ + 1] = starts_[dirtyFrom_] + rowStride(dirtyFrom_); return starts_[row]; } float ListLayout::slack(float viewportLength) const { - if (!config_.stackFromEnd) return 0; + if (!config_.stackFromEnd && !justified()) return 0; const float length = config_.paddingStart + rowStart(static_cast(rows_.size())) + config_.paddingEnd; - return std::max(0.f, viewportLength - length); + const float free = std::max(0.f, viewportLength - length); + return config_.stackFromEnd || config_.justify == ListLayoutConfig::Justify::End ? free : free / 2; } float ListLayout::startOf(int row, float viewportLength) const { diff --git a/cpp/adapter/ListLayout.h b/cpp/adapter/ListLayout.h index 4feb31f..d376c57 100644 --- a/cpp/adapter/ListLayout.h +++ b/cpp/adapter/ListLayout.h @@ -1,8 +1,10 @@ #pragma once +#include #include #include #include +#include #include #include "core/KeyDiff.h" @@ -18,13 +20,26 @@ struct ListLayoutConfig { float estimatedItemLength = -1; // estimatedItemSize; negative for the per-type mean float estimateFloor = 50; float separator = 0; // the gap after every data row but the last, along the scroll axis + float mainGap = 0; // after every row but the last, after the separator, the header and footer included + float gridRowGap = 0; // after the separator of every data row but the last + float crossGap = 0; // between the lanes of a grid row + float laneInsetStart = 0, laneInsetEnd = 0; // a data row's cross insets, inside the cross padding int dataStart = 0, afterData = 0; // the items before and after the data rows: the header and the footer int emptyIndex = -1; // the empty row, -1 for none float separatorInsetStart = 0, separatorInsetEnd = 0; // across the scroll axis, from the padded edges // startRenderingFromBottom on an upright list; short content sits at the end, sizes keep the last row in view. bool stackFromEnd = false; + // contentContainerStyle flexGrow with justifyContent: short upright content sits in the middle or at the end. + enum class Justify : uint8_t { Start, Center, End }; + Justify justify = Justify::Start; + bool growFooter = false; // the footer takes what the other rows leave of the viewport }; +// Percent padding is a fraction of the list width on every edge, as Yoga resolves it. +inline float paddingOf(float points, float fraction, float listWidth) { + return points + fraction * std::max(0.f, listWidth); +} + struct ItemRect { float x, y, width, height; bool operator==(const ItemRect&) const = default; @@ -62,10 +77,14 @@ class ListLayout { int rowCount() const { return static_cast(rows_.size()); } int rowOf(int index) const { return rowOf_[index]; } float rowLength(int row) const { return rows_[row].length; } + float rowStride(int row) const; // the row's length with the separator and the gaps after it + float itemLength(int index) const { return items_[index].length; } // its own, measured or estimated IndexRange itemsOfRows(int firstRow, int lastRow) const; bool measured(int index) const; float estimate(int type) const; float contentLength(float viewportLength) const; + // From the start of the padding to the end of it, at the bottom of a short list that sits there. + std::pair contentSpan(float viewportLength) const; float crossLength(int index, float listCrossLength) const; // the size a cell binds at across the scroll axis float laneLength(float listCrossLength) const; // one column of a grid, the whole width with one lane ItemRect rectOf(int index, float listCrossLength, float viewportLength) const; @@ -76,11 +95,13 @@ class ListLayout { float anchorEdgeOf(int index, float viewportLength) const; std::vector itemsIn(float start, float end, float viewportLength) const; float emptyMinLength(float viewportLength) const; // the viewport the padding and the other rows leave + float growMinLength(float viewportLength) const; // the same for a growing footer std::optional pinned(const std::vector& sticky, float viewportStart, float viewportLength) const; // Relative to the item's origin: the gap after its row in content order, none after the last row. std::optional separatorRect(int index, float listCrossLength) const; // Inverted or stacked from the end: the list keeps its end where it was. bool bottomAnchored() const { return config_.inverted || config_.stackFromEnd; } + bool justified() const { return !config_.inverted && config_.justify != ListLayoutConfig::Justify::Start; } private: struct Item { @@ -103,9 +124,11 @@ class ListLayout { void rebuildRows(); void updateRow(int row); bool gapAfter(int row) const; - float stride(int row) const; // the row's length and the separator after it + bool isData(int index) const; // not the header, the footer or the empty row + float lineAfter(int row) const; // the separator after the row, 0 when it has none float rowStart(int row) const; // from the start of item 0, inside the padding - float slack(float viewportLength) const; // the space a short list that stacks from the end leaves above its rows + float slack(float viewportLength) const; // the space short content leaves above its rows: all of it at the end, half centered + float minLengthOf(int index, float viewportLength) const; float startOf(int row, float viewportLength) const; // in content coordinates float anchorEdge(int row, float viewportLength) const; int rowAt(float offset, float viewportLength) const; // offset in content coordinates diff --git a/cpp/adapter/ListRows.cpp b/cpp/adapter/ListRows.cpp index 1e241ed..0d59a1a 100644 --- a/cpp/adapter/ListRows.cpp +++ b/cpp/adapter/ListRows.cpp @@ -31,6 +31,7 @@ ListOps ListRows::positions(const ListOps& dataOps) const { to += shift; } for (int& index : ops.changed) index += shift; + for (int& index : ops.neighbors) index += shift; return ops; } diff --git a/cpp/bindings/Engine.cpp b/cpp/bindings/Engine.cpp index cc1e980..4c74d9b 100644 --- a/cpp/bindings/Engine.cpp +++ b/cpp/bindings/Engine.cpp @@ -4,6 +4,7 @@ #include #include "bindings/JsiConverter.h" +#include "core/SeparatorRule.h" #include "core/TreeParser.h" #ifdef __ANDROID__ @@ -118,6 +119,14 @@ void Engine::setCell(int storeId, std::shared_ptr render scheduleRefresh(store, true); } +void Engine::setSeparatorCell(int storeId, std::shared_ptr separatorCell) { + auto store = find(storeId); + if (store == nullptr) return; + store->list.setSeparators(separatorCell != nullptr); + store->setSeparatorCell(std::move(separatorCell)); + scheduleRefresh(store, true); +} + void Engine::setCellKinds(int storeId, bool reactByDefault, std::vector reactTypes) { auto store = find(storeId); if (store == nullptr) return; @@ -133,17 +142,25 @@ void Engine::scheduleRefresh(const std::shared_ptr& store, bool always) { if (scheduler == nullptr) return; std::weak_ptr weak = store; worklets::scheduleOnUI(scheduler, [weak, always] { - auto s = weak.lock(); - if (s == nullptr) return; - std::optional ops = s->list.applyPending(); - if (s->listener == nullptr || (!ops && !always)) return; - ListOps reset; - reset.reset = true; - reset.sticky = s->list.sticky(); - s->listener->onListChanged(always ? reset : *ops, s->list.count()); + if (auto s = weak.lock()) applyPending(*s, always); }); } +bool Engine::applyPending(Store& store, bool always) { + std::optional ops = store.list.applyPending(); + if (store.listener == nullptr || (!ops && !always)) return ops.has_value(); + ListOps reset; + reset.reset = true; + reset.sticky = store.list.sticky(); + store.listener->onListChanged(always ? reset : *ops, store.list.count()); + return ops.has_value(); +} + +bool Engine::applyNow(int storeId) { + auto store = find(storeId); + return store != nullptr && store->list.attached() && applyPending(*store, false); +} + // The JS thread only unregisters. The UI job releases runtime handles under the runtime lock, ~Store the native parts. void Engine::releaseStore(int storeId) { std::shared_ptr scheduler; @@ -203,6 +220,7 @@ void Engine::releaseOnRuntime(int storeId) { store = it->second; } store->slot.renderCellFn.reset(); + store->slot.separatorCellFn.reset(); store->slot.items.clear(); } @@ -228,6 +246,13 @@ void Engine::detach(int storeId) { store->list.setAttached(false); } +void Engine::setRowShape(int storeId, RowShape shape) { + auto store = find(storeId); + if (store == nullptr) return; + store->shape = shape; + store->list.setLanes(shape.horizontal ? 1 : shape.lanes); +} + int Engine::count(int storeId) { auto store = find(storeId); return store == nullptr ? 0 : store->list.count(); @@ -298,6 +323,19 @@ bool Engine::bind(int storeId, int holderId, int index, float widthDp, float hei return true; } +bool Engine::relayout(int storeId, int holderId, float mainDp, OpBatch& out) { + auto store = find(storeId); + if (store == nullptr || store->layout == nullptr) return false; + auto it = store->holders.find(holderId); + if (it == store->holders.end() || it->second == nullptr || it->second->root == nullptr) return false; + Holder& holder = *it->second; + out.clear(); + store->layout->relayout(*holder.root, store->shape.horizontal, mainDp); + store->layout->readFrames(*holder.root, out); + store->reconciler->emitAfterLayout(holder, out); + return true; +} + // Runs on the flume runtime with its lock held: materializes renderCell and the item, calls, parses. void Engine::bindOnRuntime(jsi::Runtime& rt, int index) { std::shared_ptr store = current_.store; @@ -342,6 +380,53 @@ void Engine::bindOnRuntime(jsi::Runtime& rt, int index) { } catch (const std::exception& e) { current_.error = std::string("renderCell failed: ") + e.what(); } + if (current_.fresh != nullptr) composeOnRuntime(rt, *store, index); +} + +// With a separator worklet every row binds composed, and rows before the last grid row get its tree. +void Engine::composeOnRuntime(jsi::Runtime& rt, Store& store, int index) { + Store::RuntimeSlot& slot = store.slot; + auto [separatorCell, version] = store.separatorCell(); + if (separatorCell == nullptr) { + slot.separatorCellFn.reset(); + return; + } + const RowShape& shape = store.shape; + std::unique_ptr separator; + try { + if (!slot.separatorCellFn || slot.separatorCellVersion != version) { + slot.separatorCellFn = separatorCell->toJSValue(rt).asObject(rt).asFunction(rt); + slot.separatorCellVersion = version; + } + int count = store.list.count(); + if (index < lastRowStart(count, shape.horizontal ? 1 : shape.lanes, store.list.sticky())) { + const ListStore& list = store.list; + jsi::Object info(rt); + info.setProperty(rt, "leadingItem", + jsi::Value(rt, slot.items.materialize(rt, list.keyAt(index), list.itemVersion(index), + list.itemAt(index)))); + int next = index + 1; + // A React row's item lives in JS only, so its separator gets no trailing item. + if (next < count && !list.isReactAt(next)) { + info.setProperty(rt, "trailingItem", + jsi::Value(rt, slot.items.materialize(rt, list.keyAt(next), list.itemVersion(next), + list.itemAt(next)))); + } + jsi::Value result = slot.separatorCellFn->call(rt, {jsi::Value(rt, info)}); + if (!result.isNull() && !result.isUndefined()) { + std::vector unknownKeys; + ParseResult parsed = parseTree(toValue(rt, result), &unknownKeys); + for (const std::string& key : unknownKeys) report(1, "unknown style key: " + key); + if (parsed.root == nullptr) report(2, "renderSeparatorCell returned an invalid tree: " + parsed.error); + separator = std::move(parsed.root); + } + } + } catch (const jsi::JSError& e) { + report(2, "renderSeparatorCell threw: " + e.getMessage()); + } catch (const std::exception& e) { + report(2, std::string("renderSeparatorCell failed: ") + e.what()); + } + current_.fresh = composeRow(std::move(current_.fresh), std::move(separator), shape.horizontal, shape.inverted); } int Engine::viewType(int storeId, int position) { diff --git a/cpp/bindings/Engine.h b/cpp/bindings/Engine.h index a5e9397..f4ca673 100644 --- a/cpp/bindings/Engine.h +++ b/cpp/bindings/Engine.h @@ -41,6 +41,7 @@ class Engine { // A sticky-only change: it joins pending data, or applies alone. void setStickyHeaderIndices(int storeId, std::vector sticky); void setCell(int storeId, std::shared_ptr renderCell); + void setSeparatorCell(int storeId, std::shared_ptr separatorCell); // null clears it void setCellKinds(int storeId, bool reactByDefault, std::vector reactTypes); void setReporter(int session, facebook::jsi::Function reporter); // a function on the React runtime, development only void report(int level, const std::string& message); // once per message: the reporter when set, else logcat @@ -52,6 +53,7 @@ class Engine { // UI thread (platform bridge) int attach(int storeId, StoreListener* listener, std::unique_ptr measurer, float pointScale); void detach(int storeId); + void setRowShape(int storeId, RowShape shape); // before any bind laid out with the new shape int count(int storeId); int viewType(int storeId, int position); // type id * 2, plus 1 for React; 0 for an unknown position bool hasReactKinds(int storeId); // some item type renders as a React row @@ -59,9 +61,13 @@ class Engine { std::string keyAt(int storeId, int position); std::vector stickyIndices(int storeId); // UI thread, the applied data's sticky indices bool bind(int storeId, int holderId, int index, float widthDp, float heightDp, OpBatch& out); + // The holder's bound tree laid out again at a main length, NaN for its own, with no worklet call. False with no tree. + bool relayout(int storeId, int holderId, float mainDp, OpBatch& out); void releaseHolder(int storeId, int holderId); void invalidateMeasures(int storeId); // clears the text measure cache void refresh(int storeId); // applies deferred data + // UI thread: applies deferred data now, in the frame of the mount that brought its cells. False when none was pending. + bool applyNow(int storeId); void setStatsEnabled(bool enabled) { statsEnabled_ = enabled; } // any thread; binds read the clock only while on private: @@ -85,7 +91,9 @@ class Engine { std::shared_ptr schedulerOf(int session); std::shared_ptr flumeOf(int session); void scheduleRefresh(const std::shared_ptr& store, bool always); + static bool applyPending(Store& store, bool always); void bindOnRuntime(facebook::jsi::Runtime& rt, int index); + void composeOnRuntime(facebook::jsi::Runtime& rt, Store& store, int index); void releaseOnRuntime(int storeId); void logLine(const std::string& message); diff --git a/cpp/bindings/FlumeHost.cpp b/cpp/bindings/FlumeHost.cpp index d6f7f30..8365635 100644 --- a/cpp/bindings/FlumeHost.cpp +++ b/cpp/bindings/FlumeHost.cpp @@ -15,7 +15,8 @@ namespace jsi = facebook::jsi; namespace { const char* const kNames[] = {"install", "setScheduler", "createStore", "releaseStore", "setData", - "setCell", "setCellKinds", "setStickyHeaderIndices", "setReporter"}; + "setCell", "setSeparatorCell", "setCellKinds", "setStickyHeaderIndices", + "setReporter"}; std::vector stringsOf(jsi::Runtime& rt, const jsi::Value& value) { std::vector out; @@ -157,6 +158,19 @@ jsi::Value FlumeHost::get(jsi::Runtime& rt, const jsi::PropNameID& nameId) { return jsi::Value::undefined(); }); } + if (name == "setSeparatorCell") { + return hostFunction(rt, "setSeparatorCell", 2, + [&engine](jsi::Runtime& rt, const jsi::Value&, const jsi::Value* args, size_t count) { + if (count < 1) throw jsi::JSError(rt, "setSeparatorCell needs a store id"); + std::shared_ptr worklet; + if (count > 1 && !args[1].isNull() && !args[1].isUndefined()) { + worklet = worklets::extractSerializable( + rt, args[1], "react-native-flume: renderSeparatorCell must be a worklet"); + } + engine.setSeparatorCell(static_cast(args[0].asNumber()), std::move(worklet)); + return jsi::Value::undefined(); + }); + } if (name == "setCellKinds") { return hostFunction(rt, "setCellKinds", 3, [&engine](jsi::Runtime& rt, const jsi::Value&, const jsi::Value* args, size_t count) { diff --git a/cpp/bindings/Store.cpp b/cpp/bindings/Store.cpp index 4f0e361..7c0c061 100644 --- a/cpp/bindings/Store.cpp +++ b/cpp/bindings/Store.cpp @@ -28,4 +28,15 @@ uint64_t Store::renderCellVersion() const { return renderCellVersion_; } +void Store::setSeparatorCell(std::shared_ptr separatorCell) { + std::lock_guard lock(mutex_); + separatorCell_ = std::move(separatorCell); + separatorCellVersion_++; +} + +std::pair, uint64_t> Store::separatorCell() const { + std::lock_guard lock(mutex_); + return {separatorCell_, separatorCellVersion_}; +} + } // namespace flume diff --git a/cpp/bindings/Store.h b/cpp/bindings/Store.h index 464cc94..23f26d6 100644 --- a/cpp/bindings/Store.h +++ b/cpp/bindings/Store.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "bindings/ItemCache.h" @@ -37,6 +38,14 @@ struct FlumeRuntime { const facebook::jsi::Function release; }; +// How the platform lays rows out, which decides where a separator goes and which rows draw one. +struct RowShape { + bool horizontal = false; + bool inverted = false; + int lanes = 1; + bool operator==(const RowShape&) const = default; +}; + // One list: its order and items, the cell worklet, its holders and its runtime handles. class Store : public std::enable_shared_from_this { public: @@ -49,10 +58,14 @@ class Store : public std::enable_shared_from_this { // JS thread void setRenderCell(std::shared_ptr renderCell); + void setSeparatorCell(std::shared_ptr separatorCell); // null clears it // UI thread std::shared_ptr renderCell() const; uint64_t renderCellVersion() const; + // The separator worklet with its version, read together so a set between two reads cannot pair them wrong. + std::pair, uint64_t> separatorCell() const; + RowShape shape; // set by the platform view before it binds with a new shape std::unordered_map> holders; StoreListener* listener = nullptr; @@ -65,6 +78,8 @@ class Store : public std::enable_shared_from_this { std::shared_ptr flume; // the runtime of the values below, declared first so it dies last std::optional renderCellFn; uint64_t renderCellVersion = 0; + std::optional separatorCellFn; + uint64_t separatorCellVersion = 0; ItemCache items; uint64_t retainedGeneration = 0; } slot; @@ -73,6 +88,8 @@ class Store : public std::enable_shared_from_this { mutable std::mutex mutex_; std::shared_ptr renderCell_; uint64_t renderCellVersion_ = 0; + std::shared_ptr separatorCell_; + uint64_t separatorCellVersion_ = 0; }; } // namespace flume diff --git a/cpp/core/KeyDiff.cpp b/cpp/core/KeyDiff.cpp index 26169d9..8537172 100644 --- a/cpp/core/KeyDiff.cpp +++ b/cpp/core/KeyDiff.cpp @@ -101,4 +101,16 @@ ListOps diffKeys(const Keys& previous, const Keys& next, const std::vector& return ops; } +std::vector rebound(const ListOps& ops) { + std::vector rows = ops.changed; + rows.insert(rows.end(), ops.neighbors.begin(), ops.neighbors.end()); + std::sort(rows.begin(), rows.end()); + rows.erase(std::unique(rows.begin(), rows.end()), rows.end()); + return rows; +} + +bool isNeighbor(const ListOps& ops, int index) { + return std::binary_search(ops.neighbors.begin(), ops.neighbors.end(), index); +} + } // namespace flume diff --git a/cpp/core/KeyDiff.h b/cpp/core/KeyDiff.h index d45d236..d9d5c3d 100644 --- a/cpp/core/KeyDiff.h +++ b/cpp/core/KeyDiff.h @@ -18,9 +18,16 @@ struct ListOps { std::vector inserted; // next positions, ascending std::vector> moved; // from, to; sequential on the order left by removes then inserts std::vector changed; // next positions of changed items that already existed + std::vector neighbors; // next positions of worklet rows whose separator changed, none of them changed std::vector sticky; // the sticky header indices of the data these ops lead to }; +// The rows a platform rebinds in place: the changed rows and the neighbors, ascending. +std::vector rebound(const ListOps& ops); + +// Whether a next position gained or lost its separator, so a measured length no longer holds. +bool isNeighbor(const ListOps& ops, int index); + // Past this many moves the platform reloads: per-row move animations stop meaning anything, and the work stays bounded. inline constexpr int kMaxMoves = 100; diff --git a/cpp/core/Layout.cpp b/cpp/core/Layout.cpp index 8353340..ee4bbc5 100644 --- a/cpp/core/Layout.cpp +++ b/cpp/core/Layout.cpp @@ -101,8 +101,24 @@ void Layout::invalidateText(Mounted& node) { static bool sameConstraint(float a, float b) { return (std::isnan(a) && std::isnan(b)) || a == b; } +static bool open(const Dimension& dimension) { + return dimension.unit == Dimension::Unit::Undefined || dimension.unit == Dimension::Unit::Auto; +} + +// Yoga sizes a root from the constraints it is given, so the root's own aspect ratio turns one axis into the other here. +static void applyRatio(const Mounted& root, float& width, float& height) { + const std::optional ratio = root.style.aspectRatio; + if (!ratio || *ratio <= 0) return; + if (std::isnan(height) && !std::isnan(width) && open(root.style.height)) { + height = width / *ratio; + } else if (std::isnan(width) && !std::isnan(height) && open(root.style.width)) { + width = height * *ratio; + } +} + // A root laid out at another size re-measures every text first, or Yoga reuses a width it measured before. void Layout::layout(Mounted& root, float width, float height) { + applyRatio(root, width, height); if (!sameConstraint(root.lastLayoutSize[0], width) || !sameConstraint(root.lastLayoutSize[1], height)) { invalidateText(root); root.lastLayoutSize = {width, height}; @@ -110,6 +126,16 @@ void Layout::layout(Mounted& root, float width, float height) { YGNodeCalculateLayout(root.yoga, width, height, YGDirectionLTR); } +// The cross length stays the bound one, so Yoga keeps every text measure. A root with an aspect ratio keeps its length. +void Layout::relayout(Mounted& root, bool horizontal, float main) { + if (root.yoga == nullptr) return; + float width = horizontal ? main : root.lastLayoutSize[0]; + float height = horizontal ? root.lastLayoutSize[1] : main; + if (root.style.aspectRatio) (horizontal ? width : height) = NAN; + applyRatio(root, width, height); + YGNodeCalculateLayout(root.yoga, width, height, YGDirectionLTR); +} + void Layout::readFrames(Mounted& root, OpBatch& out) { out.rootWidth = YGNodeLayoutGetWidth(root.yoga); out.rootHeight = YGNodeLayoutGetHeight(root.yoga); diff --git a/cpp/core/Layout.h b/cpp/core/Layout.h index a35bf05..dfa8e44 100644 --- a/cpp/core/Layout.h +++ b/cpp/core/Layout.h @@ -24,6 +24,8 @@ class Layout { void invalidateText(Mounted& root); // every text re-measures and is sent again, for a new font scale or size void layout(Mounted& root, float width, float height); // NaN on an axis means automatic, as YGUndefined void readFrames(Mounted& root, OpBatch& out); // Frame ops for nodes with a new layout, root size into out + // Lays the root out again at a new main length, its cross length and text measures kept. NaN gives its own length. + void relayout(Mounted& root, bool horizontal, float main); MeasureCache& cache() { return cache_; } int measureCalls = 0; // reset by the caller per bind diff --git a/cpp/core/ListStore.cpp b/cpp/core/ListStore.cpp index 6864f6b..7318640 100644 --- a/cpp/core/ListStore.cpp +++ b/cpp/core/ListStore.cpp @@ -2,6 +2,8 @@ #include +#include "core/SeparatorRule.h" + namespace flume { void ListStore::setPending(std::vector keys, std::vector types, @@ -51,6 +53,7 @@ std::vector stickyWithin(const std::vector& sticky, size_t count) { for (int index : sticky) { if (index >= 0 && static_cast(index) < count) out.push_back(index); } + std::sort(out.begin(), out.end()); return out; } @@ -71,6 +74,11 @@ void ListStore::setKinds(bool reactByDefault, std::vector reactType pendingKinds_ = Kinds{reactByDefault, {reactTypes.begin(), reactTypes.end()}}; } +void ListStore::setSeparators(bool on) { + std::lock_guard lock(mutex_); + separators_ = on; +} + void ListStore::resolveKinds() { reactByTypeId_.assign(typeRegistry_.size(), false); for (const auto& [name, id] : typeRegistry_) { @@ -82,11 +90,13 @@ std::optional ListStore::applyPending() { std::optional pending; std::optional kinds; std::optional> sticky; + bool separators = false; { std::lock_guard lock(mutex_); pending.swap(pending_); kinds.swap(pendingKinds_); sticky.swap(pendingSticky_); + separators = separators_; } if (kinds) { kinds_ = std::move(*kinds); @@ -110,6 +120,9 @@ std::optional ListStore::applyPending() { std::vector typeIds(size); std::vector itemIds(size); std::vector changed = pending->changedIndices; + // Each row's index in the previous data, -1 for a new key, kept only for the separator neighbors. + std::vector oldOf(separators ? size : 0, -1); + const int oldStart = lastRowStart(static_cast(keys_.size()), lanes_, sticky_); size_t carried = 0; for (size_t i = 0; i < size; i++) { typeIds[i] = typeRegistry_.try_emplace(pending->types[i], static_cast(typeRegistry_.size())).first->second; @@ -117,6 +130,7 @@ std::optional ListStore::applyPending() { idRegistry_.try_emplace(pending->keys[i], static_cast(idRegistry_.size()) + 1).first->second; auto it = previous.find(pending->keys[i]); if (it == previous.end()) continue; + if (separators) oldOf[i] = static_cast(it->second); items[i] = std::move(items_[it->second]); versions[i] = versions_[it->second]; carried++; @@ -142,7 +156,28 @@ std::optional ListStore::applyPending() { versions_ = std::move(versions); typeIds_ = std::move(typeIds); itemIds_ = std::move(itemIds); + if (separators && !ops.reset) ops.neighbors = separatorNeighbors(ops, oldOf, oldStart); return ops; } +// A worklet row rebinds when its separator came or went, or when the row after it is another key or changed. +std::vector ListStore::separatorNeighbors(const ListOps& ops, const std::vector& oldOf, int oldStart) const { + const int size = count(); + std::vector fresh(size, false); + for (int index : ops.changed) fresh[index] = true; + for (const auto& range : ops.inserted) { + for (int i = range.index; i < range.index + range.count; i++) fresh[i] = true; + } + const int newStart = lastRowStart(size, lanes_, sticky_); + std::vector neighbors; + for (int i = 0; i < size; i++) { + const int was = oldOf[i]; + if (was < 0 || fresh[i] || isReactAt(i)) continue; + const bool had = was < oldStart; + const bool has = i < newStart; + if (had != has || (has && (fresh[i + 1] || oldOf[i + 1] != was + 1))) neighbors.push_back(i); + } + return neighbors; +} + } // namespace flume diff --git a/cpp/core/ListStore.h b/cpp/core/ListStore.h index f087999..1fd25c5 100644 --- a/cpp/core/ListStore.h +++ b/cpp/core/ListStore.h @@ -26,6 +26,11 @@ class ListStore { // JS thread; the next applyPending applies it, also when no data is pending. void setKinds(bool reactByDefault, std::vector reactTypes); + // JS thread: with worklet separators on, applyPending lists the rows whose separator changed. + void setSeparators(bool on); + // UI thread: the lanes a grid row holds, which decide its last row. + void setLanes(int lanes) { lanes_ = lanes; } + // UI thread, before the attach applies the pending data, so a snapshot that saw the store detached is still applied. void setAttached(bool attached); // Any thread; a detached store needs no UI wake, its attach applies what is pending. @@ -61,6 +66,7 @@ class ListStore { }; void resolveKinds(); + std::vector separatorNeighbors(const ListOps& ops, const std::vector& oldOf, int oldStart) const; mutable std::mutex mutex_; bool attached_ = false; @@ -80,6 +86,8 @@ class ListStore { std::unordered_map idRegistry_; uint64_t nextVersion_ = 1; uint64_t keysGeneration_ = 0; + bool separators_ = false; // under mutex_ + int lanes_ = 1; }; } // namespace flume diff --git a/cpp/core/Mounted.h b/cpp/core/Mounted.h index db80f26..af9e02d 100644 --- a/cpp/core/Mounted.h +++ b/cpp/core/Mounted.h @@ -32,7 +32,8 @@ struct Mounted { std::string testID; std::string accessibilityLabel; std::optional accessible; - std::string derivedLabel; // the label last sent from the texts inside a pressable without its own + bool separator = false; // the separator half of a composed row, left out of the row's label + std::string derivedLabel; // the label last sent from the texts inside a pressable without its own int viewId = 0; // 0 is the holder's own view YGNodeRef yoga = nullptr; Layout* layout = nullptr; diff --git a/cpp/core/Node.h b/cpp/core/Node.h index 9900d2a..4a5220a 100644 --- a/cpp/core/Node.h +++ b/cpp/core/Node.h @@ -28,6 +28,7 @@ struct Node { std::string testID; std::string accessibilityLabel; std::optional accessible; + bool separator = false; // the separator half of a composed row, left out of the row's label std::vector> children; // view and pressable only }; diff --git a/cpp/core/Reconciler.cpp b/cpp/core/Reconciler.cpp index 1e59b83..7e63a55 100644 --- a/cpp/core/Reconciler.cpp +++ b/cpp/core/Reconciler.cpp @@ -81,9 +81,11 @@ void copyProps(Mounted& mounted, Node& fresh) { mounted.testID = std::move(fresh.testID); mounted.accessibilityLabel = std::move(fresh.accessibilityLabel); mounted.accessible = fresh.accessible; + mounted.separator = fresh.separator; } void appendTexts(const Mounted& node, std::string& out) { + if (node.separator) return; if (node.type == NodeType::Text && !node.text.empty()) { if (!out.empty()) out += ' '; out += node.text; @@ -101,6 +103,8 @@ void Reconciler::reconcile(Holder& holder, std::unique_ptr fresh, OpBatch& } return; } + // The cell view is the root's box, so a root margin would only shrink the layout under an unchanged paint. + clearParentLayout(fresh->style); if (holder.root != nullptr && holder.root->type != fresh->type) { unmount(*holder.root, out); holder.root.reset(); diff --git a/cpp/core/SeparatorRule.cpp b/cpp/core/SeparatorRule.cpp new file mode 100644 index 0000000..7b03156 --- /dev/null +++ b/cpp/core/SeparatorRule.cpp @@ -0,0 +1,56 @@ +#include "core/SeparatorRule.h" + +#include +#include + +namespace flume { + +int lastRowStart(int count, int lanes, const std::vector& sortedFullSpans) { + if (count <= 0) return 0; + int last = count - 1; + lanes = std::max(lanes, 1); + // Only the last full span at or before the last index decides where the last run of lanes starts. + auto after = std::upper_bound(sortedFullSpans.begin(), sortedFullSpans.end(), last); + int runStart = 0; + if (after != sortedFullSpans.begin()) { + int span = *(after - 1); + if (span == last) return last; + runStart = span + 1; + } + return runStart + (last - runStart) / lanes * lanes; +} + +std::unique_ptr composeRow(std::unique_ptr row, std::unique_ptr separator, bool horizontal, + bool inverted) { + auto root = std::make_unique(); + root->style.flexDirection = horizontal ? YGFlexDirectionRow : YGFlexDirectionColumn; + if (row->type == NodeType::Pressable) { + root->type = NodeType::Pressable; + row->type = NodeType::View; + } + root->pressId = std::move(row->pressId); + root->pressedOpacity = row->pressedOpacity; + root->testID = std::move(row->testID); + root->accessibilityLabel = std::move(row->accessibilityLabel); + root->accessible = row->accessible; + row->pressId.clear(); + row->testID.clear(); + row->accessibilityLabel.clear(); + row->accessible.reset(); + clearParentLayout(row->style); + // Stretched to a grid row's length, an auto-length row grows like a FlatList row child and the line stays at the end. + root->style.justifyContent = YGJustifySpaceBetween; + const Dimension& length = horizontal ? row->style.width : row->style.height; + const bool own = length.unit == Dimension::Unit::Point || length.unit == Dimension::Unit::Percent; + if (!own && !row->style.aspectRatio) row->style.flexGrow = 1; + row->key = "r"; + root->children.push_back(std::move(row)); + if (separator != nullptr) { + separator->key = "s"; + separator->separator = true; + root->children.insert(inverted ? root->children.begin() : root->children.end(), std::move(separator)); + } + return root; +} + +} // namespace flume diff --git a/cpp/core/SeparatorRule.h b/cpp/core/SeparatorRule.h new file mode 100644 index 0000000..2cb5901 --- /dev/null +++ b/cpp/core/SeparatorRule.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +#include "core/Node.h" + +namespace flume { + +// The first index of the last grid row, whose rows draw no separator. A full-span index ends a run of lanes. +int lastRowStart(int count, int lanes, const std::vector& sortedFullSpans); + +// The row and its separator (first when inverted) under a root that takes the row root's press, label, id and role. +std::unique_ptr composeRow(std::unique_ptr row, std::unique_ptr separator, bool horizontal, + bool inverted); + +} // namespace flume diff --git a/cpp/core/Style.cpp b/cpp/core/Style.cpp index 880b701..aafd611 100644 --- a/cpp/core/Style.cpp +++ b/cpp/core/Style.cpp @@ -290,3 +290,18 @@ Style Style::fromValue(const Value& object, std::vector* unknownKey } } // namespace flume + +namespace flume { + +void clearParentLayout(Style& style) { + style.margin.fill(Dimension{}); + style.position.fill(Dimension{}); + style.positionType.reset(); + style.alignSelf.reset(); + style.flex.reset(); + style.flexGrow.reset(); + style.flexShrink.reset(); + style.flexBasis = Dimension{}; +} + +} // namespace flume diff --git a/cpp/core/Style.h b/cpp/core/Style.h index 3004928..dcac85f 100644 --- a/cpp/core/Style.h +++ b/cpp/core/Style.h @@ -60,4 +60,7 @@ struct Style { bool operator==(const Style&) const = default; }; +// Drops what only a parent reads (margins, insets, position type, alignSelf and flex), as a cell root never has one. +void clearParentLayout(Style& style); + } // namespace flume diff --git a/cpp/tests/batch_updates_test.cpp b/cpp/tests/batch_updates_test.cpp index 1b58e81..6219399 100644 --- a/cpp/tests/batch_updates_test.cpp +++ b/cpp/tests/batch_updates_test.cpp @@ -88,3 +88,10 @@ TEST_CASE("a reset reloads") { ops.reset = true; CHECK(toBatchUpdates(ops, 3).reload); } + +TEST_CASE("separator neighbors are reconfigured with the changed items") { + ListOps ops = diffKeys({"a", "b", "c"}, {"a", "b", "c", "d"}, {}, true); + ops.neighbors = {2}; + BatchUpdates batch = toBatchUpdates(ops, 3); + CHECK(batch.reconfigures == std::vector{2}); +} diff --git a/cpp/tests/jsi/engine_separator_test.cpp b/cpp/tests/jsi/engine_separator_test.cpp new file mode 100644 index 0000000..b1e85d0 --- /dev/null +++ b/cpp/tests/jsi/engine_separator_test.cpp @@ -0,0 +1,167 @@ +#include +#include +#include +#include + +#include "batch.h" +#include "bindings/Engine.h" +#include "bindings/FlumeHost.h" +#include "doctest.h" +#include "fake_measurer.h" +#include "fake_worklets.h" +#include "hermes_rig.h" + +namespace { + +// A React runtime with __flume and a flume runtime installed, so rows bind. +struct ReactSide { + HermesRig rig; + std::shared_ptr invoker = std::make_shared(); + ReactSide() { + flume::FlumeHost::install(rig.rt(), invoker); + installFlumeRuntime(rig.rt()); + } +}; + +struct NullListener : flume::StoreListener { + void onListChanged(const flume::ListOps&, int) override {} +}; + +// Rows 10 pt tall, typed by typeIds, and a separator 1 pt tall whose text names its leading and trailing items. +int separatedStore(ReactSide& side, flume::StoreListener& listener, int count, const std::string& typeIds, + const std::string& reactTypes = "[]") { + std::string keys, items; + for (int i = 0; i < count; i++) { + keys += (i ? ", '" : "'") + std::to_string(i) + "'"; + items += (i ? ", {n: " : "{n: ") + std::to_string(i) + "}"; + } + std::string indices; + for (int i = 0; i < count; i++) indices += (i ? ", " : "") + std::to_string(i); + int id = static_cast( + side.rig + .eval("__flume.setScheduler({});" + "var id = __flume.createStore();" + "__flume.setCellKinds(id, false, " + + reactTypes + + ");" + "__flume.setData(id, [" + + keys + "], ['row', 'react'], new Int32Array([" + typeIds + "]), [" + indices + "], [" + items + + "], true, false);" + "__flume.setCell(id, function (item, index) {" + " 'show source';" + " return {type: 'view', style: {height: 10}};" + "});" + "__flume.setSeparatorCell(id, function (info) {" + " 'show source';" + " var trailing = info.trailingItem === undefined ? 'none' : String(info.trailingItem.n);" + " return {type: 'text', text: info.leadingItem.n + '-' + trailing, style: {height: 1}};" + "});" + "id") + .asNumber()); + REQUIRE(flume::Engine::instance().attach(id, &listener, std::make_unique(), 1) == count); + return id; +} + +flume::OpBatch bound(int id, int index) { + flume::OpBatch out; + REQUIRE(flume::Engine::instance().bind(id, index, index, 300, NAN, out)); + return out; +} + +bool says(const flume::OpBatch& batch, const std::string& text) { + return std::find(batch.strings.begin(), batch.strings.end(), text) != batch.strings.end(); +} + +} // namespace + +TEST_CASE("a separator worklet draws under every row but the last, with the next item") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + auto first = bound(id, 0); + CHECK(says(first, "0-1")); + CHECK(first.rootHeight == 11); + auto last = bound(id, 2); + CHECK_FALSE(says(last, "2-none")); + CHECK(last.rootHeight == 10); + // The last row keeps the composed root, so it never switches shape. + CHECK(frameOf(last, 1).has_value()); +} + +TEST_CASE("a separator before a React row has no trailing item") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 1", "['react']"); + CHECK(says(bound(id, 1), "1-none")); +} + +TEST_CASE("an inverted row shape puts the separator before the row") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + flume::Engine::instance().setRowShape(id, {false, true, 1}); + auto out = bound(id, 0); + // The separator is created first: view 1 at the top, the row view 2 under it. + auto divider = frameOf(out, 1); + auto row = frameOf(out, 2); + REQUIRE(divider); + REQUIRE(row); + CHECK((*divider)[1] == 0); + CHECK((*row)[1] == 1); +} + +TEST_CASE("three lanes leave the last grid row without a separator") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 10, "0, 0, 0, 0, 0, 0, 0, 0, 0, 0"); + flume::Engine::instance().setRowShape(id, {false, false, 3}); + CHECK(says(bound(id, 8), "8-9")); + CHECK(bound(id, 9).rootHeight == 10); +} + +TEST_CASE("clearing the separator worklet binds plain rows again") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + side.rig.eval("__flume.setSeparatorCell(id, null)"); + auto out = bound(id, 0); + CHECK(out.rootHeight == 10); + CHECK_FALSE(frameOf(out, 1).has_value()); +} + +namespace { + +struct RecordingListener : flume::StoreListener { + std::vector calls; + void onListChanged(const flume::ListOps& ops, int) override { calls.push_back(ops); } +}; + +} // namespace + +TEST_CASE("with a separator worklet an append lists the old last row as a neighbor") { + ReactSide side; + RecordingListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + listener.calls.clear(); + side.rig.eval( + "__flume.setData(id, ['0', '1', '2', '3'], ['row', 'react'], new Int32Array([0, 0, 0, 0]), [3], [{n: 3}]," + " true, false);"); + REQUIRE(listener.calls.size() == 1); + CHECK(listener.calls.back().inserted == std::vector{{3, 1}}); + CHECK(listener.calls.back().neighbors == std::vector{2}); +} + +TEST_CASE("relayout lays a bound row out again at a grid row's length without calling the worklet") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + bound(id, 0); + side.rig.eval("__flume.setCell(id, function () { 'show source'; return {type: 'text', text: 'again'}; });"); + flume::OpBatch out; + REQUIRE(flume::Engine::instance().relayout(id, 0, 30, out)); + CHECK_FALSE(says(out, "again")); + CHECK(out.rootHeight == 30); + CHECK(flume::Engine::instance().relayout(id, 0, NAN, out)); + CHECK(out.rootHeight == 11); + CHECK_FALSE(flume::Engine::instance().relayout(id, 99, 30, out)); +} diff --git a/cpp/tests/jsi/engine_session_test.cpp b/cpp/tests/jsi/engine_session_test.cpp index b14156f..448e05f 100644 --- a/cpp/tests/jsi/engine_session_test.cpp +++ b/cpp/tests/jsi/engine_session_test.cpp @@ -181,3 +181,30 @@ TEST_CASE("a sticky-only change reaches the listener as empty ops") { CHECK(listener.calls.back().sticky == std::vector{0, 2}); CHECK(flume::Engine::instance().stickyIndices(id) == std::vector{0, 2}); } + +TEST_CASE("deferred data waits for its cells and applyNow applies it at once") { + ReactSide side; + RecordingListener listener; + int id = stickyStore(side, listener); + listener.calls.clear(); + side.rig.eval( + "__flume.setData(id, ['a', 'b', 'c', 'd'], ['row'], new Int32Array([0, 0, 0, 0]), [], [], true, true, [1]);"); + CHECK(listener.calls.empty()); + CHECK(flume::Engine::instance().applyNow(id)); + REQUIRE(listener.calls.size() == 1); + CHECK(listener.calls.back().inserted == std::vector{{3, 1}}); + CHECK_FALSE(flume::Engine::instance().applyNow(id)); + CHECK(listener.calls.size() == 1); +} + +TEST_CASE("applyNow before the deferred data arrives reports nothing applied") { + ReactSide side; + RecordingListener listener; + int id = stickyStore(side, listener); + listener.calls.clear(); + CHECK_FALSE(flume::Engine::instance().applyNow(id)); + side.rig.eval( + "__flume.setData(id, ['a', 'b', 'c', 'd'], ['row'], new Int32Array([0, 0, 0, 0]), [], [], true, true, [1]);"); + CHECK(flume::Engine::instance().applyNow(id)); + CHECK(listener.calls.size() == 1); +} diff --git a/cpp/tests/layout_test.cpp b/cpp/tests/layout_test.cpp index fbd4d97..6bd0dd2 100644 --- a/cpp/tests/layout_test.cpp +++ b/cpp/tests/layout_test.cpp @@ -186,3 +186,62 @@ TEST_CASE("a row laid out at a fixed height takes its content width") { CHECK(batch.rootWidth == 50); CHECK(batch.rootHeight == 48); } + +namespace { + +// A tree bound at 134 wide, like a grid column, kept for a relayout. +struct Column { + FakeMeasurer fake; + flume::Layout layout{fake, 1}; + std::unique_ptr root; + + explicit Column(const flume::Value& tree) { + int nextId = 1; + auto parsed = flume::parseTree(tree); + REQUIRE(parsed.root); + root = mount(layout, *parsed.root, nextId, true); + frames([&] { layout.layout(*root, 134, NAN); }); + } + + template + flume::OpBatch frames(F run) { + run(); + flume::OpBatch batch; + layout.readFrames(*root, batch); + return batch; + } + + flume::OpBatch relayout(float main) { + return frames([&] { layout.relayout(*root, false, main); }); + } +}; + +flume::Value tile(flume::Value style) { + return styled(std::move(style), {styled(obj({{"flex", V(1)}}), {obj({{"type", V("text")}, {"text", V("hello")}})})}); +} + +} // namespace + +TEST_CASE("relayout stretches an auto root to the row length and keeps its text measures") { + Column column(tile(obj({{"padding", V(4)}}))); + const float natural = YGNodeLayoutGetHeight(column.root->yoga); + const int calls = column.layout.measureCalls; + auto batch = column.relayout(150); + CHECK(batch.rootHeight == 150); + CHECK(frameOf(batch, 1) == Frame{4, 4, 126, 142}); + CHECK(column.layout.measureCalls == calls); + CHECK(column.relayout(NAN).rootHeight == natural); +} + +TEST_CASE("relayout keeps a root that sets its own height") { + Column column(tile(obj({{"height", V(100)}}))); + CHECK(column.relayout(150).rootHeight == 100); +} + +TEST_CASE("a root with an aspect ratio takes its height from the bind width and keeps it") { + Column column(tile(obj({{"aspectRatio", V(1)}}))); + auto bound = column.frames([&] { column.layout.layout(*column.root, 134, NAN); }); + CHECK(column.root->yoga != nullptr); + CHECK(YGNodeLayoutGetHeight(column.root->yoga) == 134); + CHECK(column.relayout(150).rootHeight == 134); +} diff --git a/cpp/tests/list_layout_test.cpp b/cpp/tests/list_layout_test.cpp index 2403d82..a10e815 100644 --- a/cpp/tests/list_layout_test.cpp +++ b/cpp/tests/list_layout_test.cpp @@ -481,3 +481,203 @@ TEST_CASE("the anchor edge is the bottom when inverted or stacking from the end" stacked.stackFromEnd = true; CHECK(measured(4, 50, stacked).anchorEdgeOf(1, 1000) == 900); } + +namespace { + +// A 3-lane grid 300 wide: 16 in from each side, 8 between columns. +ListLayoutConfig gapped() { + ListLayoutConfig config; + config.lanes = 3; + config.crossGap = 8; + config.laneInsetStart = 16; + config.laneInsetEnd = 16; + return config; +} + +} // namespace + +TEST_CASE("lanes take the lane insets and the column gaps out of the row") { + ListLayout layout = measured(3, 50, gapped()); + CHECK(layout.laneLength(300) == 84); + CHECK(layout.crossLength(0, 300) == 84); + CHECK(layout.rectOf(0, 300, 1000) == ItemRect{16, 0, 84, 50}); + CHECK(layout.rectOf(1, 300, 1000) == ItemRect{108, 0, 84, 50}); + CHECK(layout.rectOf(2, 300, 1000) == ItemRect{200, 0, 84, 50}); +} + +TEST_CASE("the header spans the padded width and a full-span data row keeps the lane insets") { + ListLayoutConfig config = gapped(); + config.dataStart = 1; + ListLayout layout = list(5, config, {0, 4}); + CHECK(layout.rectOf(0, 300, 1000).x == 0); + CHECK(layout.rectOf(0, 300, 1000).width == 300); + CHECK(layout.rectOf(1, 300, 1000).x == 16); + CHECK(layout.rectOf(4, 300, 1000).x == 16); + CHECK(layout.rectOf(4, 300, 1000).width == 268); + CHECK(layout.crossLength(4, 300) == 268); +} + +TEST_CASE("the main gap follows every row but the last, after the line, header and footer included") { + ListLayoutConfig config = separated(1); + config.mainGap = 8; + config.dataStart = 1; + config.afterData = 1; + ListLayout layout = list(5, config, {0, 4}); + for (int i = 0; i < 5; i++) layout.setLength(i, 50, 0); + CHECK(y(layout, 1) == 58); + CHECK(y(layout, 2) == 117); + CHECK(y(layout, 3) == 176); + CHECK(y(layout, 4) == 234); + CHECK(layout.contentLength(0) == 284); + CHECK(layout.rowStride(1) == 59); + CHECK(layout.rowStride(4) == 50); + CHECK(*layout.separatorRect(1, 400) == ItemRect{0, 50, 400, 1}); +} + +TEST_CASE("grid rows add the grid row gap after the line") { + ListLayoutConfig config = separated(1); + config.lanes = 2; + config.gridRowGap = 12; + ListLayout layout = measured(4, 50, config); + CHECK(y(layout, 2) == 63); + CHECK(layout.contentLength(0) == 113); +} + +TEST_CASE("an inverted list keeps the line next to its row and the gap beyond it") { + ListLayoutConfig config = separated(1); + config.inverted = true; + config.mainGap = 8; + ListLayout layout = measured(2, 50, config); + CHECK(y(layout, 0) == 950); + CHECK(y(layout, 1) == 891); + CHECK(*layout.separatorRect(0, 400) == ItemRect{0, -1, 400, 1}); +} + +TEST_CASE("the line runs across the column gaps and the lane insets") { + ListLayoutConfig config = gapped(); + config.separator = 1; + ListLayout layout = measured(6, 50, config); + CHECK(*layout.separatorRect(0, 300) == ItemRect{-16, 50, 100, 1}); + CHECK(*layout.separatorRect(1, 300) == ItemRect{-8, 50, 100, 1}); + CHECK(*layout.separatorRect(2, 300) == ItemRect{0, 50, 100, 1}); +} + +TEST_CASE("a pushed sticky header ends with its line at the pusher, over the gap") { + ListLayout layout = measured(10, 100, separated(2)); + CHECK(layout.pinned({0, 5}, 450, 1000)->start == 408); + ListLayoutConfig config = separated(2); + config.mainGap = 8; + ListLayout gapped = measured(10, 100, config); + CHECK(gapped.pinned({0, 5}, 500, 1000)->start == 448); +} + +TEST_CASE("the empty row leaves the viewport the other rows and every gap leave") { + ListLayoutConfig config; + config.mainGap = 8; + config.dataStart = 1; + config.afterData = 1; + config.emptyIndex = 1; + ListLayout layout = list(3, config, {0, 1, 2}); + layout.setLength(0, 50, 0); + layout.setLength(2, 50, 0); + CHECK(layout.emptyMinLength(1000) == 884); +} + +TEST_CASE("an inverted pinned header ends at the pusher's line, which sits above the pusher") { + ListLayoutConfig config = separated(2); + config.inverted = true; + ListLayout layout = measured(10, 100, config); + CHECK(layout.pinned({2, 7}, 650, 1000)->start == 612); +} + +TEST_CASE("every cell of a grid row is as long as the row's longest and keeps its own length") { + ListLayoutConfig config; + config.lanes = 3; + ListLayout layout = list(3, config); + layout.setLength(0, 100, 0); + layout.setLength(1, 150, 0); + layout.setLength(2, 120, 0); + for (int i = 0; i < 3; i++) CHECK(length(layout, i) == 150); + CHECK(layout.itemLength(0) == 100); + layout.setLength(1, 90, 0); + for (int i = 0; i < 3; i++) CHECK(length(layout, i) == 120); + CHECK(layout.itemLength(1) == 90); +} + +TEST_CASE("percent padding resolves against the list width on every edge") { + CHECK(paddingOf(0, 0.05f, 400) == 20); + CHECK(paddingOf(8, 0, 400) == 8); + CHECK(paddingOf(0, 0.05f, 0) == 0); +} + +TEST_CASE("the content span covers the rows and their padding, at the bottom when inverted") { + ListLayoutConfig config; + config.paddingStart = 10; + config.paddingEnd = 20; + CHECK(measured(3, 50, config).contentSpan(1000) == std::pair{0, 180}); + config.inverted = true; + CHECK(measured(3, 50, config).contentSpan(1000) == std::pair{820, 1000}); +} + +TEST_CASE("short content sits at the center or the end of the viewport") { + ListLayoutConfig config; + config.justify = ListLayoutConfig::Justify::Center; + ListLayout centered = measured(3, 100, config); + CHECK(centered.rectOf(0, 400, 600).y == 150); + CHECK(centered.contentLength(600) == 600); + CHECK(centered.contentSpan(600) == std::pair{150, 450}); + config.justify = ListLayoutConfig::Justify::Start; + config.stackFromEnd = true; + CHECK(measured(3, 100, config).rectOf(0, 400, 600).y == 300); +} + +TEST_CASE("end justification moves short content to the end without stacking the list from it") { + ListLayoutConfig config; + config.justify = ListLayoutConfig::Justify::End; + ListLayout column = measured(3, 100, config); + CHECK(column.rectOf(0, 400, 600).y == 300); + CHECK(column.contentLength(600) == 600); + CHECK_FALSE(column.bottomAnchored()); + config.lanes = 3; + CHECK(measured(4, 100, config).rectOf(0, 400, 600).y == 400); + config.lanes = 1; + ListLayout overflowing = measured(20, 50, config); + CHECK(overflowing.rectOf(0, 400, 500).y == 0); + CHECK(overflowing.anchorAt(100, 300) == 2); +} + +TEST_CASE("end-justified short content moves with its slack, so a length change moves no anchor") { + ListLayoutConfig config; + config.justify = ListLayoutConfig::Justify::End; + ListLayout layout = list(3, config); + CHECK(layout.setLength(0, 100, 0, 600).anchorMoved == 0); + CHECK(layout.rectOf(0, 400, 600).y == 400); +} + +TEST_CASE("a growing footer takes what the other rows leave of the viewport") { + ListLayoutConfig config; + config.afterData = 1; + config.growFooter = true; + ListLayout layout = list(4, config, {3}); + for (int i = 0; i < 3; i++) layout.setLength(i, 100, 0); + layout.setLength(3, 50, 0); + CHECK(layout.growMinLength(600) == 300); +} + +TEST_CASE("centered short content recenters itself, so a length change moves no anchor") { + ListLayoutConfig config; + config.justify = ListLayoutConfig::Justify::Center; + ListLayout layout = list(3, config); + CHECK(layout.setLength(0, 100, 0, 600).anchorMoved == 0); + CHECK(layout.rectOf(0, 400, 600).y == 200); +} + +TEST_CASE("stacked from the end, centered content keeps its anchor's bottom where it was") { + ListLayoutConfig config; + config.justify = ListLayoutConfig::Justify::Center; + config.stackFromEnd = true; + ListLayout layout = measured(3, 100, config); + // The end stacking wins: row 2 ends at the viewport end before and after row 0 grows. + CHECK(layout.setLength(0, 200, 2, 600).anchorMoved == 0); + CHECK(layout.rectOf(2, 400, 600).y == 500); +} diff --git a/cpp/tests/list_rows_test.cpp b/cpp/tests/list_rows_test.cpp index b3a0f49..0f83bd8 100644 --- a/cpp/tests/list_rows_test.cpp +++ b/cpp/tests/list_rows_test.cpp @@ -42,3 +42,10 @@ TEST_CASE("full span takes the header, sticky rows, the empty row and the footer ListRows rows{.header = true, .dataCount = 5, .footer = true}; CHECK(rows.fullSpanPositions({2, 4, 9}) == std::vector{0, 3, 5, 6}); } + +TEST_CASE("positions shift the separator neighbors past the header") { + ListRows rows{.header = true, .dataCount = 3, .footer = false}; + ListOps ops; + ops.neighbors = {0, 2}; + CHECK(rows.positions(ops).neighbors == std::vector{1, 3}); +} diff --git a/cpp/tests/list_store_test.cpp b/cpp/tests/list_store_test.cpp index a23018a..e2722fe 100644 --- a/cpp/tests/list_store_test.cpp +++ b/cpp/tests/list_store_test.cpp @@ -18,6 +18,13 @@ TEST_CASE("a first snapshot inserts everything") { CHECK(store.keyAt(2) == "c"); } +TEST_CASE("sticky indices apply sorted, so the last full span is found by a search") { + flume::ListStore store; + store.setPending({"a", "b", "c", "d"}, {"t", "t", "t", "t"}, {0, 1, 2, 3}, {V(1), V(2), V(3), V(4)}, true, {3, 0, 2}); + store.applyPending(); + CHECK(store.sticky() == std::vector{0, 2, 3}); +} + TEST_CASE("a reset carries the sticky indices of its own data") { flume::ListStore store; store.setPending({"a", "b", "c"}, {"t", "t", "t"}, {0, 1, 2}, {V(1), V(2), V(3)}, true, {0}); @@ -167,3 +174,116 @@ TEST_CASE("data set while detached waits for the attach to apply it") { CHECK(ops->inserted == std::vector{{0, 2}}); CHECK(store.count() == 2); } + +namespace { + +std::vector keysUpTo(int count) { + std::vector keys; + for (int i = 0; i < count; i++) keys.push_back("k" + std::to_string(i)); + return keys; +} + +// Applies keys of one worklet type, with the items at changed given new values. +std::optional applyKeys(flume::ListStore& store, std::vector keys, + std::vector changed = {}, std::vector types = {}) { + if (types.empty()) types.assign(keys.size(), "t"); + std::vector items; + for (int index : changed) items.push_back(V(index)); + store.setPending(std::move(keys), std::move(types), std::move(changed), std::move(items), true); + return store.applyPending(); +} + +// A store holding k0..k(count-1) with worklet separators on. +void separated(flume::ListStore& store, int count, int lanes = 1) { + store.setSeparators(true); + store.setLanes(lanes); + std::vector all; + for (int i = 0; i < count; i++) all.push_back(i); + applyKeys(store, keysUpTo(count), all); +} + +} // namespace + +TEST_CASE("an append rebinds the old last row for its separator") { + flume::ListStore store; + separated(store, 5); + auto ops = applyKeys(store, keysUpTo(6), {5}); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{4}); +} + +TEST_CASE("deleting the last row rebinds the new last row") { + flume::ListStore store; + separated(store, 5); + auto ops = applyKeys(store, keysUpTo(4)); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{3}); +} + +TEST_CASE("an insert rebinds the row before it, whose next item changed") { + flume::ListStore store; + separated(store, 5); + auto ops = applyKeys(store, {"k0", "k1", "new", "k2", "k3", "k4"}, {2}); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{1}); +} + +TEST_CASE("a move rebinds the rows before both ends and the moved row") { + flume::ListStore store; + separated(store, 5); + auto ops = applyKeys(store, {"k0", "k2", "k3", "k1", "k4"}); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{0, 2, 3}); +} + +TEST_CASE("a changed item rebinds the row before it, and neighbors leave out changed rows") { + flume::ListStore store; + separated(store, 5); + auto one = applyKeys(store, keysUpTo(5), {3}); + REQUIRE(one); + CHECK(one->neighbors == std::vector{2}); + auto two = applyKeys(store, keysUpTo(5), {3, 4}); + REQUIRE(two); + CHECK(two->neighbors == std::vector{2}); +} + +TEST_CASE("an append to a full last grid row rebinds that whole row") { + flume::ListStore store; + separated(store, 9, 3); + auto ops = applyKeys(store, keysUpTo(10), {9}); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{6, 7, 8}); +} + +TEST_CASE("without separators no neighbor rebinds") { + flume::ListStore store; + separated(store, 5); + store.setSeparators(false); + auto ops = applyKeys(store, keysUpTo(6), {5}); + REQUIRE(ops); + CHECK(ops->neighbors.empty()); +} + +TEST_CASE("a key that turns into a React row rebinds the worklet row before it") { + flume::ListStore store; + store.setKinds(false, {"react"}); + separated(store, 4); + auto ops = applyKeys(store, keysUpTo(4), {}, {"t", "t", "react", "t"}); + REQUIRE(ops); + CHECK(ops->changed == std::vector{2}); + CHECK(ops->neighbors == std::vector{1}); +} + +TEST_CASE("the rows to rebind in place are the changed rows and the neighbors, ascending") { + flume::ListOps ops; + ops.changed = {5, 2}; + ops.neighbors = {1, 4}; + CHECK(flume::rebound(ops) == std::vector{1, 2, 4, 5}); +} + +TEST_CASE("a neighbor position is found among the neighbors only") { + flume::ListOps ops; + ops.neighbors = {1, 4}; + CHECK(flume::isNeighbor(ops, 4)); + CHECK_FALSE(flume::isNeighbor(ops, 2)); +} diff --git a/cpp/tests/separator_rule_test.cpp b/cpp/tests/separator_rule_test.cpp new file mode 100644 index 0000000..b6f3609 --- /dev/null +++ b/cpp/tests/separator_rule_test.cpp @@ -0,0 +1,195 @@ +#include "doctest.h" + +#include +#include +#include +#include + +#include "batch.h" +#include "core/Layout.h" +#include "core/Reconciler.h" +#include "core/SeparatorRule.h" +#include "core/TreeParser.h" +#include "fake_measurer.h" +#include "values.h" + +namespace { + +// The same table as src/__tests__/separators.test.ts. +struct Case { + int count, columns; + std::vector spans; + int start; +}; + +struct Bound { + FakeMeasurer fake; + flume::Layout layout{fake, 1}; + flume::Reconciler rec{layout}; + flume::Holder holder; + flume::OpBatch batch; + + void bind(std::unique_ptr root, float width = 360) { + batch.clear(); + rec.reconcile(holder, std::move(root), batch); + layout.layout(*holder.root, width, NAN); + layout.readFrames(*holder.root, batch); + rec.emitAfterLayout(holder, batch); + } +}; + +std::unique_ptr parsed(const flume::Value& tree) { + auto result = flume::parseTree(tree); + REQUIRE(result.root); + return std::move(result.root); +} + +flume::Value row(const char* label = nullptr) { + flume::Value::Object row{ + {"type", V("pressable")}, + {"id", V("open")}, + {"testID", V("row-a")}, + {"style", obj({{"margin", V(10)}, {"padding", V(12)}, {"backgroundColor", V("#ffffff")}, + {"shadowOpacity", V(0.3)}, {"shadowRadius", V(4)}})}, + {"children", arr({obj({{"type", V("text")}, {"text", V("hello")}}), + obj({{"type", V("text")}, {"text", V("9:41")}})})}}; + if (label != nullptr) row.emplace_back("accessibilityLabel", V(label)); + return flume::Value(std::move(row)); +} + +flume::Value separator() { + return obj({{"type", V("view")}, + {"style", obj({{"height", V(1)}, {"backgroundColor", V("#cccccc")}})}, + {"children", arr({obj({{"type", V("text")}, {"text", V("divider")}})})}}); +} + +// The last accessibility op of a view: label, testID, role. +struct Access { + std::string label, testID; + int role; +}; +std::optional accessOf(const flume::OpBatch& batch, int id) { + std::optional found; + for (const auto& op : decode(batch)) { + if (op.op != 8 || op.id != id) continue; + auto text = [&](int index) { return index < 0 ? std::string() : batch.strings[index]; }; + found = Access{text(op.ints[0]), text(op.ints[1]), op.ints[2]}; + } + return found; +} + +} // namespace + +TEST_CASE("the last grid row starts where the table says") { + const std::vector cases{{0, 1, {}, 0}, {5, 1, {}, 4}, {9, 3, {}, 6}, {10, 3, {}, 9}, + {10, 3, {4}, 8}, {10, 3, {9}, 9}, {6, 2, {0, 3}, 4}}; + for (const Case& c : cases) { + CAPTURE(c.count); + CAPTURE(c.columns); + CHECK(flume::lastRowStart(c.count, c.columns, c.spans) == c.start); + } +} + +TEST_CASE("a composed row draws like the plain row") { + Bound plain; + plain.bind(parsed(row())); + Bound composed; + composed.bind(flume::composeRow(parsed(row()), parsed(separator()), false, false)); + // Plain: the root is view 0 and its texts views 1 and 2. Composed: the row is view 1, its texts 2 and 3. + auto plainRoot = frameOf(plain.batch, 0); + auto composedRow = frameOf(composed.batch, 1); + REQUIRE(plainRoot); + REQUIRE(composedRow); + // A root margin is ignored, so the row spans the bind width in both. + CHECK((*plainRoot)[2] == 360); + CHECK((*composedRow)[0] == 0); + CHECK((*composedRow)[1] == 0); + CHECK((*composedRow)[2] == (*plainRoot)[2]); + CHECK((*composedRow)[3] == (*plainRoot)[3]); + CHECK(frameOf(composed.batch, 2) == frameOf(plain.batch, 1)); + CHECK(frameOf(composed.batch, 3) == frameOf(plain.batch, 2)); + // The separator is view 4, under the row and as wide as the bind width. + auto divider = frameOf(composed.batch, 4); + REQUIRE(divider); + CHECK((*divider)[0] == 0); + CHECK((*divider)[1] == (*plainRoot)[3]); + CHECK((*divider)[2] == 360); + CHECK((*divider)[3] == 1); + auto plainAccess = accessOf(plain.batch, 0); + auto composedAccess = accessOf(composed.batch, 0); + REQUIRE(plainAccess); + REQUIRE(composedAccess); + CHECK(composedAccess->label == plainAccess->label); + CHECK(composedAccess->label.find("divider") == std::string::npos); + CHECK(composedAccess->testID == "row-a"); + CHECK(composedAccess->role == 1); + CHECK_FALSE(accessOf(composed.batch, 1).has_value()); + CHECK(firstOp(composed.batch, 7, 0).id == 0); +} + +TEST_CASE("a composed row keeps the row's own label on the cell") { + Bound composed; + composed.bind(flume::composeRow(parsed(row("Open chat")), parsed(separator()), false, false)); + auto access = accessOf(composed.batch, 0); + REQUIRE(access); + CHECK(access->label == "Open chat"); + CHECK(access->testID == "row-a"); + CHECK_FALSE(accessOf(composed.batch, 1).has_value()); +} + +TEST_CASE("an inverted composed row puts the separator first") { + Bound composed; + composed.bind(flume::composeRow(parsed(row()), parsed(separator()), false, true)); + // The separator is created first, so it is view 1 and the row view 3. + auto divider = frameOf(composed.batch, 1); + REQUIRE(divider); + CHECK((*divider)[1] == 0); + CHECK((*divider)[3] == 1); +} + +TEST_CASE("a composed row without a separator keeps the row alone") { + Bound composed; + composed.bind(flume::composeRow(parsed(row()), nullptr, false, false)); + CHECK(frameOf(composed.batch, 1).has_value()); + CHECK_FALSE(frameOf(composed.batch, 4).has_value()); +} + +namespace { + +flume::Value sized(int height) { + return obj({{"type", V("view")}, {"style", obj({{"height", V(height)}, {"backgroundColor", V("#ffffff")}})}}); +} + +} // namespace + +TEST_CASE("a stretched composed row keeps its separator at the row's end") { + Bound composed; + composed.bind(flume::composeRow(parsed(row()), parsed(separator()), false, false)); + composed.batch.clear(); + composed.layout.relayout(*composed.holder.root, false, 100); + composed.layout.readFrames(*composed.holder.root, composed.batch); + CHECK(composed.batch.rootHeight == 100); + // An auto-height row grows like a FlatList row child, and the line sits at the bottom. + CHECK((*frameOf(composed.batch, 1))[3] == 99); + CHECK((*frameOf(composed.batch, 4))[1] == 99); +} + +TEST_CASE("a stretched composed row keeps a row's own height and the separator at the end, inverted too") { + Bound upright; + upright.bind(flume::composeRow(parsed(sized(40)), parsed(separator()), false, false)); + upright.batch.clear(); + upright.layout.relayout(*upright.holder.root, false, 100); + upright.layout.readFrames(*upright.holder.root, upright.batch); + const auto& rows = upright.holder.root->children; + CHECK(rows[0]->lastFrame == std::array{0, 0, 360, 40}); + CHECK(rows[1]->lastFrame[1] == 99); + Bound inverted; + inverted.bind(flume::composeRow(parsed(sized(40)), parsed(separator()), false, true)); + inverted.batch.clear(); + inverted.layout.relayout(*inverted.holder.root, false, 100); + inverted.layout.readFrames(*inverted.holder.root, inverted.batch); + // Inverted, the separator comes first and the row sits at the end. + const auto& flipped = inverted.holder.root->children; + CHECK(flipped[0]->lastFrame[1] == 0); + CHECK(flipped[1]->lastFrame == std::array{0, 60, 360, 40}); +} diff --git a/example/src/App.tsx b/example/src/App.tsx index 09e61a1..ab45fb1 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -3,6 +3,7 @@ import { NavigationContainer } from '@react-navigation/native'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; import BenchScreen from './screens/BenchScreen'; import ChatScreen from './screens/ChatScreen'; +import CompareScreen from './screens/CompareScreen'; import GridScreen from './screens/GridScreen'; import ReactScreen from './screens/ReactScreen'; import ScrollScreen from './screens/ScrollScreen'; @@ -30,6 +31,7 @@ export default function App() { + diff --git a/example/src/chat.ts b/example/src/chat.ts index 61354a2..36b29b0 100644 --- a/example/src/chat.ts +++ b/example/src/chat.ts @@ -1,4 +1,4 @@ -import { type CellNode, cell } from 'react-native-flume'; +import { type CellNode, cell, type SeparatorCellInfo } from 'react-native-flume'; export type Chat = { id: string; @@ -68,6 +68,16 @@ export function dayIndices(chats: readonly Chat[]): number[] { export const accentColor = (dark: boolean) => (dark ? '#6ea8ff' : '#0066ff'); +// A hairline under each message, inset past the avatar, and full width next to a day chip. +export function makeRenderSeparatorCell(dark: boolean) { + const line = dark ? '#3a3a3a' : '#dddddd'; + return ({ leadingItem, trailingItem }: SeparatorCellInfo): CellNode => { + 'worklet'; + const nextToDay = leadingItem.kind === 'day' || trailingItem?.kind === 'day'; + return cell.view({ height: 1, marginLeft: nextToDay ? 0 : 64, backgroundColor: line }); + }; +} + export function makeRenderCell(dark: boolean) { const textColor = dark ? '#eeeeee' : '#111111'; const timeColor = dark ? '#aaaaaa' : '#666666'; diff --git a/example/src/screens/ChatScreen.tsx b/example/src/screens/ChatScreen.tsx index 9519aeb..c9a8c9c 100644 --- a/example/src/screens/ChatScreen.tsx +++ b/example/src/screens/ChatScreen.tsx @@ -1,7 +1,14 @@ import { useMemo, useRef, useState } from 'react'; import { Button, Platform, ToastAndroid, View } from 'react-native'; import { Flume, type FlumeRef, type PressInfo } from 'react-native-flume'; -import { accentColor, type Chat, dayIndices, makeChats, makeRenderCell } from '../chat'; +import { + accentColor, + type Chat, + dayIndices, + makeChats, + makeRenderCell, + makeRenderSeparatorCell, +} from '../chat'; function blockJs(ms: number) { const end = Date.now() + ms; @@ -53,6 +60,9 @@ export default function ChatScreen() { older: 0, })); const renderCell = useMemo(() => makeRenderCell(dark), [dark]); + // Native hairlines from the separator prop, or a worklet that draws each one next to its rows. + const [workletSeparators, setWorkletSeparators] = useState(false); + const renderSeparatorCell = useMemo(() => makeRenderSeparatorCell(dark), [dark]); const sticky = useMemo(() => dayIndices(list.chats), [list.chats]); const onPress = ({ item, id }: PressInfo) => toast(id === 'like' ? `like ${item.id}` : `open ${item.id}`); @@ -107,6 +117,10 @@ export default function ChatScreen() {