@onekeyfe/react-native-native-list 3.0.157-alpha.258 → 3.0.157-alpha.273

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -302,7 +302,9 @@ The ref exposes `applySnapshot`, `applyPatches`, `reconcileSelection`,
302
302
  `scrollToKey(key, animated, alignment)` signatures remain supported. Object
303
303
  parameters follow React Native list semantics: `viewPosition` is from `0`
304
304
  (start) through `1` (end), and a positive `viewOffset` leaves space before the
305
- target row.
305
+ target row. Web, Android and iOS explicit position alignment also centers/ends
306
+ oversized rows; `nearest` preserves its legacy behavior. See [scrolling contract](docs/SPEC.md#explicit-scroll-alignment-ok-64041)
307
+ for platform status.
306
308
 
307
309
  Use `initialScrollIndex` or the stable-key extension `initialScrollKey` to set
308
310
  the first position. They are mutually exclusive, run once after the first
@@ -418,3 +420,17 @@ status. See [docs/DESIGN.md](docs/DESIGN.md) for the architecture and ownership
418
420
  tokens, local layout-safety rules, common list capabilities and current implementation
419
421
  gaps. [docs/ROW_TEMPLATES.md](docs/ROW_TEMPLATES.md) defines all 12 row types with
420
422
  structural illustrations, required fields, variants and styling boundaries.
423
+
424
+ ## Native scrolling regression tests
425
+
426
+ In a configured React Native example/consumer Android project, run
427
+ `./gradlew :onekeyfe_react-native-native-list:testDebugUnitTest --tests com.margelo.nitro.nativelist.NativeListScrollAlignmentTest`.
428
+ This uses the existing JUnit dependency and compiles the shipping Kotlin helper
429
+ and NativeListView. The Gradle project name may differ in another consumer.
430
+
431
+ Run `swift test --package-path tests/swiftpm` from this package for the native
432
+ Swift geometry regression suite. Its source symlink compiles the shipping
433
+ helper directly. These are geometry unit tests, not RecyclerView/UICollectionView
434
+ integration tests. Full-app visibility, unmounted/deferred behavior and
435
+ consumer-owned layout/input cancellation require separate runtime validation;
436
+ see [the scrolling spec](docs/SPEC.md).
@@ -1,11 +1,13 @@
1
1
  package com.margelo.nitro.nativelist
2
2
 
3
+ import android.graphics.Bitmap
3
4
  import android.graphics.Rect
4
5
  import android.view.ViewTreeObserver
5
6
  import android.view.Gravity
6
7
  import android.view.TextureView
7
8
  import android.view.View
8
9
  import android.widget.FrameLayout
10
+ import android.widget.ImageView
9
11
  import androidx.annotation.OptIn
10
12
  import androidx.media3.common.MediaItem
11
13
  import androidx.media3.common.PlaybackException
@@ -25,7 +27,10 @@ import com.facebook.react.uimanager.ThemedReactContext
25
27
  import okhttp3.JavaNetCookieJar
26
28
  import org.json.JSONObject
27
29
 
28
- /** Uses Media3 like native Video, but never starts playback or requests audio focus. */
30
+ /**
31
+ * Uses Media3 like native Video, but never starts playback or requests audio focus. A player
32
+ * lives only until its first frame is captured; the tile then shows that still frame.
33
+ */
29
34
  @OptIn(UnstableApi::class)
30
35
  internal class NativeListMediaPreviewSlot(private val context: ThemedReactContext) {
31
36
  val view: FrameLayout = object : FrameLayout(context) {
@@ -37,6 +42,7 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
37
42
  private val image = NativeListImageSlot(context)
38
43
  private val video = AspectRatioFrameLayout(context)
39
44
  private val texture = TextureView(context)
45
+ private val frame = ImageView(context)
40
46
  private var identity: String? = null
41
47
  private var epoch = 0
42
48
  private var candidateGeneration = 0
@@ -58,6 +64,9 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
58
64
  view.isFocusable = false
59
65
  view.descendantFocusability = android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS
60
66
  video.addView(texture, FrameLayout.LayoutParams(-1, -1))
67
+ frame.scaleType = ImageView.ScaleType.FIT_XY
68
+ frame.visibility = View.GONE
69
+ video.addView(frame, FrameLayout.LayoutParams(-1, -1))
61
70
  view.addView(image.view, FrameLayout.LayoutParams(-1, -1))
62
71
  view.addView(video, FrameLayout.LayoutParams(-1, -1, Gravity.CENTER))
63
72
  video.visibility = View.GONE
@@ -147,7 +156,11 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
147
156
  next.setAudioAttributes(androidx.media3.common.AudioAttributes.DEFAULT, false)
148
157
  next.setVideoTextureView(texture)
149
158
  next.addListener(object : Player.Listener {
150
- override fun onRenderedFirstFrame() { if (playerGeneration == generation) finished(true, generation) }
159
+ override fun onRenderedFirstFrame() {
160
+ if (playerGeneration != generation) return
161
+ finished(true, generation)
162
+ captureFirstFrame(token, candidate, generation, FIRST_FRAME_CAPTURE_ATTEMPTS)
163
+ }
151
164
  override fun onPlayerError(error: PlaybackException) { if (playerGeneration == generation) finished(false, generation) }
152
165
  override fun onVideoSizeChanged(size: VideoSize) {
153
166
  if (playerGeneration == generation && size.height > 0) video.setAspectRatio(size.width * size.pixelWidthHeightRatio / size.height)
@@ -165,6 +178,40 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
165
178
  updateVisibility()
166
179
  }
167
180
 
181
+ /**
182
+ * The rendered frame reaches the TextureView asynchronously, so a transparent copy is
183
+ * retried on later frames. If no frame can be copied the paused player stays attached.
184
+ */
185
+ private fun captureFirstFrame(token: Int, candidate: Int, generation: Int, attemptsLeft: Int) {
186
+ view.postOnAnimation {
187
+ if (epoch != token || candidateGeneration != candidate || playerGeneration != generation) return@postOnAnimation
188
+ // Releasing first would make the queued success completion drop itself as stale.
189
+ if (result != true) {
190
+ captureFirstFrame(token, candidate, generation, attemptsLeft)
191
+ return@postOnAnimation
192
+ }
193
+ val still = if (texture.isAvailable && texture.width > 0 && texture.height > 0) {
194
+ runCatching { texture.getBitmap(texture.width, texture.height) }.getOrNull()
195
+ } else null
196
+ if (still == null || !hasVisiblePixels(still)) {
197
+ still?.recycle()
198
+ if (attemptsLeft > 1) captureFirstFrame(token, candidate, generation, attemptsLeft - 1)
199
+ return@postOnAnimation
200
+ }
201
+ frame.setImageBitmap(still)
202
+ frame.visibility = View.VISIBLE
203
+ resumeVideo = null
204
+ stopObservingViewport()
205
+ releasePlayer()
206
+ }
207
+ }
208
+
209
+ private fun hasVisiblePixels(bitmap: Bitmap): Boolean {
210
+ val columns = intArrayOf(bitmap.width / 4, bitmap.width / 2, bitmap.width * 3 / 4)
211
+ val rows = intArrayOf(bitmap.height / 4, bitmap.height / 2, bitmap.height * 3 / 4)
212
+ return columns.any { x -> rows.any { y -> (bitmap.getPixel(x, y) ushr 24) != 0 } }
213
+ }
214
+
168
215
  private fun observeViewport() {
169
216
  if (viewportObserver != null || resumeVideo == null || !view.isAttachedToWindow) return
170
217
  view.viewTreeObserver.takeIf { it.isAlive }?.let {
@@ -209,7 +256,13 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
209
256
  image.view.visibility = View.VISIBLE
210
257
  video.visibility = View.GONE
211
258
  video.setAspectRatio(0f)
259
+ frame.setImageDrawable(null)
260
+ frame.visibility = View.GONE
212
261
  identity = null; result = null; completion = null
213
262
  }
263
+
264
+ private companion object {
265
+ const val FIRST_FRAME_CAPTURE_ATTEMPTS = 6
266
+ }
214
267
  fun dispose() { recycle(); image.dispose() }
215
268
  }
@@ -0,0 +1,29 @@
1
+ package com.margelo.nitro.nativelist
2
+
3
+ import kotlin.math.roundToInt
4
+
5
+ internal fun nativeListAlignedStart(
6
+ viewportStart: Int,
7
+ viewportLength: Int,
8
+ itemLength: Int,
9
+ viewPosition: Double,
10
+ viewOffset: Int,
11
+ nearest: Boolean,
12
+ ): Int {
13
+ val alignmentSpace = viewportLength - itemLength
14
+ val resolvedSpace = if (nearest) alignmentSpace.coerceAtLeast(0) else alignmentSpace
15
+ return viewportStart + (viewPosition * resolvedSpace).roundToInt() + viewOffset
16
+ }
17
+
18
+ internal fun nativeListProvisionalStart(
19
+ viewportLength: Int,
20
+ viewPosition: Double,
21
+ viewOffset: Int,
22
+ nearest: Boolean,
23
+ ): Int {
24
+ val provisionalOffset = (viewPosition * viewportLength).roundToInt() + viewOffset
25
+ // Keep an explicit target mounted until its measured size can be aligned.
26
+ return if (nearest) provisionalOffset else {
27
+ provisionalOffset.coerceIn(0, (viewportLength - 1).coerceAtLeast(0))
28
+ }
29
+ }
@@ -15,6 +15,8 @@ internal class NativeListScrollPositionTracker {
15
15
  this.end = end
16
16
  }
17
17
 
18
+ val isConfigured: Boolean get() = start != null && end != null
19
+
18
20
  fun resetDelivery() { previous = null }
19
21
 
20
22
  fun update(offset: Double): Boolean? {
@@ -27,3 +29,31 @@ internal class NativeListScrollPositionTracker {
27
29
  return next
28
30
  }
29
31
  }
32
+
33
+ /**
34
+ * Content extent above [first]: whole grid lines (tallest item per line) that end before the
35
+ * line containing [first]. Span sizes follow GridLayoutManager's default line breaking.
36
+ */
37
+ internal fun nativeListScrollPrefixPx(
38
+ first: Int,
39
+ spanCount: Int,
40
+ spanSize: (Int) -> Int,
41
+ extent: (Int) -> Int,
42
+ ): Long {
43
+ val columns = spanCount.coerceAtLeast(1)
44
+ var prefix = 0L
45
+ var lineExtent = 0
46
+ var lineSpans = 0
47
+ for (position in 0 until first) {
48
+ val span = spanSize(position).coerceIn(1, columns)
49
+ if (lineSpans + span > columns) {
50
+ prefix += lineExtent
51
+ lineExtent = 0
52
+ lineSpans = 0
53
+ }
54
+ lineSpans += span
55
+ lineExtent = maxOf(lineExtent, extent(position))
56
+ }
57
+ if (first > 0 && lineSpans + spanSize(first).coerceIn(1, columns) > columns) prefix += lineExtent
58
+ return prefix
59
+ }
@@ -58,6 +58,21 @@ private class NativeListGridLayoutManager(
58
58
  context: Context,
59
59
  spanCount: Int,
60
60
  ) : GridLayoutManager(context, spanCount) {
61
+ var onChildLaidOut: ((View, Int) -> Unit)? = null
62
+ var onLayoutPassCompleted: (() -> Unit)? = null
63
+
64
+ // Scroll fills and layout passes both place children here, including rows that a
65
+ // positional jump lays out and immediately leaves offscreen.
66
+ override fun layoutDecoratedWithMargins(child: View, left: Int, top: Int, right: Int, bottom: Int) {
67
+ super.layoutDecoratedWithMargins(child, left, top, right, bottom)
68
+ onChildLaidOut?.invoke(child, if (orientation == RecyclerView.VERTICAL) bottom - top else right - left)
69
+ }
70
+
71
+ override fun onLayoutCompleted(state: RecyclerView.State) {
72
+ super.onLayoutCompleted(state)
73
+ onLayoutPassCompleted?.invoke()
74
+ }
75
+
61
76
  override fun removeAndRecycleViewAt(index: Int, recycler: RecyclerView.Recycler) {
62
77
  val child = getChildAt(index) ?: return
63
78
  removeViewAt(index)
@@ -115,26 +130,32 @@ class NativeListView(
115
130
  private val coordinatorOffsetListener = Runnable { emitScrollPositionThresholdIfNeeded() }
116
131
  private var logicalScrollDistancePx = 0
117
132
  private val scrollPositionTracker = NativeListScrollPositionTracker()
133
+ private val measuredRowExtentsPx = HashMap<String, Int>()
134
+ private var measuredRowExtentSumPx = 0L
118
135
  var onScrollPositionThresholdChange: ((Boolean) -> Unit)? = null
119
136
  set(value) {
120
137
  field = value
121
138
  scrollPositionTracker.resetDelivery()
122
- emitScrollPositionThresholdIfNeeded()
139
+ emitScrollPositionThresholdIfNeeded(resync = true)
123
140
  }
124
141
 
125
142
  fun setScrollPositionThresholdsJson(json: String) {
126
143
  val config = runCatching { JSONObject(json) }.getOrNull()
127
144
  scrollPositionTracker.configure(config?.optDouble("start"), config?.optDouble("end"))
128
- emitScrollPositionThresholdIfNeeded()
145
+ emitScrollPositionThresholdIfNeeded(resync = true)
129
146
  }
130
147
 
131
- private fun emitScrollPositionThresholdIfNeeded() {
148
+ /**
149
+ * Continuous scrolling accumulates the exact consumed dy. Layout passes and positional
150
+ * jumps (scrollToIndex/End, anchor restores, inserts above) report no dy, so they re-derive
151
+ * the distance from the laid-out first item plus the extents of every item before it.
152
+ */
153
+ private fun emitScrollPositionThresholdIfNeeded(resync: Boolean = false) {
132
154
  if (disposed) return
133
155
  val callback = onScrollPositionThresholdChange ?: return
134
- if (layoutManager.findFirstVisibleItemPosition() == 0) {
135
- layoutManager.findViewByPosition(0)?.let { first ->
136
- logicalScrollDistancePx = (recyclerView.paddingTop - layoutManager.getDecoratedTop(first)).coerceAtLeast(0)
137
- }
156
+ if (!scrollPositionTracker.isConfigured) return
157
+ if (resync || layoutManager.findFirstVisibleItemPosition() == 0) {
158
+ measuredScrollDistancePx()?.let { logicalScrollDistancePx = it }
138
159
  }
139
160
  val contributions = recyclerView.getTag(R.id.onekey_native_scroll_coordinator_consumed_offsets) as? Map<*, *>
140
161
  val parentDistance = contributions?.values?.sumOf { (it as? Int)?.coerceAtLeast(0)?.toLong() ?: 0L } ?: 0L
@@ -154,6 +175,7 @@ class NativeListView(
154
175
  private val density = resources.displayMetrics.density
155
176
  private val recyclerView = RecyclerView(context)
156
177
  private var configuredTopPaddingPx = 0
178
+ private var slotInsetPx = 0
157
179
  private var configuredBottomPaddingPx = 0
158
180
  private val refreshLayout = SwipeRefreshLayout(context)
159
181
  private val refreshIndicatorTravelPx = refreshLayout.progressViewEndOffset
@@ -201,6 +223,52 @@ class NativeListView(
201
223
  }
202
224
 
203
225
  private fun scrollPositionForRow(index: Int): Int = index + headerSlotAdapter.itemCount
226
+
227
+ private fun recordLaidOutRowExtent(child: View, extentPx: Int) {
228
+ val holder = recyclerView.getChildViewHolder(child) as? NativeListViewHolder ?: return
229
+ if (holder.bindingAdapter !== adapter) return
230
+ val key = adapter.itemAt(holder.bindingAdapterPosition)?.key ?: return
231
+ val previous = measuredRowExtentsPx.put(key, extentPx)
232
+ measuredRowExtentSumPx += extentPx - (previous ?: 0)
233
+ }
234
+
235
+ private fun pruneMeasuredRowExtents(items: List<NativeListItem>) {
236
+ if (measuredRowExtentsPx.isEmpty()) return
237
+ val keys = items.mapTo(HashSet(items.size)) { it.key }
238
+ measuredRowExtentsPx.keys.retainAll(keys)
239
+ measuredRowExtentSumPx = measuredRowExtentsPx.values.sumOf { it.toLong() }
240
+ }
241
+
242
+ /** Rows skipped by a jump have never been laid out; explicit heights beat the average. */
243
+ private fun estimatedScrollExtentPx(position: Int): Int {
244
+ val headerCount = headerSlotAdapter.itemCount
245
+ if (position < headerCount) return slotHeights[0]
246
+ val row = position - headerCount
247
+ if (row >= adapter.itemCount) {
248
+ return if (row - adapter.itemCount < emptySlotAdapter.itemCount) slotHeights[1] else slotHeights[2]
249
+ }
250
+ val item = adapter.itemAt(row)
251
+ item?.key?.let(measuredRowExtentsPx::get)?.let { return it }
252
+ val explicit = item?.styledHeight ?: item?.json?.optDouble("height")?.takeIf { it.isFinite() }
253
+ if (explicit != null) return (explicit * density).roundToInt()
254
+ return if (measuredRowExtentsPx.isEmpty()) 0 else (measuredRowExtentSumPx / measuredRowExtentsPx.size).toInt()
255
+ }
256
+
257
+ private fun measuredScrollDistancePx(): Int? {
258
+ if (layoutManager.orientation != RecyclerView.VERTICAL) return null
259
+ val first = layoutManager.findFirstVisibleItemPosition()
260
+ if (first == RecyclerView.NO_POSITION) return null
261
+ val view = layoutManager.findViewByPosition(first) ?: return null
262
+ val prefix = nativeListScrollPrefixPx(
263
+ first,
264
+ layoutManager.spanCount,
265
+ layoutManager.spanSizeLookup::getSpanSize,
266
+ ::estimatedScrollExtentPx,
267
+ )
268
+ val topMargin = (view.layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin ?: 0
269
+ val top = layoutManager.getDecoratedTop(view) - topMargin
270
+ return (prefix + recyclerView.paddingTop - top).coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
271
+ }
204
272
  private fun rowPositionForScroll(index: Int): Int =
205
273
  if (index == RecyclerView.NO_POSITION) RecyclerView.NO_POSITION else index - headerSlotAdapter.itemCount
206
274
 
@@ -417,6 +485,9 @@ class NativeListView(
417
485
  recyclerView.addItemDecoration(reorderPlaceholderDecoration)
418
486
  // OneKey patch: full-width selector header backgrounds do not change row content insets.
419
487
  recyclerView.addItemDecoration(SelectorBackgroundDecoration(adapter))
488
+ recyclerView.addItemDecoration(ContainerSlotInsetDecoration { slotInsetPx })
489
+ layoutManager.onChildLaidOut = ::recordLaidOutRowExtent
490
+ layoutManager.onLayoutPassCompleted = { emitScrollPositionThresholdIfNeeded(resync = true) }
420
491
  recyclerView.setHasFixedSize(false)
421
492
  layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
422
493
  override fun getSpanSize(position: Int): Int {
@@ -522,7 +593,7 @@ class NativeListView(
522
593
 
523
594
  override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
524
595
  logicalScrollDistancePx = (logicalScrollDistancePx + dy).coerceAtLeast(0)
525
- emitScrollPositionThresholdIfNeeded()
596
+ emitScrollPositionThresholdIfNeeded(resync = dx == 0 && dy == 0)
526
597
  if (dx != 0 || dy != 0) invalidateActionAnchor("scroll")
527
598
  syncSectionIndexToVisibleRows()
528
599
  scheduleVisibleEvent()
@@ -687,6 +758,7 @@ class NativeListView(
687
758
  }
688
759
  } else null
689
760
  config = next
761
+ pruneMeasuredRowExtents(next.items)
690
762
  updateContainerSlots()
691
763
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
692
764
  adapter.usesSelectorSourceScale = usesSelectorSourceScale
@@ -1107,9 +1179,10 @@ class NativeListView(
1107
1179
  requestedViewPosition.coerceIn(0.0, 1.0)
1108
1180
  }
1109
1181
  val offsetPx = (viewOffset * density).roundToInt()
1182
+ val nearest = alignment == "nearest"
1110
1183
 
1111
1184
  if (visibleView != null) {
1112
- alignVisibleView(manager, visibleView, viewPosition, offsetPx, animated)
1185
+ alignVisibleView(manager, visibleView, viewPosition, offsetPx, animated, nearest)
1113
1186
  return
1114
1187
  }
1115
1188
  if (animated) {
@@ -1119,12 +1192,12 @@ class NativeListView(
1119
1192
 
1120
1193
  override fun calculateDyToMakeVisible(view: View, snapPreference: Int): Int {
1121
1194
  if (manager.orientation != RecyclerView.VERTICAL) return 0
1122
- return smoothAlignmentDelta(manager, view, viewPosition, offsetPx)
1195
+ return smoothAlignmentDelta(manager, view, viewPosition, offsetPx, nearest)
1123
1196
  }
1124
1197
 
1125
1198
  override fun calculateDxToMakeVisible(view: View, snapPreference: Int): Int {
1126
1199
  if (manager.orientation != RecyclerView.HORIZONTAL) return 0
1127
- return smoothAlignmentDelta(manager, view, viewPosition, offsetPx)
1200
+ return smoothAlignmentDelta(manager, view, viewPosition, offsetPx, nearest)
1128
1201
  }
1129
1202
  }
1130
1203
  smoothScroller.targetPosition = scrollPositionForRow(index)
@@ -1132,10 +1205,12 @@ class NativeListView(
1132
1205
  return
1133
1206
  }
1134
1207
 
1135
- val provisionalOffset = (viewPosition * viewportLength(manager)).roundToInt() + offsetPx
1136
- manager.scrollToPositionWithOffset(scrollPositionForRow(index), provisionalOffset)
1208
+ val layoutOffset = nativeListProvisionalStart(
1209
+ viewportLength(manager), viewPosition, offsetPx, nearest,
1210
+ )
1211
+ manager.scrollToPositionWithOffset(scrollPositionForRow(index), layoutOffset)
1137
1212
  relayoutRecyclerView()
1138
- alignAfterLayout(index, viewPosition, offsetPx)
1213
+ alignAfterLayout(index, viewPosition, offsetPx, nearest)
1139
1214
  }
1140
1215
 
1141
1216
  private fun performOffsetScroll(offset: Double, animated: Boolean) {
@@ -1171,6 +1246,7 @@ class NativeListView(
1171
1246
  index: Int,
1172
1247
  viewPosition: Double,
1173
1248
  viewOffset: Int,
1249
+ nearest: Boolean,
1174
1250
  attemptsRemaining: Int = 2,
1175
1251
  ) {
1176
1252
  recyclerView.post {
@@ -1178,11 +1254,11 @@ class NativeListView(
1178
1254
  val view = manager.findViewByPosition(scrollPositionForRow(index))
1179
1255
  if (view == null) {
1180
1256
  if (attemptsRemaining > 0) {
1181
- alignAfterLayout(index, viewPosition, viewOffset, attemptsRemaining - 1)
1257
+ alignAfterLayout(index, viewPosition, viewOffset, nearest, attemptsRemaining - 1)
1182
1258
  }
1183
1259
  return@post
1184
1260
  }
1185
- alignVisibleView(manager, view, viewPosition, viewOffset, false)
1261
+ alignVisibleView(manager, view, viewPosition, viewOffset, false, nearest)
1186
1262
  }
1187
1263
  }
1188
1264
 
@@ -1192,6 +1268,7 @@ class NativeListView(
1192
1268
  viewPosition: Double,
1193
1269
  viewOffset: Int,
1194
1270
  animated: Boolean,
1271
+ nearest: Boolean,
1195
1272
  ) {
1196
1273
  val itemStart = decoratedStart(manager, view)
1197
1274
  val itemLength = decoratedEnd(manager, view) - itemStart
@@ -1200,9 +1277,9 @@ class NativeListView(
1200
1277
  } else {
1201
1278
  manager.paddingLeft
1202
1279
  }
1203
- val targetStart = viewportStart +
1204
- (viewPosition * (viewportLength(manager) - itemLength).coerceAtLeast(0)).roundToInt() +
1205
- viewOffset
1280
+ val targetStart = nativeListAlignedStart(
1281
+ viewportStart, viewportLength(manager), itemLength, viewPosition, viewOffset, nearest,
1282
+ )
1206
1283
  val delta = itemStart - targetStart
1207
1284
  if (manager.orientation == RecyclerView.VERTICAL) {
1208
1285
  if (animated) recyclerView.smoothScrollBy(0, delta) else recyclerView.scrollBy(0, delta)
@@ -1216,6 +1293,7 @@ class NativeListView(
1216
1293
  view: View,
1217
1294
  viewPosition: Double,
1218
1295
  viewOffset: Int,
1296
+ nearest: Boolean,
1219
1297
  ): Int {
1220
1298
  val itemStart = decoratedStart(manager, view)
1221
1299
  val itemLength = decoratedEnd(manager, view) - itemStart
@@ -1224,9 +1302,9 @@ class NativeListView(
1224
1302
  } else {
1225
1303
  manager.paddingLeft
1226
1304
  }
1227
- val targetStart = viewportStart +
1228
- (viewPosition * (viewportLength(manager) - itemLength).coerceAtLeast(0)).roundToInt() +
1229
- viewOffset
1305
+ val targetStart = nativeListAlignedStart(
1306
+ viewportStart, viewportLength(manager), itemLength, viewPosition, viewOffset, nearest,
1307
+ )
1230
1308
  return targetStart - itemStart
1231
1309
  }
1232
1310
 
@@ -1300,6 +1378,10 @@ class NativeListView(
1300
1378
  actionAnchor = null
1301
1379
  pendingScrollRequest = null
1302
1380
  visibleEventScheduled = false
1381
+ layoutManager.onChildLaidOut = null
1382
+ layoutManager.onLayoutPassCompleted = null
1383
+ measuredRowExtentsPx.clear()
1384
+ measuredRowExtentSumPx = 0L
1303
1385
  reorderTouchHandler?.removeCallbacksAndMessages(null)
1304
1386
  reorderTouchHandler = null
1305
1387
  reorderTouchListener?.let(recyclerView::removeOnItemTouchListener)
@@ -1332,6 +1414,8 @@ class NativeListView(
1332
1414
  // Content/theme snapshots must replace only the padding owned by NativeList.
1333
1415
  val coordinatorTopPadding = (recyclerView.paddingTop - configuredTopPaddingPx).coerceAtLeast(0)
1334
1416
  val coordinatorBottomPadding = (recyclerView.paddingBottom - configuredBottomPaddingPx).coerceAtLeast(0)
1417
+ // Slot roots are laid out by React at the unscaled JS inset, without the index gutter.
1418
+ slotInsetPx = (horizontalPadding * density).roundToInt()
1335
1419
  configuredTopPaddingPx = dp(topPadding)
1336
1420
  configuredBottomPaddingPx = dp(bottomPadding)
1337
1421
  recyclerView.setPaddingRelative(
@@ -2298,6 +2382,8 @@ class NativeListView(
2298
2382
  val child = recyclerView.findChildViewUnder(event.x, event.y)
2299
2383
  candidate = child
2300
2384
  ?.let(recyclerView::getChildViewHolder)
2385
+ // Container-slot holders report binding position 0 in their own adapter.
2386
+ ?.takeIf { holder -> holder is NativeListViewHolder && holder.bindingAdapter === adapter }
2301
2387
  ?.takeIf { holder ->
2302
2388
  adapter.itemAt(holder.bindingAdapterPosition)?.let { item ->
2303
2389
  // OneKey patch: any wallet group member can initiate the group drag.
@@ -2896,6 +2982,25 @@ private class ItemSpacingDecoration(
2896
2982
  }
2897
2983
  }
2898
2984
 
2985
+ /**
2986
+ * React lays out slot content at `contentPaddingHorizontal ?? contentPadding` logical units
2987
+ * from each edge. Row padding may be scaled or widened by the section-index gutter, so slot
2988
+ * holders offset themselves (possibly negatively) back to the JavaScript inset.
2989
+ */
2990
+ private class ContainerSlotInsetDecoration(private val insetPx: () -> Int) : RecyclerView.ItemDecoration() {
2991
+ override fun getItemOffsets(
2992
+ outRect: android.graphics.Rect,
2993
+ view: View,
2994
+ parent: RecyclerView,
2995
+ state: RecyclerView.State,
2996
+ ) {
2997
+ if (parent.getChildViewHolder(view) !is NativeListContainerSlotAdapter.Holder) return
2998
+ val inset = insetPx()
2999
+ outRect.left = inset - parent.paddingLeft
3000
+ outRect.right = inset - parent.paddingRight
3001
+ }
3002
+ }
3003
+
2899
3004
  internal fun isStickySectionHeader(item: NativeListItem): Boolean =
2900
3005
  item.type == "sectionHeader" && item.json.optBoolean("sticky", true) && item.json.optString("variant") != "summary"
2901
3006
 
@@ -0,0 +1,62 @@
1
+ package com.margelo.nitro.nativelist
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Test
5
+
6
+ class NativeListScrollAlignmentTest {
7
+ @Test
8
+ fun oversizedGroupUsesMeasuredSignedSpaceForParentMiddleAndLastMember() {
9
+ // Complete-app measurements: usable viewport 1377px, decorated group 4648px.
10
+ // The caller supplies offsets for the parent and two hidden-wallet members.
11
+ val offsets = listOf(2205, 105, -1995)
12
+ assertEquals(
13
+ listOf(591, -1509, -3609),
14
+ offsets.map { nativeListAlignedStart(21, 1377, 4648, 0.5, it, false) },
15
+ )
16
+ }
17
+
18
+ @Test
19
+ fun explicitStartCenterAndEndPreservePaddingAndSignedOffsets() {
20
+ assertEquals(8, nativeListAlignedStart(8, 400, 870, 0.0, 0, false))
21
+ assertEquals(-227, nativeListAlignedStart(8, 400, 870, 0.5, 0, false))
22
+ assertEquals(-462, nativeListAlignedStart(8, 400, 870, 1.0, 0, false))
23
+ assertEquals(-547, nativeListAlignedStart(8, 400, 870, 0.5, -320, false))
24
+ assertEquals(93, nativeListAlignedStart(8, 400, 870, 0.5, 320, false))
25
+ }
26
+
27
+ @Test
28
+ fun shortAndEqualRowsKeepTheirExistingAlignment() {
29
+ assertEquals(8, nativeListAlignedStart(8, 400, 68, 0.0, 0, false))
30
+ assertEquals(174, nativeListAlignedStart(8, 400, 68, 0.5, 0, false))
31
+ assertEquals(340, nativeListAlignedStart(8, 400, 68, 1.0, 0, false))
32
+ assertEquals(28, nativeListAlignedStart(8, 400, 400, 0.5, 20, false))
33
+ }
34
+
35
+ @Test
36
+ fun nearestRetainsLegacyOversizedAndShortRowBehavior() {
37
+ assertEquals(21, nativeListAlignedStart(21, 1377, 4648, 0.0, 0, true))
38
+ assertEquals(126, nativeListAlignedStart(21, 1377, 4648, 1.0, 105, true))
39
+ assertEquals(174, nativeListAlignedStart(8, 400, 68, 0.5, 0, true))
40
+ }
41
+
42
+ @Test
43
+ fun unmountedExplicitTargetStartsInsideViewportUntilMeasured() {
44
+ assertEquals(1376, nativeListProvisionalStart(1377, 0.5, 2205, false))
45
+ assertEquals(794, nativeListProvisionalStart(1377, 0.5, 105, false))
46
+ assertEquals(0, nativeListProvisionalStart(1377, 0.5, -1995, false))
47
+ assertEquals(1376, nativeListProvisionalStart(1377, 1.0, 0, false))
48
+ }
49
+
50
+ @Test
51
+ fun provisionalBoundaryIsDefinedForEmptyAndOnePixelViewports() {
52
+ assertEquals(0, nativeListProvisionalStart(0, 0.5, 2205, false))
53
+ assertEquals(0, nativeListProvisionalStart(1, 0.5, -1995, false))
54
+ assertEquals(0, nativeListProvisionalStart(1, 1.0, 2205, false))
55
+ }
56
+
57
+ @Test
58
+ fun nearestKeepsItsExistingUnboundedProvisionalPosition() {
59
+ assertEquals(2894, nativeListProvisionalStart(1377, 0.5, 2205, true))
60
+ assertEquals(-1306, nativeListProvisionalStart(1377, 0.5, -1995, true))
61
+ }
62
+ }
@@ -25,4 +25,20 @@ class NativeListScrollPositionTrackerTest {
25
25
  tracker.configure(48.0, 48.0)
26
26
  assertNull(tracker.update(48.0))
27
27
  }
28
+
29
+ @Test fun measuredPrefixMatchesLinearAndGridLines() {
30
+ val heights = intArrayOf(30, 80, 80, 80, 40, 90, 60)
31
+ // Linear: every item before the first visible one.
32
+ assertEquals(0L, nativeListScrollPrefixPx(0, 1, { 1 }, heights::get))
33
+ assertEquals(30L + 80 + 80, nativeListScrollPrefixPx(3, 1, { 1 }, heights::get))
34
+ // Grid of 3 with a full-span header at 0: lines [0], [1,2,3], [4,5,6].
35
+ val span = { position: Int -> if (position == 0) 3 else 1 }
36
+ assertEquals(30L, nativeListScrollPrefixPx(1, 3, span, heights::get))
37
+ assertEquals(30L, nativeListScrollPrefixPx(2, 3, span, heights::get))
38
+ assertEquals(30L + 80, nativeListScrollPrefixPx(4, 3, span, heights::get))
39
+ assertEquals(30L + 80, nativeListScrollPrefixPx(6, 3, span, heights::get))
40
+ // The tallest cell defines a grid line.
41
+ val uneven = intArrayOf(10, 20, 50, 5)
42
+ assertEquals(50L, nativeListScrollPrefixPx(3, 3, { 1 }, uneven::get))
43
+ }
28
44
  }