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

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.
@@ -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
  }
@@ -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
@@ -1300,6 +1372,10 @@ class NativeListView(
1300
1372
  actionAnchor = null
1301
1373
  pendingScrollRequest = null
1302
1374
  visibleEventScheduled = false
1375
+ layoutManager.onChildLaidOut = null
1376
+ layoutManager.onLayoutPassCompleted = null
1377
+ measuredRowExtentsPx.clear()
1378
+ measuredRowExtentSumPx = 0L
1303
1379
  reorderTouchHandler?.removeCallbacksAndMessages(null)
1304
1380
  reorderTouchHandler = null
1305
1381
  reorderTouchListener?.let(recyclerView::removeOnItemTouchListener)
@@ -1332,6 +1408,8 @@ class NativeListView(
1332
1408
  // Content/theme snapshots must replace only the padding owned by NativeList.
1333
1409
  val coordinatorTopPadding = (recyclerView.paddingTop - configuredTopPaddingPx).coerceAtLeast(0)
1334
1410
  val coordinatorBottomPadding = (recyclerView.paddingBottom - configuredBottomPaddingPx).coerceAtLeast(0)
1411
+ // Slot roots are laid out by React at the unscaled JS inset, without the index gutter.
1412
+ slotInsetPx = (horizontalPadding * density).roundToInt()
1335
1413
  configuredTopPaddingPx = dp(topPadding)
1336
1414
  configuredBottomPaddingPx = dp(bottomPadding)
1337
1415
  recyclerView.setPaddingRelative(
@@ -2298,6 +2376,8 @@ class NativeListView(
2298
2376
  val child = recyclerView.findChildViewUnder(event.x, event.y)
2299
2377
  candidate = child
2300
2378
  ?.let(recyclerView::getChildViewHolder)
2379
+ // Container-slot holders report binding position 0 in their own adapter.
2380
+ ?.takeIf { holder -> holder is NativeListViewHolder && holder.bindingAdapter === adapter }
2301
2381
  ?.takeIf { holder ->
2302
2382
  adapter.itemAt(holder.bindingAdapterPosition)?.let { item ->
2303
2383
  // OneKey patch: any wallet group member can initiate the group drag.
@@ -2896,6 +2976,25 @@ private class ItemSpacingDecoration(
2896
2976
  }
2897
2977
  }
2898
2978
 
2979
+ /**
2980
+ * React lays out slot content at `contentPaddingHorizontal ?? contentPadding` logical units
2981
+ * from each edge. Row padding may be scaled or widened by the section-index gutter, so slot
2982
+ * holders offset themselves (possibly negatively) back to the JavaScript inset.
2983
+ */
2984
+ private class ContainerSlotInsetDecoration(private val insetPx: () -> Int) : RecyclerView.ItemDecoration() {
2985
+ override fun getItemOffsets(
2986
+ outRect: android.graphics.Rect,
2987
+ view: View,
2988
+ parent: RecyclerView,
2989
+ state: RecyclerView.State,
2990
+ ) {
2991
+ if (parent.getChildViewHolder(view) !is NativeListContainerSlotAdapter.Holder) return
2992
+ val inset = insetPx()
2993
+ outRect.left = inset - parent.paddingLeft
2994
+ outRect.right = inset - parent.paddingRight
2995
+ }
2996
+ }
2997
+
2899
2998
  internal fun isStickySectionHeader(item: NativeListItem): Boolean =
2900
2999
  item.type == "sectionHeader" && item.json.optBoolean("sticky", true) && item.json.optString("variant") != "summary"
2901
3000
 
@@ -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
  }
package/docs/SPEC.md CHANGED
@@ -390,9 +390,10 @@ only. Existing Web rendering and caller behavior are unchanged.
390
390
  Replacing the JS callback takes effect on the next event; disabling emits no event.
391
391
  Configuration updates reset hysteresis before recomputing current position.
392
392
  - iOS uses contentOffset + contentInset, excluding overscroll below zero. Android
393
- accumulates consumed child scroll distance and rebases from first-item geometry.
394
- Parent-pager header contributions and arbitrary index-jump acceptance are tracked
395
- separately; no estimate-based parity claim is made for unverified jumps.
393
+ accumulates consumed child scroll distance and, after every layout pass or
394
+ zero-delta scroll, re-derives it from the measured extents above the first laid-out
395
+ item (see Android ancestor scroll distance). Parent-pager header contributions are
396
+ tracked separately.
396
397
  - `layout.gridColumns` accepts integers 2 through 7 on native. Native parsers
397
398
  clamp malformed external JSON to 1 through 7 as before; public JS validation
398
399
  rejects invalid requested counts. Grid geometry remains container-owned.
@@ -433,14 +434,22 @@ changing probe order or the terminal result contract; native runtime regression
433
434
  acceptance is still required. A tile owns at most one native player. On iOS,
434
435
  eligibility requires intersection with the window and every clipping/scroll
435
436
  ancestor viewport; native scroll, bounds, layer transform/position and visibility
436
- observations release retained offscreen pager pages. Detach, background,
437
- invisibility and recycle release the player; reattachment rebuilds its retained
438
- source while remaining paused. Android observes native global scroll/layout and
437
+ observations release retained offscreen pager pages. A player lives only until
438
+ its first rendered frame is copied (Android TextureView bitmap, iOS
439
+ AVPlayerItemVideoOutput pixel buffer); the tile then shows that still frame with the
440
+ same fit and letterbox and releases the player and its viewport observers. If no frame
441
+ can be copied after a few frames, the paused player stays attached. Detach,
442
+ background, invisibility and recycle release a player still awaiting its first frame;
443
+ reattachment rebuilds its retained source while remaining paused. The still frame is
444
+ kept across detach and same-identity rebinding and dropped on recycle or identity
445
+ change. Android observes native global scroll/layout and
439
446
  pre-draw geometry (including property animations), checking ancestor alpha and
440
447
  getGlobalVisibleRect before allocating a player. These observers do not schedule
441
448
  frames or emit JavaScript events.
442
- Player count is bounded by intersecting native video tiles, including partially
443
- visible tiles; there is no numeric cap that blanks visible iPad cells. iOS requests
449
+ Live player count is bounded by intersecting native video tiles that have not yet
450
+ captured a frame, including partially visible tiles; there is no numeric cap that
451
+ blanks visible iPad cells. Per-draw (Android) and ancestor-layer KVO (iOS) viewport
452
+ observation exists only while a tile awaits its first frame. iOS requests
444
453
  one second of forward buffer; AVFoundation treats this as an advisory preference,
445
454
  not a hard byte limit. Android uses a 250–1000 ms forward buffer, zero back buffer
446
455
  and a 2 MiB target allocator; Media3 may exceed a target by allocation granularity.
@@ -479,14 +488,20 @@ Slots scroll with the native list. `fixedFooter` remains a separate fixed native
479
488
  row descriptor. `scrollToEnd` aligns the final scrolling slot bottom with the
480
489
  viewport end, including footer/empty/header-only slots taller than the viewport. Callers using `listEmpty` MUST omit `snapshot.emptyState`, whose
481
490
  existing native descriptor becomes a data item. Horizontal content padding applies
482
- to slots as well as data rows. Slot React trees own their internal layout and
491
+ to slots as well as data rows: every platform places a slot root exactly
492
+ `contentPaddingHorizontal ?? contentPadding` logical units from each edge, the same
493
+ width React lays it out at. Android's narrow-screen row scale and section-index gutter
494
+ apply to data rows only. Slot React trees own their internal layout and
483
495
  business actions; NativeList owns their scroll placement and lifecycle.
484
496
 
485
497
  The wrapper mounts exactly three non-collapsible slot roots and reports measured
486
498
  heights through `containerSlotHeightsJson` in header/empty/footer order. Native
487
499
  validates three finite, non-negative heights. Slot updates MUST NOT alter data-row
488
500
  keys or public row indices. No per-scroll-frame JS position updates are used.
489
- iOS mounts slot roots inside UICollectionView and reserves native layout space.
501
+ iOS mounts each slot root inside a list-owned host view in UICollectionView and
502
+ reserves native layout space. The host owns the slot's vertical position and clips to
503
+ the reported height, so React frame updates cannot move a slot out of place and a slot
504
+ whose height has not been reported yet (or has just grown) never draws over rows.
490
505
  Android uses ConcatAdapter with three single-item slot adapters around the existing
491
506
  data adapter; adapter binding indices stay local while layout-manager positions
492
507
  are explicitly translated. Slots span all grid columns, do not select/reorder,
@@ -558,7 +573,10 @@ source `description`; footer actions retain their existing source/keys and
558
573
  disabled behavior. All actions use the current host binding epoch.
559
574
 
560
575
  Rich rows measure the declared line/visual metrics; there is no six-line native
561
- truncation. The existing height override contract still applies. RTL follows
576
+ truncation. iOS automatic height mirrors the rendered stacks: `lineGap` between the
577
+ visible title/description/status lines, the description measured at the identity
578
+ column's actual width (stacked or table, including the fee column), fee height and the
579
+ footer-action button height. Android sizes the row to its content. The existing height override contract still applies. RTL follows
562
580
  semantic leading/trailing anchors. Clearing rich fields returns to the legacy
563
581
  renderer, and removing amount lines recycles their visual slots. Web rendering
564
582
  remains unchanged; rich fields are native-only until a separate Web migration.
@@ -581,12 +599,17 @@ same logical Home threshold as iOS normalized content scrolling, without a JS
581
599
  scroll-frame event. Changes to the listener or public callbacks do not replace
582
600
  native resource ownership.
583
601
 
584
- Child distance uses actual onScrolled dy and rebases from first-item geometry at
585
- top; scrollToOffset seeds a known explicit offset. It does not use RecyclerView's
586
- average-height scrollbar estimate. Continuous scrolling and return-to-top are
587
- covered by this policy; exact classification immediately after arbitrary distant
588
- scrollToIndex jumps remains pending measured-prefix correction and MUST NOT be
589
- claimed as verified. A later top anchor restores exact distance.
602
+ Child distance uses actual onScrolled dy while scrolling continuously. Programmatic
603
+ jumps (scrollToIndex/Key/End/Offset), anchor restores and inserts or height changes
604
+ above the viewport report no dy, so every layout pass and zero-delta scroll re-derives
605
+ the distance as the extent of all grid lines before the first laid-out item plus its
606
+ offset from the padded top. Extents are those actually laid out (recorded per row key,
607
+ including rows a jump lays out and leaves offscreen, pruned to the current rows); a row
608
+ that was never laid out uses its explicit height, else the mean laid-out row extent.
609
+ Slots use their reported heights. The result is exact once every item above the
610
+ viewport has been laid out and an estimate only across never-laid-out rows; it does not
611
+ use RecyclerView's average-height scrollbar estimate. Runtime acceptance for distant
612
+ jumps remains pending.
590
613
 
591
614
 
592
615
  ### Container follow-up verification
@@ -249,7 +249,7 @@ Each cell describes the same public contract on **Web + iOS + Android**.
249
249
  | `identity` | title, subtitle, tertiary, badge, value, valueSecondary | padding, leadingGap, lineGap, titleBadgeGap, trailingGap, image |
250
250
  | `walletGroup` | None; members own their identity styles | padding |
251
251
  | `rail` | title, badge, status | padding, leadingGap, titleBadgeGap, trailingGap, image |
252
- | `activity` | title, description, status, primaryAmount, secondaryAmount | padding, leadingGap, lineGap, trailingGap, image |
252
+ | `activity` | title, description, status, primaryAmount, secondaryAmount | padding, leadingGap, lineGap, titleBadgeGap, trailingGap, image |
253
253
  | `message` | title, body, time | padding, leadingGap, lineGap, image |
254
254
  | `dataRow` | columns, columnSecondary, index | padding, leadingGap, lineGap, titleBadgeGap, image |
255
255
  | `market` | title, subtitle, price, change | padding, leadingGap, lineGap, titleBadgeGap, trailingGap, image; Market-specific properties below |
@@ -265,7 +265,9 @@ its existing template-specific style surface on every platform.
265
265
 
266
266
  Gap meanings are structural: `leadingGap` separates the primary visual from
267
267
  content; `lineGap` separates content text rows (primary/secondary per data column);
268
- `titleBadgeGap` separates a title and its badges (vertical for walletSidebar);
268
+ `titleBadgeGap` separates a title and its badges (vertical for walletSidebar;
269
+ for activity, the native failure label or rich title badges; Web has no activity
270
+ badge target);
269
271
  `trailingGap` separates trailing values/controls (title/badge to status for rail).
270
272
  `walletGroup` padding applies only to the group; it never cascades into members.
271
273
  Composite metric-card `lineGap` separates heading/metric blocks and dividers; it
@@ -49,25 +49,87 @@ final class NativeListActivityDetailsView: UIStackView {
49
49
  }
50
50
  required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
51
51
 
52
+ private static let sizingButton: UIButton = {
53
+ let button = UIButton(type: .system)
54
+ button.titleLabel?.font = nativeListFont(ofSize: 14, weight: .medium)
55
+ button.contentEdgeInsets = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)
56
+ return button
57
+ }()
58
+
59
+ /// Mirrors bind(): the same resolved texts, stack spacings and column widths, so the
60
+ /// automatic height matches the rendered stacks.
52
61
  static func measure(_ data: [String: Any], width: CGFloat) -> CGFloat {
53
62
  let style = data.dictionary("style") ?? [:]
54
- let primary = style.dictionary("primaryAmount") ?? [:]
55
- let secondary = style.dictionary("secondaryAmount") ?? [:]
56
- let rows = data.dictionaries("amounts")
57
- let gap = CGFloat(style.double("trailingGap", default: 2))
58
- let amountsHeight = rows.reduce(CGFloat(0)) { height, row in
59
- height + CGFloat(primary.double("lineHeight", default: 24)) +
60
- (row.string("secondaryText").isEmpty ? 0 : CGFloat(secondary.double("lineHeight", default: 20)))
61
- } + CGFloat(max(0, rows.count - 1)) * gap
62
- let titleHeight = CGFloat(style.dictionary("title")?.double("lineHeight", default: 24) ?? 24)
63
+ let table = data.string("presentation") == "table"
64
+ let image = style.dictionary("image") ?? [:]
65
+ let horizontalPadding = CGFloat(style.double("horizontalPadding", default: table ? 16 : 12))
66
+ let verticalPadding = CGFloat(style.double("verticalPadding", default: 8))
67
+ let lineGap = CGFloat(style.double("lineGap"))
68
+ let gap = CGFloat(style.double("leadingGap", default: 12))
69
+ let imageWidth = CGFloat(image.double("width", default: 40))
70
+ let imageHeight = CGFloat(image.double("height", default: 40))
71
+ let mainWidth = max(0, width - horizontalPadding * 2)
72
+
73
+ let amounts = data.dictionaries("amounts").map { amount -> (width: CGFloat, height: CGFloat) in
74
+ let primary = NativeListResolvedText(amount.string("text"), style: style.dictionary("primaryAmount"),
75
+ size: 16, weight: .medium, color: .label, lineHeight: 24, lines: 1, tabular: true)
76
+ let secondary = NativeListResolvedText(amount.string("secondaryText"), style: style.dictionary("secondaryAmount"),
77
+ size: 14, color: .label, lineHeight: 20, lines: 1)
78
+ let visual: CGFloat = amount.dictionary("leading") == nil ? 0 : 20
79
+ return (
80
+ (visual > 0 ? visual + 6 : 0) + max(primary.measureWidth(), secondary.measureWidth()),
81
+ max(visual, primary.measure(width: .greatestFiniteMagnitude) + secondary.measure(width: .greatestFiniteMagnitude))
82
+ )
83
+ }
84
+ let amountsGap = CGFloat(style.double("trailingGap", default: 2))
85
+ let amountsHeight = amounts.reduce(CGFloat(0)) { $0 + $1.height } + CGFloat(max(0, amounts.count - 1)) * amountsGap
86
+ let amountsWidth = amounts.map(\.width).max() ?? 0
87
+
88
+ var feeWidth: CGFloat = 0
89
+ var feeHeight: CGFloat = 0
90
+ if let feeData = data.dictionary("fee") {
91
+ let secondaryStyle = style.dictionary("secondaryAmount")
92
+ let label = NativeListResolvedText(feeData.string("label"), style: secondaryStyle, size: 12, color: .label, lineHeight: 16, lines: 1)
93
+ let primary = NativeListResolvedText(feeData.string("primary"), style: secondaryStyle, size: 14, color: .label, lineHeight: 20, lines: 1)
94
+ let secondary = NativeListResolvedText(feeData.string("secondary"), style: secondaryStyle, size: 12, color: .label, lineHeight: 16, lines: 1)
95
+ let lineWidth = primary.measureWidth() + secondary.measureWidth() +
96
+ (primary.text.isEmpty || secondary.text.isEmpty ? 0 : 4)
97
+ feeWidth = max(label.measureWidth(), lineWidth)
98
+ feeHeight = label.measure(width: .greatestFiniteMagnitude) +
99
+ max(primary.measure(width: .greatestFiniteMagnitude), secondary.measure(width: .greatestFiniteMagnitude))
100
+ }
101
+ let feeColumn = data.dictionary("fee") == nil ? 0 : gap + feeWidth
102
+ let identityWidth: CGFloat
103
+ if table {
104
+ let shared = (mainWidth - imageWidth - gap * 2 - feeColumn) / 2
105
+ identityWidth = min(mainWidth * 0.42, shared)
106
+ } else {
107
+ identityWidth = mainWidth - imageWidth - gap * 2 - feeColumn - min(amountsWidth, mainWidth * 0.5)
108
+ }
109
+
110
+ let title = NativeListResolvedText(data.string("title"), style: style.dictionary("title"), size: 16,
111
+ weight: .medium, color: .label, lineHeight: 24, lines: 1)
112
+ let titleHeight = max(
113
+ title.measure(width: .greatestFiniteMagnitude),
114
+ data.dictionaries("badges").isEmpty ? 0 : 16)
63
115
  let description = NativeListResolvedText(data.string("description"), style: style.dictionary("description"),
64
116
  size: 14, color: .label, lineHeight: 20, lines: 2)
65
- let identityHeight = titleHeight + description.measure(width: max(1, width * 0.4 - 52)) +
66
- (data.string("status").isEmpty ? 0 : 16)
67
- let imageHeight = CGFloat(style.dictionary("image")?.double("height", default: 40) ?? 40)
68
- return max(imageHeight, identityHeight, amountsHeight) +
69
- CGFloat(style.double("verticalPadding", default: 8)) * 2 +
70
- (data.dictionaries("footerActions").isEmpty ? 0 : 40)
117
+ let status = NativeListResolvedText(data.string("status"), style: style.dictionary("status"),
118
+ size: 12, color: .label, lineHeight: 16, lines: 1)
119
+ var identityHeight = titleHeight
120
+ for text in [description, status] where !text.text.isEmpty {
121
+ identityHeight += lineGap + text.measure(width: max(1, identityWidth))
122
+ }
123
+
124
+ var actionsHeight: CGFloat = 0
125
+ let actions = data.dictionaries("footerActions")
126
+ if !actions.isEmpty {
127
+ actionsHeight = actions.reduce(CGFloat(0)) { height, action in
128
+ sizingButton.setTitle(action.string("label"), for: .normal)
129
+ return max(height, ceil(sizingButton.intrinsicContentSize.height))
130
+ } + 8
131
+ }
132
+ return max(imageHeight, identityHeight, amountsHeight, feeHeight) + actionsHeight + verticalPadding * 2
71
133
  }
72
134
 
73
135
  func bind(_ item: NativeListItem, theme: [String: Any]?) {
@@ -10,11 +10,16 @@ private final class NativeListPausedVideoView: UIView {
10
10
  override func layoutSubviews() { super.layoutSubviews(); onLayoutChanged?() }
11
11
  }
12
12
 
13
- /// Uses the same AVPlayer source semantics as native Video, always paused and muted.
13
+ /// Uses the same AVPlayer source semantics as native Video, always paused and muted. A player
14
+ /// lives only until its first frame is copied; the tile then shows that still frame.
14
15
  final class NativeListMediaPreviewSlot {
15
16
  let view = UIView()
16
17
  private let image = NativeListImageSlot()
17
18
  private let video = NativeListPausedVideoView()
19
+ private let frameView = UIImageView()
20
+ private var videoOutput: AVPlayerItemVideoOutput?
21
+ private static let frameContext = CIContext(options: [.cacheIntermediates: false])
22
+ private static let frameCaptureAttempts = 6
18
23
  private var identity: String?
19
24
  private var epoch = 0
20
25
  private var candidateGeneration = 0
@@ -37,6 +42,10 @@ final class NativeListMediaPreviewSlot {
37
42
  }
38
43
  video.clipsToBounds = true
39
44
  video.isHidden = true
45
+ frameView.frame = video.bounds
46
+ frameView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
47
+ frameView.isHidden = true
48
+ video.addSubview(frameView)
40
49
  video.onWindowChanged = { [weak self] in self?.observeViewport(); self?.updateVisibility() }
41
50
  video.onLayoutChanged = { [weak self] in self?.updateVisibility() }
42
51
  lifecycleObservers = [
@@ -63,7 +72,9 @@ final class NativeListMediaPreviewSlot {
63
72
  recycle()
64
73
  identity = next
65
74
  self.completion = completion
66
- video.playerLayer.videoGravity = (fit ?? source.string("contentFit")) == "cover" ? .resizeAspectFill : .resizeAspect
75
+ let cover = (fit ?? source.string("contentFit")) == "cover"
76
+ video.playerLayer.videoGravity = cover ? .resizeAspectFill : .resizeAspect
77
+ frameView.contentMode = cover ? .scaleAspectFill : .scaleAspectFit
67
78
  probe(source, key: key, fit: fit, placeholder: placeholder, order: probeOrder, attempt: 0, token: epoch)
68
79
  }
69
80
 
@@ -109,6 +120,11 @@ final class NativeListMediaPreviewSlot {
109
120
  let asset = AVURLAsset(url: url, options: ["AVURLAssetHTTPHeaderFieldsKey": source.dictionary("headers") ?? [:]])
110
121
  let item = AVPlayerItem(asset: asset)
111
122
  item.preferredForwardBufferDuration = 1
123
+ let output = AVPlayerItemVideoOutput(pixelBufferAttributes: [
124
+ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
125
+ ])
126
+ item.add(output)
127
+ self.videoOutput = output
112
128
  let player = AVPlayer(playerItem: item)
113
129
  player.isMuted = true
114
130
  player.pause()
@@ -123,7 +139,9 @@ final class NativeListMediaPreviewSlot {
123
139
  self.readyObservation = self.video.playerLayer.observe(\.isReadyForDisplay, options: [.initial, .new]) { [weak self] layer, _ in
124
140
  DispatchQueue.main.async {
125
141
  guard let self, self.playerGeneration == generation else { return }
126
- if layer.isReadyForDisplay { finished(true) }
142
+ guard layer.isReadyForDisplay else { return }
143
+ finished(true)
144
+ self.captureFirstFrame(generation: generation, attemptsLeft: Self.frameCaptureAttempts)
127
145
  }
128
146
  }
129
147
  }
@@ -131,6 +149,42 @@ final class NativeListMediaPreviewSlot {
131
149
  updateVisibility()
132
150
  }
133
151
 
152
+ /// A paused item may not have handed its preroll frame to the output yet, so copying retries
153
+ /// on later runloop turns. If no frame arrives the paused player stays attached.
154
+ private func captureFirstFrame(generation: Int, attemptsLeft: Int) {
155
+ guard playerGeneration == generation, let player, let item = player.currentItem, let output = videoOutput else { return }
156
+ let time = item.currentTime()
157
+ if let buffer = output.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil),
158
+ let still = Self.frameContext.createCGImage(CIImage(cvPixelBuffer: buffer), from: CGRect(
159
+ x: 0, y: 0, width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer))) {
160
+ let transform = item.tracks.lazy.compactMap(\.assetTrack).first { $0.mediaType == .video }?.preferredTransform
161
+ frameView.image = UIImage(cgImage: still, scale: 1, orientation: Self.orientation(transform))
162
+ frameView.isHidden = false
163
+ resumeVideo = nil
164
+ viewportObservations.removeAll()
165
+ releasePlayer()
166
+ return
167
+ }
168
+ guard attemptsLeft > 1 else { return }
169
+ // An exact seek re-delivers the paused preroll frame to newly attached outputs.
170
+ if attemptsLeft == Self.frameCaptureAttempts {
171
+ player.seek(to: time, toleranceBefore: .zero, toleranceAfter: .zero)
172
+ }
173
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
174
+ self?.captureFirstFrame(generation: generation, attemptsLeft: attemptsLeft - 1)
175
+ }
176
+ }
177
+
178
+ private static func orientation(_ transform: CGAffineTransform?) -> UIImage.Orientation {
179
+ guard let transform else { return .up }
180
+ switch (transform.a, transform.b, transform.c, transform.d) {
181
+ case (0, 1, -1, 0): return .right
182
+ case (0, -1, 1, 0): return .left
183
+ case (-1, 0, 0, -1): return .down
184
+ default: return .up
185
+ }
186
+ }
187
+
134
188
  private func observeViewport() {
135
189
  viewportObservations.removeAll()
136
190
  guard resumeVideo != nil, video.window != nil else { return }
@@ -149,6 +203,9 @@ final class NativeListMediaPreviewSlot {
149
203
  }
150
204
  }
151
205
 
206
+ var hasLivePlayer: Bool { player != nil }
207
+ var capturedFrame: UIImage? { frameView.image }
208
+
152
209
  /// Retained pager pages can have a window while lying outside its clipped viewport.
153
210
  static func intersectsViewport(_ view: UIView) -> Bool {
154
211
  guard let window = view.window, !view.bounds.isEmpty else { return false }
@@ -173,6 +230,7 @@ final class NativeListMediaPreviewSlot {
173
230
  playerGeneration &+= 1
174
231
  itemObservation = nil
175
232
  readyObservation = nil
233
+ videoOutput = nil
176
234
  player?.pause()
177
235
  video.playerLayer.player = nil
178
236
  player?.replaceCurrentItem(with: nil)
@@ -187,6 +245,8 @@ final class NativeListMediaPreviewSlot {
187
245
  image.recycle()
188
246
  image.view.isHidden = false
189
247
  video.isHidden = true
248
+ frameView.image = nil
249
+ frameView.isHidden = true
190
250
  identity = nil
191
251
  result = nil
192
252
  completion = nil
@@ -104,6 +104,14 @@ struct NativeListResolvedText {
104
104
  return cache
105
105
  }()
106
106
 
107
+ /// Single-line natural width of the full-size text (subscript runs only make it narrower).
108
+ func measureWidth() -> CGFloat {
109
+ guard !text.isEmpty else { return 0 }
110
+ return ceil(attributed(direction: .leftToRight).boundingRect(
111
+ with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
112
+ options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).width)
113
+ }
114
+
107
115
  func measure(width: CGFloat) -> CGFloat {
108
116
  guard !text.isEmpty else { return 0 }
109
117
  let width = max(1, width)
@@ -6,21 +6,34 @@ import UniformTypeIdentifiers
6
6
  final class NativeListView: UIView {
7
7
  private var refreshEmittedForDrag = false
8
8
  private var minimumDragOffset: CGFloat = 0
9
- private var reactContainerSlots: [UIView] = []
10
9
  private var containerSlotHeights: [CGFloat] = [0, 0, 0]
10
+ // Fabric keeps assigning each slot root the frame React computed (inset, 0, width, height).
11
+ // Each root therefore lives in a list-owned host whose origin the list alone controls, so a
12
+ // React layout update can never move a slot out of its native position, even for a frame.
13
+ private var reactContainerSlots: [(content: UIView, host: UIView)] = []
11
14
  private var lastLaidOutContentHeight: CGFloat?
12
15
  private var needsContentShrinkCorrection = false
13
16
  private var contentShrinkCorrectionScheduled = false
14
17
 
15
18
  @objc func mountContainerSlot(_ view: UIView, atIndex index: Int) {
16
- reactContainerSlots.insert(view, at: min(index, reactContainerSlots.count))
17
- collectionView.addSubview(view)
19
+ let host = UIView()
20
+ // Clipping to the reported height keeps new content from overlapping rows until the list
21
+ // has reserved space for it.
22
+ host.clipsToBounds = true
23
+ host.addSubview(view)
24
+ reactContainerSlots.insert((view, host), at: min(index, reactContainerSlots.count))
25
+ collectionView.addSubview(host)
26
+ layoutContainerSlots()
18
27
  setNeedsLayout()
19
28
  }
20
29
 
21
30
  @objc func unmountContainerSlot(_ view: UIView) {
22
- reactContainerSlots.removeAll { $0 === view }
23
- view.removeFromSuperview()
31
+ reactContainerSlots.removeAll { slot in
32
+ guard slot.content === view else { return false }
33
+ view.removeFromSuperview()
34
+ slot.host.removeFromSuperview()
35
+ return true
36
+ }
24
37
  }
25
38
 
26
39
  func setContainerSlotHeightsJson(_ json: String) {
@@ -29,11 +42,11 @@ final class NativeListView: UIView {
29
42
  heights.count == 3, heights.allSatisfy({ $0.isFinite && $0 >= 0 }) else { return }
30
43
  containerSlotHeights = heights.map { CGFloat($0) }
31
44
  if let config { configureLayout(config) }
45
+ layoutContainerSlots()
32
46
  setNeedsLayout()
33
47
  }
34
48
 
35
49
  private func layoutContainerSlots() {
36
- guard reactContainerSlots.count == 3 else { return }
37
50
  let empty = config?.items.isEmpty ?? true
38
51
  let header = containerSlotHeights[0]
39
52
  let emptyHeight = empty ? containerSlotHeights[1] : 0
@@ -43,12 +56,11 @@ final class NativeListView: UIView {
43
56
  let footerY = max(paddingTop + header + emptyHeight,
44
57
  collectionView.contentSize.height - paddingBottom - footer)
45
58
  let positions = [paddingTop, paddingTop + header, footerY]
46
- for (index, view) in reactContainerSlots.enumerated() {
47
- view.isHidden = index == 1 && !empty
48
- let horizontalPadding = config?.contentPaddingHorizontal ?? 0
49
- view.frame = CGRect(x: horizontalPadding, y: positions[index],
50
- width: max(0, collectionView.bounds.width - horizontalPadding * 2),
51
- height: containerSlotHeights[index])
59
+ for (index, slot) in reactContainerSlots.prefix(3).enumerated() {
60
+ slot.host.isHidden = index == 1 && !empty
61
+ // React places the root at the horizontal inset inside this full-width host.
62
+ slot.host.frame = CGRect(x: 0, y: positions[index],
63
+ width: collectionView.bounds.width, height: containerSlotHeights[index])
52
64
  }
53
65
  }
54
66
 
@@ -40,4 +40,58 @@ final class NativeListActivityPresentationTests: XCTestCase {
40
40
  XCTAssertEqual(countBaseline?.doubleValue ?? 0, baseline?.doubleValue ?? 0)
41
41
  }
42
42
  }
43
+
44
+ func testAutomaticHeightMatchesRenderedStacks() throws {
45
+ let amount: [String: Any] = ["key": "send", "text": "-0.5 ETH", "secondaryText": "$1,000.00"]
46
+ let cases: [(String, [String: Any])] = [
47
+ ("stacked single-line", [
48
+ "presentation": "stacked", "description": "Jan 1 • 0x1234…abcd", "amounts": [amount],
49
+ "style": ["horizontalPadding": 20, "verticalPadding": 12, "lineGap": 0,
50
+ "title": ["fontSize": 16, "lineHeight": 24, "fontWeight": "medium", "lines": 1],
51
+ "description": ["fontSize": 14, "lineHeight": 20, "lines": 1]],
52
+ ]),
53
+ ("table line gap without secondary amount", [
54
+ "presentation": "table", "description": "0x1234…abcd",
55
+ "amounts": [["key": "approve", "text": "Unlimited USDC"]],
56
+ "fee": ["label": "Network fee", "primary": "0.0001 ETH", "secondary": "$0.20"],
57
+ "badges": [["key": "risk", "text": "Scam", "tone": "danger"]],
58
+ "style": ["horizontalPadding": 20, "verticalPadding": 12, "lineGap": 4,
59
+ "title": ["fontSize": 14, "lineHeight": 20, "fontWeight": "medium", "lines": 1],
60
+ "description": ["fontSize": 14, "lineHeight": 20, "lines": 1]],
61
+ ]),
62
+ ("wrapped description, status and actions", [
63
+ "description": String(repeating: "Contract interaction with a long label ", count: 3),
64
+ "status": "Pending", "amounts": [amount, ["key": "receive", "text": "+1 USDC"]],
65
+ "footerActions": [["key": "speedUp", "label": "Speed up"], ["key": "cancel", "label": "Cancel"]],
66
+ "style": ["lineGap": 6],
67
+ ]),
68
+ ]
69
+ for (name, fields) in cases {
70
+ var data: [String: Any] = [
71
+ "type": "activity", "key": name, "title": "Send",
72
+ "leading": ["kind": "icon", "name": "ArrowTopOutline"],
73
+ ]
74
+ fields.forEach { data[$0.key] = $0.value }
75
+ let item = try NativeListItem(data: data)
76
+ let width: CGFloat = 390
77
+ let style = data["style"] as? [String: Any] ?? [:]
78
+ let table = data["presentation"] as? String == "table"
79
+ let horizontal = CGFloat(style.double("horizontalPadding", default: table ? 16 : 12))
80
+ let vertical = CGFloat(style.double("verticalPadding", default: 8))
81
+ let container = UIView(frame: CGRect(x: 0, y: 0, width: width - horizontal * 2, height: 1000))
82
+ let view = NativeListActivityDetailsView()
83
+ view.translatesAutoresizingMaskIntoConstraints = false
84
+ container.addSubview(view)
85
+ NSLayoutConstraint.activate([
86
+ view.leadingAnchor.constraint(equalTo: container.leadingAnchor),
87
+ view.trailingAnchor.constraint(equalTo: container.trailingAnchor),
88
+ view.topAnchor.constraint(equalTo: container.topAnchor),
89
+ ])
90
+ view.bind(item, theme: nil)
91
+ container.layoutIfNeeded()
92
+ container.layoutIfNeeded()
93
+ let rendered = ceil(view.frame.height) + vertical * 2
94
+ XCTAssertEqual(NativeListActivityDetailsView.measure(data, width: width), rendered, accuracy: 1, name)
95
+ }
96
+ }
43
97
  }
@@ -175,6 +175,34 @@ final class NativeListLifecycleTests: XCTestCase {
175
175
  XCTAssertEqual(list.contentOffset.y, maximum, accuracy: 0.5)
176
176
  }
177
177
 
178
+ func testReactSlotFramesCannotMoveSlotsOutOfNativePlacement() throws {
179
+ let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
180
+ // Fabric assigns each root the frame React computed: horizontal inset, top 0.
181
+ let slots = (0..<3).map { _ in UIView(frame: CGRect(x: 16, y: 0, width: 288, height: 44)) }
182
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
183
+ view.applySnapshotJson(try scrollingSnapshot(count: 3))
184
+ view.layoutIfNeeded()
185
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
186
+ list.layoutIfNeeded()
187
+ let header = try XCTUnwrap(slots[0].superview)
188
+ XCTAssertTrue(header.clipsToBounds)
189
+ XCTAssertEqual(header.bounds.height, 0, "An unmeasured header cannot draw over the first rows")
190
+
191
+ view.setContainerSlotHeightsJson("[44,44,60]")
192
+ view.layoutIfNeeded()
193
+ list.layoutIfNeeded()
194
+ XCTAssertEqual(slots[0].convert(CGPoint.zero, to: list), CGPoint(x: 16, y: 0))
195
+ let footerY = 44 + 3 * 80 as CGFloat
196
+ XCTAssertEqual(slots[2].convert(CGPoint.zero, to: list).y, footerY)
197
+ // A React height update rewrites the root frame before the new height reaches native.
198
+ slots[2].frame = CGRect(x: 16, y: 0, width: 288, height: 90)
199
+ XCTAssertEqual(slots[2].convert(CGPoint.zero, to: list), CGPoint(x: 16, y: footerY))
200
+ XCTAssertTrue(slots[1].superview?.isHidden == true, "The empty slot stays hidden with rows")
201
+
202
+ view.unmountContainerSlot(slots[2])
203
+ XCTAssertNil(slots[2].superview)
204
+ }
205
+
178
206
  private func makeScrollingList() throws -> NativeListView {
179
207
  let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
180
208
  for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
@@ -40,3 +40,70 @@ final class NativeListMediaVisibilityTests: XCTestCase {
40
40
  XCTAssertFalse(NativeListMediaPreviewSlot.intersectsViewport(tile))
41
41
  }
42
42
  }
43
+
44
+ @MainActor
45
+ final class NativeListMediaFrameCaptureTests: XCTestCase {
46
+ func testVisibleVideoReleasesPlayerAfterCapturingFirstFrame() throws {
47
+ let url = try writeVideo()
48
+ defer { try? FileManager.default.removeItem(at: url) }
49
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
50
+ window.rootViewController = UIViewController()
51
+ window.isHidden = false
52
+ defer { window.isHidden = true }
53
+ let slot = NativeListMediaPreviewSlot()
54
+ slot.view.frame = CGRect(x: 0, y: 0, width: 120, height: 120)
55
+ window.rootViewController?.view.addSubview(slot.view)
56
+ slot.view.layoutIfNeeded()
57
+
58
+ var loaded: Bool?
59
+ slot.bind(["uri": url.absoluteString], key: "video", probeOrder: ["video"]) { loaded = $0 }
60
+ XCTAssertTrue(slot.hasLivePlayer, "A visible tile starts one paused player")
61
+ let deadline = Date().addingTimeInterval(10)
62
+ while slot.capturedFrame == nil, Date() < deadline {
63
+ RunLoop.main.run(until: Date().addingTimeInterval(0.05))
64
+ }
65
+ XCTAssertEqual(loaded, true)
66
+ let frame = try XCTUnwrap(slot.capturedFrame, "The first frame replaces the live player")
67
+ XCTAssertEqual(frame.size, CGSize(width: 64, height: 48))
68
+ XCTAssertFalse(slot.hasLivePlayer)
69
+
70
+ // Leaving and re-entering the viewport keeps the still without rebuilding a player.
71
+ slot.view.removeFromSuperview()
72
+ window.rootViewController?.view.addSubview(slot.view)
73
+ slot.bind(["uri": url.absoluteString], key: "video", probeOrder: ["video"])
74
+ XCTAssertFalse(slot.hasLivePlayer)
75
+ XCTAssertNotNil(slot.capturedFrame)
76
+ slot.recycle()
77
+ XCTAssertNil(slot.capturedFrame)
78
+ }
79
+
80
+ /// A 64×48, ten-frame H.264 MP4 (generated with AVAssetWriter on macOS); the simulator
81
+ /// has no reliable H.264 encoder for writing one at test time.
82
+ private static let videoBase64 = [
83
+ "AAAAHGZ0eXBtcDQyAAAAAWlzb21tcDQxbXA0MgAAAAFtZGF0AAAAAAAAAXQAAAA1BgUtR1ZK3FxMQz+U78URPNFDqAEAAAMA",
84
+ "AQMAAAMAAQIAAeYACwAAAwAAAwAArDoMA5ErAYAAAAA8JbggH94I5Uz/gak9b71ouT+PwABUezojLMLPpBfbqJ15oD1BM5L2",
85
+ "vvLSFvvy+AABSCrnn2hX8nKgIiU0AAAAHSHhEF/Eku94/c0JBdrVAqcS2Y43GYAJD/p9QzWAAAAAGSGogoS/nFT7cZbZ8xnp",
86
+ "PB3mw6AB/xojtyEAAAAXAajBj/+nyteRkHQKsy3f1gAFJajGDXAAAAAVAajDj/9TDF3o0LWPJnRoAJ7STV8lAAAAGSHjIaIl",
87
+ "/wHKBDW4y227MDl54AH+VxDvqGgAAAAUIakGhL9JSwD9lXLr+gAf8c7Z0iAAAAATAalFiT9cnuAKgJxY0AGV0YL85AAAABEB",
88
+ "qUeJP1ye5zMOKAAol0Uv0AAAABQh5SWiJf8BygQQ1yj2ACX52k6mwAAAA0xtb292AAAAbG12aGQAAAAA5uAsIObgLCAAAAJY",
89
+ "AAACWAABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAA",
90
+ "AAAAAAAAAAAAAAACAAAC2HRyYWsAAABcdGtoZAAAAAHm4Cwg5uAsIAAAAAEAAAAAAAACWAAAAAAAAAAAAAAAAAAAAAAAAQAA",
91
+ "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAQAAAADAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAlgAAAB4",
92
+ "AAEAAAAAAlBtZGlhAAAAIG1kaGQAAAAA5uAsIObgLCAAAAJYAAACWFXEAAAAAAAxaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAA",
93
+ "AAAAAENvcmUgTWVkaWEgVmlkZW8AAAAB921pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAA",
94
+ "AQAAAAx1cmwgAAAAAQAAAbdzdGJsAAAAoXN0c2QAAAAAAAAAAQAAAJFhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAEAA",
95
+ "MABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAJ2F2Y0MBZAAL/+EADCdkAAus",
96
+ "VlDDeBBhlAEABCjuPLD9+PgAAAAACmZpZWwBAAAAAApjaHJtAAAAAAAYc3R0cwAAAAAAAAABAAAACgAAADwAAABgY3R0cwAA",
97
+ "AAAAAAAKAAAAAQAAAHgAAAABAAABLAAAAAEAAAB4AAAAAQAAAAAAAAABAAAAPAAAAAEAAAEsAAAAAQAAAHgAAAABAAAAAAAA",
98
+ "AAEAAAA8AAAAAQAAAHgAAAAUc3RzcwAAAAAAAAABAAAAAQAAABZzZHRwAAAAACAQEBgYEBAYGBAAAAAcc3RzYwAAAAAAAAAB",
99
+ "AAAAAQAAAAoAAAABAAAAPHN0c3oAAAAAAAAAAAAAAAoAAAB5AAAAIQAAAB0AAAAbAAAAGQAAAB0AAAAYAAAAFwAAABUAAAAY",
100
+ "AAAAFHN0Y28AAAAAAAAAAQAAACw=",
101
+ ].joined()
102
+
103
+ private func writeVideo() throws -> URL {
104
+ let url = FileManager.default.temporaryDirectory
105
+ .appendingPathComponent("native-list-frame-\(UUID().uuidString).mp4")
106
+ try XCTUnwrap(Data(base64Encoded: Self.videoBase64)).write(to: url)
107
+ return url
108
+ }
109
+ }
@@ -16,7 +16,7 @@ export const ROW_BOX_STYLE_KEYS_BY_TYPE = {
16
16
  identity: ['horizontalPadding', 'verticalPadding', 'leadingGap', 'lineGap', 'titleBadgeGap', 'trailingGap', 'image'],
17
17
  walletGroup: ['horizontalPadding', 'verticalPadding'],
18
18
  rail: ['horizontalPadding', 'verticalPadding', 'leadingGap', 'titleBadgeGap', 'trailingGap', 'image'],
19
- activity: ['horizontalPadding', 'verticalPadding', 'leadingGap', 'lineGap', 'trailingGap', 'image'],
19
+ activity: ['horizontalPadding', 'verticalPadding', 'leadingGap', 'lineGap', 'titleBadgeGap', 'trailingGap', 'image'],
20
20
  message: ['horizontalPadding', 'verticalPadding', 'leadingGap', 'lineGap', 'image'],
21
21
  dataRow: ['horizontalPadding', 'verticalPadding', 'leadingGap', 'lineGap', 'titleBadgeGap', 'image'],
22
22
  market: ['horizontalPadding', 'verticalPadding', 'leadingGap', 'lineGap', 'titleBadgeGap', 'trailingGap', 'image'],
@@ -128,13 +128,13 @@ const TEXT_STYLE_KEYS_BY_ROW_TYPE = {
128
128
  identity: ['title', 'subtitle', 'tertiary', 'badge', 'value', 'valueSecondary'],
129
129
  walletGroup: [],
130
130
  rail: ['title', 'badge', 'status'],
131
- activity: ['title', 'description', 'status', 'amounts', 'badges', 'presentation', 'fee', 'descriptionActionKey', 'primaryAmount', 'secondaryAmount'],
131
+ activity: ['title', 'description', 'status', 'primaryAmount', 'secondaryAmount'],
132
132
  message: ['title', 'body', 'time'],
133
133
  dataRow: ['columns', 'columnSecondary', 'index'],
134
134
  market: ['title', 'subtitle', 'price', 'change'],
135
135
  mediaTile: ['title', 'subtitle', 'badge'],
136
136
  metricCard: ['title', 'value', 'subtitle', 'trend'],
137
- sectionHeader: ['titleLoading', 'title', 'subtitle', 'value'],
137
+ sectionHeader: ['title', 'subtitle', 'value'],
138
138
  action: ['title', 'value'],
139
139
  system: ['title', 'message', 'actionText']
140
140
  };
@@ -87,7 +87,7 @@ export declare const ROW_BOX_STYLE_KEYS_BY_TYPE: {
87
87
  readonly identity: readonly ["horizontalPadding", "verticalPadding", "leadingGap", "lineGap", "titleBadgeGap", "trailingGap", "image"];
88
88
  readonly walletGroup: readonly ["horizontalPadding", "verticalPadding"];
89
89
  readonly rail: readonly ["horizontalPadding", "verticalPadding", "leadingGap", "titleBadgeGap", "trailingGap", "image"];
90
- readonly activity: readonly ["horizontalPadding", "verticalPadding", "leadingGap", "lineGap", "trailingGap", "image"];
90
+ readonly activity: readonly ["horizontalPadding", "verticalPadding", "leadingGap", "lineGap", "titleBadgeGap", "trailingGap", "image"];
91
91
  readonly message: readonly ["horizontalPadding", "verticalPadding", "leadingGap", "lineGap", "image"];
92
92
  readonly dataRow: readonly ["horizontalPadding", "verticalPadding", "leadingGap", "lineGap", "titleBadgeGap", "image"];
93
93
  readonly market: readonly ["horizontalPadding", "verticalPadding", "leadingGap", "lineGap", "titleBadgeGap", "trailingGap", "image"];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-native-list",
3
- "version": "3.0.157-alpha.258",
3
+ "version": "3.0.157-alpha.262",
4
4
  "description": "Template-driven native RecyclerView and UICollectionView for React Native",
5
5
  "source": "./src/index.ts",
6
6
  "main": "./lib/module/index.js",
@@ -84,8 +84,8 @@
84
84
  "typescript": "^5.9.2"
85
85
  },
86
86
  "peerDependencies": {
87
- "@onekeyfe/react-native-image": "3.0.157-alpha.255",
88
- "@onekeyfe/react-native-native-logger": "3.0.157-alpha.255",
87
+ "@onekeyfe/react-native-image": "3.0.157-alpha.262",
88
+ "@onekeyfe/react-native-native-logger": "3.0.157-alpha.262",
89
89
  "react": "*",
90
90
  "react-native": "*",
91
91
  "react-native-nitro-modules": "0.37.0"
package/src/models.ts CHANGED
@@ -128,6 +128,7 @@ export const ROW_BOX_STYLE_KEYS_BY_TYPE = {
128
128
  'verticalPadding',
129
129
  'leadingGap',
130
130
  'lineGap',
131
+ 'titleBadgeGap',
131
132
  'trailingGap',
132
133
  'image',
133
134
  ],
package/src/validation.ts CHANGED
@@ -175,11 +175,6 @@ const TEXT_STYLE_KEYS_BY_ROW_TYPE: Readonly<
175
175
  'title',
176
176
  'description',
177
177
  'status',
178
- 'amounts',
179
- 'badges',
180
- 'presentation',
181
- 'fee',
182
- 'descriptionActionKey',
183
178
  'primaryAmount',
184
179
  'secondaryAmount',
185
180
  ],
@@ -188,7 +183,7 @@ const TEXT_STYLE_KEYS_BY_ROW_TYPE: Readonly<
188
183
  market: ['title', 'subtitle', 'price', 'change'],
189
184
  mediaTile: ['title', 'subtitle', 'badge'],
190
185
  metricCard: ['title', 'value', 'subtitle', 'trend'],
191
- sectionHeader: ['titleLoading', 'title', 'subtitle', 'value'],
186
+ sectionHeader: ['title', 'subtitle', 'value'],
192
187
  action: ['title', 'value'],
193
188
  system: ['title', 'message', 'actionText'],
194
189
  };