From c67dc75bef3057abff3b6e7069c5023034a1247c Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Sun, 15 Nov 2026 15:28:40 +0000 Subject: [PATCH] Draw native:lazy-stack with a LazyColumn on Android Android pointed lazy_stack at the scroll view renderer as a stopgap, which ignored content-padding. LazyStackRenderer replaces it and matches iOS: - children are keyed by node id - gap-* becomes the column's spacing - p-* and bg-* come in on the modifier like any element - content_padding_* becomes the LazyColumn's contentPadding - shows-indicators is accepted but does nothing, since a LazyColumn has no scroll indicator A LazyColumn keeps the first visible child in place by key when children are added above it, which is right for a reader scrolled down. It does that at the very top too, so new rows would land above the screen. The renderer checks during composition, before the new children are measured, whether the reader was at the top, and if so asks for the top again with requestScrollToItem(0). Inside a scroll view the height is unbounded and a LazyColumn would throw, so it falls back to a plain column, like the lazy grid does. On an API 35 emulator with the heimdall firehose (60 rows a second, capped at 1,000), the main thread applied 56 to 60 updates a second for the whole minute, before and after the cap, with new rows showing at the top. Scrolled down, the rows on screen stayed put until they were trimmed off the end. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- nativephp.json | 2 +- resources/android/LazyStackRenderer.kt | 122 ++++++++++++++++++ src/Elements/LazyStack.php | 4 +- tests/LazyStackTest.php | 4 +- tests/android/README.md | 7 +- tests/android/build.gradle.kts | 2 +- .../src/test/kotlin/LazyStackPositionTest.kt | 117 +++++++++++++++++ 8 files changed, 252 insertions(+), 8 deletions(-) create mode 100644 resources/android/LazyStackRenderer.kt create mode 100644 tests/android/src/test/kotlin/LazyStackPositionTest.kt diff --git a/README.md b/README.md index c6c94e0..352e079 100644 --- a/README.md +++ b/README.md @@ -174,7 +174,7 @@ It has none of a list's extras: no separators, swipe actions, pull-to-refresh, s Give each child a stable `key`. A child added above the screen then doesn't move what the reader is looking at, and a reader at the very top sees new children come in. -It's iOS only for now. On Android it falls back to the `native:scroll-view` renderer, which ignores `content-padding`. +iOS draws it with a `LazyVStack` and Android with a Compose `LazyColumn`. Android has no scroll indicator for it, so `shows-indicators` only matters on iOS. ## Popovers diff --git a/nativephp.json b/nativephp.json index 4e277dc..857421c 100644 --- a/nativephp.json +++ b/nativephp.json @@ -225,7 +225,7 @@ "type": "lazy_stack", "element": "Native\\Mobile\\UI\\Elements\\LazyStack", "blade": "Native\\Mobile\\UI\\Components\\LazyStack", - "android_renderer": "com.nativephp.plugins.native_ui.ui.ScrollViewRenderer", + "android_renderer": "com.nativephp.plugins.native_ui.ui.LazyStackRenderer", "ios_renderer": "NativeUILazyStackRenderer", "self_closing": false }, diff --git a/resources/android/LazyStackRenderer.kt b/resources/android/LazyStackRenderer.kt new file mode 100644 index 0000000..f716d5d --- /dev/null +++ b/resources/android/LazyStackRenderer.kt @@ -0,0 +1,122 @@ +package com.nativephp.plugins.native_ui.ui + +import androidx.compose.foundation.interaction.DragInteraction +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.unit.dp +import com.nativephp.mobile.ui.nativerender.* + +/** + * `native:lazy-stack`: a vertical scroll of children drawn lazily, in a + * LazyColumn, each child keyed by its node id. + * + * It's for long feeds that change often. It does less than a list on + * purpose: no separators, swipe actions, pull-to-refresh, sections or row + * callbacks. Rows draw themselves. + * + * - Spacing between children is the node's `gap-*`. + * - `p-*` and `bg-*` come in on [modifier] like any element. The + * `content_padding_*` props pad the scrolled content instead, so the first + * and last child can sit clear of the edges and still scroll under them. + * - `shows_indicators` is accepted and has no effect: a LazyColumn draws no + * scroll indicator to begin with. + * - A child added above the screen doesn't move what's on it: LazyColumn + * keeps the first visible child in place by key. It does that at the very + * top too, which would hide what was just added, so a reader at the very + * top is kept there and sees new children come in. + */ +object LazyStackRenderer { + @Composable + fun Render(node: NativeUINode, modifier: Modifier) { + val children = node.children + val gap = (node.layout?.gap ?: 0f).dp + val contentPadding = PaddingValues( + start = node.props.getFloat("content_padding_left").dp, + top = node.props.getFloat("content_padding_top").dp, + end = node.props.getFloat("content_padding_right").dp, + bottom = node.props.getFloat("content_padding_bottom").dp, + ) + + val state = rememberLazyListState() + StayAtTopWhenPrepended(children.firstOrNull()?.id, state) + HideKeyboardOnDrag(state) + + // A LazyColumn measured with an unbounded height (a lazy stack inside + // a scroll view) throws, and there would be no viewport to be lazy + // in anyway. Fall back to a plain column that wraps its children, + // like the lazy grid does. + BoxWithConstraints(modifier = modifier) { + if (constraints.hasBoundedHeight) { + LazyColumn( + modifier = Modifier.fillMaxSize(), + state = state, + contentPadding = contentPadding, + verticalArrangement = Arrangement.spacedBy(gap), + ) { + items(children, key = { it.id }) { child -> + NodeView(node = child) + } + } + } else { + Column( + modifier = Modifier.fillMaxWidth().padding(contentPadding), + verticalArrangement = Arrangement.spacedBy(gap), + ) { + children.forEach { child -> NodeView(node = child) } + } + } + } + } + + /** + * When a new first child arrives and the reader was at the very top, + * ask for the top again in the next measure. + * + * This runs in composition, before the LazyColumn measures the new + * children, so the scroll position it reads is still the one the reader + * was looking at. After that measure LazyColumn has already moved to keep + * the old first child, and the reader would no longer look "at the top". + * The reads skip snapshot observation so scrolling doesn't recompose the + * stack. + */ + @Composable + private fun StayAtTopWhenPrepended(firstId: Int?, state: LazyListState) { + val lastFirstId = remember { intArrayOf(NO_ID) } + val previous = lastFirstId[0] + lastFirstId[0] = firstId ?: NO_ID + if (firstId == null || previous == NO_ID || firstId == previous) return + + val atTop = Snapshot.withoutReadObservation { + state.firstVisibleItemIndex == 0 && state.firstVisibleItemScrollOffset <= 1 + } + if (atTop) state.requestScrollToItem(0) + } + + /** Dismiss the keyboard when the reader drags the stack, like a scroll view. */ + @Composable + private fun HideKeyboardOnDrag(state: LazyListState) { + val keyboard = LocalSoftwareKeyboardController.current + LaunchedEffect(state, keyboard) { + state.interactionSource.interactions.collect { interaction -> + if (interaction is DragInteraction.Start) keyboard?.hide() + } + } + } + + private const val NO_ID = Int.MIN_VALUE +} diff --git a/src/Elements/LazyStack.php b/src/Elements/LazyStack.php index a18604e..4b83051 100644 --- a/src/Elements/LazyStack.php +++ b/src/Elements/LazyStack.php @@ -28,8 +28,8 @@ * element; {@see contentPadding()} (the `content-padding` attribute, which * a server screen sends as `contentPadding`) pads the scrolled content. * - * iOS only for now. Android draws it with the scroll view's renderer, which - * ignores the content padding. + * iOS draws it with a LazyVStack, Android with a LazyColumn. A LazyColumn + * has no scroll indicator, so `shows-indicators` does nothing there. */ class LazyStack extends Element { diff --git a/tests/LazyStackTest.php b/tests/LazyStackTest.php index 2c310a0..4578850 100644 --- a/tests/LazyStackTest.php +++ b/tests/LazyStackTest.php @@ -72,14 +72,14 @@ expect($props['shows_indicators'])->toBeFalse(); }); -it('registers a renderer for iOS and falls back to the scroll view on Android', function () { +it('registers its own renderer on iOS and Android', function () { $manifest = json_decode(file_get_contents(dirname(__DIR__).'/nativephp.json'), true); $component = collect($manifest['components'])->firstWhere('type', 'lazy_stack'); expect($component)->toMatchArray([ 'element' => LazyStack::class, 'blade' => LazyStackComponent::class, - 'android_renderer' => 'com.nativephp.plugins.native_ui.ui.ScrollViewRenderer', + 'android_renderer' => 'com.nativephp.plugins.native_ui.ui.LazyStackRenderer', 'ios_renderer' => 'NativeUILazyStackRenderer', 'self_closing' => false, ]); diff --git a/tests/android/README.md b/tests/android/README.md index 1297e65..b821c95 100644 --- a/tests/android/README.md +++ b/tests/android/README.md @@ -2,7 +2,7 @@ This standalone Robolectric/Compose module compiles the production filled and outlined editors, their shared dispatcher, the production Button renderer and -the production gesture area, list, virtual list, pager and bottom sheet renderers, +the production gesture area, list, virtual list, lazy stack, pager and bottom sheet renderers, the background layer host and the layout drawer host. It records the bridge event boundary; it does not load PHP/JNI, render icons or @@ -51,6 +51,11 @@ re-arms it, and saved-state restoration keeps the reader's position unless the request changed while it was saved. Assertions check which row is at the viewport's top, not just that a scroll was invoked. +`LazyStackPositionTest` checks that a reader at the top of a lazy stack sees +children added above, a reader scrolled down keeps their child in place through +prepends and trims, content padding and gap place the children, and a stack +inside a scroll view falls back to a plain column instead of throwing. + `BottomSheetCloseTest` closes an open sheet and checks its content leaves composition: when its detents change in the same render, and when a finger grabs it while it slides away. `RenderNode` here draws each child as diff --git a/tests/android/build.gradle.kts b/tests/android/build.gradle.kts index 2132056..90930f7 100644 --- a/tests/android/build.gradle.kts +++ b/tests/android/build.gradle.kts @@ -5,7 +5,7 @@ plugins { } val stageSources = tasks.register("stageSources") { from(layout.projectDirectory.dir("../../resources/android")) { - include("FilledTextInputRenderer.kt", "OutlinedTextInputRenderer.kt", "BareTextInputRenderer.kt", "TextInputShared.kt", "NativeUIFontResolver.kt", "NativeUITheme.kt", "ButtonRenderer.kt", "GestureAreaRenderer.kt", "ListRenderer.kt", "VirtualListRenderer.kt", "PagerRenderer.kt", "BottomSheetRenderer.kt", "NativeLayoutDrawerHost.kt", "NativeUIBackgroundLayerHost.kt") + include("FilledTextInputRenderer.kt", "OutlinedTextInputRenderer.kt", "BareTextInputRenderer.kt", "TextInputShared.kt", "NativeUIFontResolver.kt", "NativeUITheme.kt", "ButtonRenderer.kt", "GestureAreaRenderer.kt", "ListRenderer.kt", "VirtualListRenderer.kt", "LazyStackRenderer.kt", "PagerRenderer.kt", "BottomSheetRenderer.kt", "NativeLayoutDrawerHost.kt", "NativeUIBackgroundLayerHost.kt") } from(providers.gradleProperty("mobileRoot").map { "$it/resources/androidstudio/app/src/main/java/com/nativephp/mobile/ui/nativerender" }) { include("KeyboardFocusPolicy.kt", "NativeUINode.kt", "SharedValueStore.kt", "NativeCompositionLocals.kt", "NativeRendererRegistry.kt", "NodeModifiers.kt", "NodeBorder.kt", "NodeAccessibility.kt", "ComposeFlexLayout.kt") diff --git a/tests/android/src/test/kotlin/LazyStackPositionTest.kt b/tests/android/src/test/kotlin/LazyStackPositionTest.kt new file mode 100644 index 0000000..4381323 --- /dev/null +++ b/tests/android/src/test/kotlin/LazyStackPositionTest.kt @@ -0,0 +1,117 @@ +package com.nativephp.plugins.native_ui.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.* +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.unit.dp +import com.nativephp.mobile.ui.nativerender.GenericProps +import com.nativephp.mobile.ui.nativerender.NativeUINode +import com.nativephp.mobile.ui.nativerender.NodeLayout +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * `native:lazy-stack` on Android. Each child is a 120dp box tagged + * `node-` (see the NodeView stand-in), in a 300dp-tall stack. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class LazyStackPositionTest { + @get:Rule val compose = createComposeRule() + + private val ids = mutableStateOf((100 until 110).toList()) + private var props = GenericProps() + private var gap = 0f + + @Test fun aReaderAtTheTopSeesChildrenAddedAbove() { + show() + assertAtTop(100) + + compose.runOnIdle { ids.value = listOf(99) + ids.value } + assertAtTop(99) + + compose.runOnIdle { ids.value = listOf(97, 98) + ids.value } + assertAtTop(97) + } + + @Test fun aReaderScrolledDownKeepsTheirChildWhenChildrenAreAddedAbove() { + show() + stack().performScrollToIndex(5) + assertAtTop(105) + + compose.runOnIdle { ids.value = listOf(98, 99) + ids.value } + assertAtTop(105) + + // And when the oldest are trimmed off the end, as a capped feed does. + compose.runOnIdle { ids.value = listOf(97) + ids.value.dropLast(2) } + assertAtTop(105) + } + + @Test fun contentPaddingAndGapPlaceTheChildren() { + props = GenericProps( + mapOf( + "content_padding_top" to 16f, + "content_padding_left" to 8f, + "content_padding_bottom" to 16f, + "content_padding_right" to 8f, + ) + ) + gap = 10f + show() + + val box = compose.onNodeWithTag("stack").getUnclippedBoundsInRoot() + val first = compose.onNodeWithTag("node-100").getUnclippedBoundsInRoot() + val second = compose.onNodeWithTag("node-101").getUnclippedBoundsInRoot() + assertEquals(box.top.value + 16f, first.top.value, 1f) + assertEquals(box.left.value + 8f, first.left.value, 1f) + assertEquals(first.bottom.value + 10f, second.top.value, 1f) + } + + @Test fun insideAScrollViewItFallsBackToAPlainColumn() { + compose.setContent { + MaterialTheme { + Column(Modifier.height(300.dp).verticalScroll(rememberScrollState())) { + LazyStackRenderer.Render(node(), Modifier.width(300.dp).testTag("stack")) + } + } + } + // Every child is composed, since there's no viewport to be lazy in. + compose.onNodeWithTag("node-109").assertExists() + } + + private fun node(): NativeUINode { + val rows = ids.value.map { id -> + NativeUINode(id, "text", null, null, GenericProps(), 0, 0, emptyList()) + } + val layout = if (gap > 0f) NodeLayout(0f, 0, 0f, 0, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0, 0, 0, gap) else null + return NativeUINode(1, "lazy_stack", layout, null, props, 0, 0, rows) + } + + private fun show() { + compose.setContent { + MaterialTheme { + LazyStackRenderer.Render(node(), Modifier.width(300.dp).height(300.dp).testTag("stack")) + } + } + } + + private fun stack() = compose.onNode(hasScrollToIndexAction()) + + private fun assertAtTop(id: Int) { + val box = compose.onNodeWithTag("stack").getUnclippedBoundsInRoot() + val row = compose.onNodeWithTag("node-$id").assertIsDisplayed().getUnclippedBoundsInRoot() + assertEquals("child $id is at the top", box.top.value, row.top.value, 1f) + } +}