@onekeyfe/react-native-native-list 6.7.0-16 → 6.7.0-18

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.
Files changed (116) hide show
  1. package/android/src/main/java/com/onekey/nativelist/HybridNativeList.kt +14 -1
  2. package/android/src/main/java/com/onekey/nativelist/NativeListAccessoryStack.kt +240 -11
  3. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +7 -4
  4. package/android/src/main/java/com/onekey/nativelist/NativeListActivityRenderer.kt +6 -3
  5. package/android/src/main/java/com/onekey/nativelist/NativeListButtonGroupRenderer.kt +102 -0
  6. package/android/src/main/java/com/onekey/nativelist/NativeListContainerSlotAdapter.kt +12 -0
  7. package/android/src/main/java/com/onekey/nativelist/NativeListDataRowRenderer.kt +87 -7
  8. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +177 -1
  9. package/android/src/main/java/com/onekey/nativelist/NativeListLeadingVisual.kt +43 -14
  10. package/android/src/main/java/com/onekey/nativelist/NativeListMessageRenderer.kt +25 -0
  11. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +33 -2
  12. package/android/src/main/java/com/onekey/nativelist/NativeListPrimitives.kt +22 -0
  13. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRegistry.kt +2 -0
  14. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRowView.kt +2 -0
  15. package/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +3 -2
  16. package/android/src/main/java/com/onekey/nativelist/NativeListSectionHeaderRenderer.kt +69 -0
  17. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +55 -1
  18. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +1904 -43
  19. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +1 -0
  20. package/docs/ROW_TEMPLATES.md +60 -9
  21. package/docs/SPEC.md +445 -5
  22. package/docs/STYLE_SPEC.md +6 -0
  23. package/ios/HybridNativeList.swift +21 -2
  24. package/ios/NativeListAccessoryStack.swift +227 -39
  25. package/ios/NativeListActivityDetailsView.swift +18 -8
  26. package/ios/NativeListActivityRenderer.swift +8 -2
  27. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  28. package/ios/NativeListDataRowRenderer.swift +155 -27
  29. package/ios/NativeListDesignAssets.swift +3 -0
  30. package/ios/NativeListIdentityRenderer.swift +166 -30
  31. package/ios/NativeListLeadingVisual.swift +49 -14
  32. package/ios/NativeListMessageRenderer.swift +34 -1
  33. package/ios/NativeListModels.swift +42 -2
  34. package/ios/NativeListRendererRegistry.swift +1 -0
  35. package/ios/NativeListResolvedText.swift +2 -1
  36. package/ios/NativeListRowHost.swift +14 -0
  37. package/ios/NativeListSectionHeaderRenderer.swift +88 -0
  38. package/ios/RNCNativeListView.swift +1013 -55
  39. package/ios/Resources/NativeListIcons.xcassets/onekey_crypto_coin_outline.imageset/Contents.json +15 -0
  40. package/ios/Resources/NativeListIcons.xcassets/onekey_crypto_coin_outline.imageset/icon.svg +4 -0
  41. package/ios/Resources/NativeListIcons.xcassets/onekey_gas_solid.imageset/Contents.json +15 -0
  42. package/ios/Resources/NativeListIcons.xcassets/onekey_gas_solid.imageset/icon.svg +3 -0
  43. package/ios/Resources/NativeListIcons.xcassets/onekey_refresh_ccw_outline.imageset/Contents.json +15 -0
  44. package/ios/Resources/NativeListIcons.xcassets/onekey_refresh_ccw_outline.imageset/icon.svg +3 -0
  45. package/ios/tests/NativeListActivityPresentationTests.swift +56 -0
  46. package/ios/tests/NativeListLifecycleTests.swift +2651 -3
  47. package/lib/module/NativeList.js +175 -28
  48. package/lib/module/NativeList.web.js +108 -25
  49. package/lib/module/index.js +1 -1
  50. package/lib/module/models.js +1 -0
  51. package/lib/module/selection.js +1 -1
  52. package/lib/module/validation.js +421 -8
  53. package/lib/module/web/NativeListWebEngine.js +503 -18
  54. package/lib/module/web/templates/ActivityRowRenderer.js +8 -7
  55. package/lib/module/web/templates/ButtonGroupRowRenderer.js +47 -0
  56. package/lib/module/web/templates/DataRowRenderer.js +40 -5
  57. package/lib/module/web/templates/IdentityRowRenderer.js +90 -4
  58. package/lib/module/web/templates/MessageRowRenderer.js +18 -2
  59. package/lib/module/web/templates/RowContainerStyle.js +1 -0
  60. package/lib/module/web/templates/RowRendererRegistry.js +3 -0
  61. package/lib/module/web/templates/SectionHeaderRowRenderer.js +36 -2
  62. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  63. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  64. package/lib/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  65. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  66. package/lib/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  67. package/lib/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  68. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  69. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  70. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  71. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  72. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  73. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  74. package/lib/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  75. package/lib/typescript/src/NativeList.d.ts +1 -1
  76. package/lib/typescript/src/NativeList.nitro.d.ts +2 -0
  77. package/lib/typescript/src/NativeList.types.d.ts +18 -0
  78. package/lib/typescript/src/index.d.ts +2 -2
  79. package/lib/typescript/src/models.d.ts +105 -9
  80. package/lib/typescript/src/validation.d.ts +12 -0
  81. package/lib/typescript/src/web/NativeListWebEngine.d.ts +31 -0
  82. package/lib/typescript/src/web/templates/ButtonGroupRowRenderer.d.ts +14 -0
  83. package/lib/typescript/src/web/templates/IdentityRowRenderer.d.ts +1 -1
  84. package/lib/typescript/src/web/templates/MessageRowRenderer.d.ts +9 -3
  85. package/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  86. package/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  87. package/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  88. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  89. package/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  90. package/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  91. package/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  92. package/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  93. package/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  94. package/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  95. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  96. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  97. package/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  98. package/package.json +3 -3
  99. package/react-native-native-list.podspec +1 -0
  100. package/src/NativeList.nitro.ts +2 -0
  101. package/src/NativeList.tsx +313 -44
  102. package/src/NativeList.types.ts +22 -0
  103. package/src/NativeList.web.tsx +170 -39
  104. package/src/index.ts +2 -0
  105. package/src/models.ts +117 -3
  106. package/src/selection.ts +1 -0
  107. package/src/validation.ts +852 -6
  108. package/src/web/NativeListWebEngine.ts +798 -19
  109. package/src/web/templates/ActivityRowRenderer.ts +14 -6
  110. package/src/web/templates/ButtonGroupRowRenderer.ts +58 -0
  111. package/src/web/templates/DataRowRenderer.ts +93 -20
  112. package/src/web/templates/IdentityRowRenderer.ts +150 -5
  113. package/src/web/templates/MessageRowRenderer.ts +23 -7
  114. package/src/web/templates/RowContainerStyle.ts +2 -0
  115. package/src/web/templates/RowRendererRegistry.ts +11 -1
  116. package/src/web/templates/SectionHeaderRowRenderer.ts +47 -4
@@ -1,6 +1,9 @@
1
1
  package com.margelo.nitro.nativelist
2
2
 
3
3
  import android.animation.TimeInterpolator
4
+ import android.animation.ValueAnimator
5
+ import android.animation.Animator
6
+ import android.animation.AnimatorListenerAdapter
4
7
  import android.content.Context
5
8
  import android.graphics.Canvas
6
9
  import android.graphics.Color
@@ -11,6 +14,7 @@ import android.graphics.RectF
11
14
  import android.graphics.drawable.ShapeDrawable
12
15
  import android.graphics.drawable.shapes.PathShape
13
16
  import android.os.Bundle
17
+ import android.os.Build
14
18
  import android.os.Handler
15
19
  import android.os.Looper
16
20
  import android.os.SystemClock
@@ -32,6 +36,7 @@ import android.widget.TextView
32
36
  import androidx.core.view.ViewCompat
33
37
  import androidx.core.view.WindowInsetsCompat
34
38
  import androidx.recyclerview.widget.ConcatAdapter
39
+ import androidx.recyclerview.widget.DefaultItemAnimator
35
40
  import androidx.recyclerview.widget.GridLayoutManager
36
41
  import androidx.recyclerview.widget.ItemTouchHelper
37
42
  import androidx.recyclerview.widget.LinearLayoutManager
@@ -39,6 +44,8 @@ import androidx.recyclerview.widget.LinearSmoothScroller
39
44
  import androidx.recyclerview.widget.RecyclerView
40
45
  import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
41
46
  import com.facebook.react.uimanager.ThemedReactContext
47
+ import com.facebook.react.uimanager.PointerEvents
48
+ import com.facebook.react.uimanager.ReactPointerEventsView
42
49
  import com.margelo.nitro.nativelogger.OneKeyLog
43
50
  import org.json.JSONArray
44
51
  import org.json.JSONObject
@@ -105,6 +112,7 @@ class NativeListView(
105
112
 
106
113
  fun setFontFamiliesJson(json: String) {
107
114
  if (!fonts.configure(json)) return
115
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
108
116
  invalidateActionAnchor("layout")
109
117
  measuredRowExtentsPx.clear()
110
118
  measuredRowExtentSumPx = 0L
@@ -200,27 +208,242 @@ class NativeListView(
200
208
  var onReorder: ((String) -> Unit)? = null
201
209
  var onEndReached: ((String) -> Unit)? = null
202
210
  var onVisibleRangeChanged: ((String) -> Unit)? = null
211
+ var onStructuralTransitionSettled: ((String) -> Unit)? = null
203
212
  var keyboardDismissMode = NativeListKeyboardDismissMode.NONE
204
213
  var keyboardShouldPersistTaps = NativeListKeyboardShouldPersistTaps.NEVER
205
214
  private val density = resources.displayMetrics.density
206
- private val recyclerView = RecyclerView(context)
215
+ private val recyclerView = object : RecyclerView(context) {
216
+ override fun onMeasure(widthSpec: Int, heightSpec: Int) {
217
+ if (isLayoutSuppressed) {
218
+ setMeasuredDimension(measuredWidth, measuredHeight)
219
+ return
220
+ }
221
+ super.onMeasure(widthSpec, heightSpec)
222
+ }
223
+
224
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
225
+ if (isLayoutSuppressed) return
226
+ super.onLayout(changed, left, top, right, bottom)
227
+ }
228
+ }
207
229
  private var configuredTopPaddingPx = 0
208
230
  private var slotInsetPx = 0
231
+ private var slotRightInsetPx = 0
209
232
  private var configuredBottomPaddingPx = 0
233
+ private data class SidecarLayout(val width: Int, val gap: Int, val maxContentWidth: Int)
234
+ private var sidecarLayout: SidecarLayout? = null
235
+ private var sidecarSpacerHeightPx = 0
236
+ private var sidecarSpacerScheduled = false
237
+ private var consumedStructuralTransitionId: String? = null
238
+ private var structuralAnimator: ValueAnimator? = null
239
+ private var structuralSpacerHeightPx = 0
240
+ private var structuralTailSignedExtentPx = 0
241
+ private var structuralStartSpacerPx = 0
242
+ private var structuralFooterVisualStartTop: Int? = null
243
+ private var structuralFooterVisualEndTop: Int? = null
244
+ private var structuralFooterVisualProgress = 0f
245
+ private var structuralFooterCompensatedHeightPx: Int? = null
246
+ private var structuralFooterObservedNativeHeightPx: Int? = null
247
+ private var acceptedFooterNaturalHeightPx: Int? = null
248
+ private data class PendingPreparingFooterFrame(
249
+ val heights: IntArray,
250
+ val naturalHeight: Int,
251
+ val observedNativeHeight: Int?,
252
+ val ownerOffset: Int,
253
+ val epoch: Int,
254
+ val footer: View?,
255
+ val handoffOnly: Boolean,
256
+ )
257
+ private var pendingPreparingFooterFrame: PendingPreparingFooterFrame? = null
258
+ private var preparingFooterFrameScheduled = false
259
+ private var structuralScrollInterrupted = false
260
+ private var structuralFooterHoldTop: Int? = null
261
+ private var structuralTransitionEpoch = 0
262
+ private class StructuralTail(
263
+ var items: MutableList<NativeListItem>,
264
+ val heights: IntArray,
265
+ spacings: IntArray,
266
+ val prefixCount: Int,
267
+ val finalExtent: Int,
268
+ ) {
269
+ val starts = IntArray(items.size)
270
+ val indexByKey = items.withIndex().associate { it.value.key to it.index }
271
+ val hosts = mutableMapOf<Int, NativeListRowHost>()
272
+ var peakHosts = 0
273
+ val extent: Int
274
+ init {
275
+ var edge = 0
276
+ for (index in items.indices) {
277
+ starts[index] = edge
278
+ edge += heights[index] + spacings[index]
279
+ }
280
+ extent = edge
281
+ }
282
+ }
283
+ private val structuralTailLayer = object : FrameLayout(reactContext), ReactPointerEventsView {
284
+ override val pointerEvents: PointerEvents = PointerEvents.NONE
285
+ override fun dispatchTouchEvent(event: MotionEvent) = false
286
+ }.apply {
287
+ clipChildren = true
288
+ clipToPadding = true
289
+ isClickable = false
290
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
291
+ visibility = GONE
292
+ }
293
+ private var structuralTail: StructuralTail? = null
294
+ private var structuralTailRowsInAdapterPx = 0
295
+ private var structuralTailStartExtentPx = 0
296
+ private var structuralTailStartProgress = 0f
297
+ private var structuralTailStartContentY = 0
298
+ private var structuralTailStartOffset = 0
299
+ private var structuralTailTargetOffset = 0
300
+ private var disclosureFraction = 0f
301
+ private var disclosureStartFraction = 0f
302
+ private var disclosurePresentedContentPx = 0
303
+ private var disclosurePresentedInsetPx = 0
304
+ private var disclosureContentStartPx = 0
305
+ private var disclosureContentStartProgress = 0f
306
+ private var disclosureTransitioning = false
307
+ private var activeDisclosureTransitionId: String? = null
308
+ private var settledDisclosureTransitionId: String? = null
309
+ private var directDisclosureStatus = "interrupted"
310
+ private var batchedDisclosureGeometryInvalid = false
311
+ private var structuralTailCommandActive = false
312
+ private var structuralTailFinalizing = false
313
+ private var structuralTailPreparing = false
314
+ private data class PendingStructuralTransition(
315
+ val transition: NativeListConfig.StructuralTransition,
316
+ val epoch: Int,
317
+ val anchorKey: String?,
318
+ val anchorTop: Int?,
319
+ val footerStartTop: Int?,
320
+ val heldHeightPx: Int,
321
+ val collapsing: Boolean,
322
+ val spacerInserted: Boolean = false,
323
+ val footerAnchorAppliedTop: Int? = null,
324
+ val rowAnchorAppliedTop: Int? = null,
325
+ )
326
+ private var pendingStructuralTransition: PendingStructuralTransition? = null
327
+ private var pendingStructuralStartScheduled = false
210
328
  private val refreshLayout = SwipeRefreshLayout(context)
211
329
  private val refreshIndicatorTravelPx = refreshLayout.progressViewEndOffset
212
330
  private val defaultRefreshTriggerDistancePx = (64 * resources.displayMetrics.density).roundToInt()
213
331
  private var refreshIndicatorOffsetPx = 0
214
332
  private val contentContainer = FrameLayout(context)
333
+ private val sidecarHost = object : FrameLayout(context) {
334
+ private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
335
+ private var down: MotionEvent? = null
336
+ private var routing = false
337
+
338
+ private fun route(event: MotionEvent) {
339
+ val copy = MotionEvent.obtain(event)
340
+ copy.offsetLocation(x - refreshLayout.x, y - refreshLayout.y)
341
+ refreshLayout.dispatchTouchEvent(copy)
342
+ copy.recycle()
343
+ }
344
+
345
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean {
346
+ when (event.actionMasked) {
347
+ MotionEvent.ACTION_DOWN -> {
348
+ down?.recycle()
349
+ down = MotionEvent.obtain(event)
350
+ routing = false
351
+ }
352
+ MotionEvent.ACTION_MOVE -> {
353
+ if (routing) {
354
+ route(event)
355
+ return true
356
+ }
357
+ val start = down
358
+ if (start != null && abs(event.y - start.y) > touchSlop &&
359
+ abs(event.y - start.y) > abs(event.x - start.x)) {
360
+ val cancel = MotionEvent.obtain(event)
361
+ cancel.action = MotionEvent.ACTION_CANCEL
362
+ super.dispatchTouchEvent(cancel)
363
+ cancel.recycle()
364
+ route(start)
365
+ route(event)
366
+ routing = true
367
+ return true
368
+ }
369
+ }
370
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
371
+ if (routing) route(event)
372
+ down?.recycle()
373
+ down = null
374
+ if (routing) {
375
+ routing = false
376
+ return true
377
+ }
378
+ }
379
+ else -> if (routing) {
380
+ route(event)
381
+ return true
382
+ }
383
+ }
384
+ return super.dispatchTouchEvent(event)
385
+ }
386
+ }
215
387
  private val adapter = NativeListAdapter(reactContext, fonts)
216
388
  private val containerSlots = mutableListOf<View>()
217
- private val slotHeights = IntArray(3)
389
+ private val slotHeights = IntArray(6)
390
+ private val expandedContentHost = object : FrameLayout(context), ReactPointerEventsView {
391
+ var naturalHeightPx = 0
392
+ override val pointerEvents: PointerEvents
393
+ get() = if (config?.disclosure?.expanded == true &&
394
+ !disclosureTransitioning && disclosureFraction >= 1f) PointerEvents.AUTO
395
+ else PointerEvents.NONE
396
+
397
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
398
+ setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
399
+ MeasureSpec.getSize(heightMeasureSpec))
400
+ }
401
+
402
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
403
+ getChildAt(0)?.layout(0, 0, right - left, naturalHeightPx)
404
+ }
405
+ }.apply {
406
+ clipChildren = true
407
+ clipToPadding = true
408
+ isClickable = false
409
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
410
+ }
411
+ private val footerPresentationHost = object : FrameLayout(context) {
412
+ var naturalHeightPx = 0
413
+ var hiddenTopPx = 0
414
+
415
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
416
+ setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
417
+ MeasureSpec.getSize(heightMeasureSpec))
418
+ }
419
+
420
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
421
+ val child = getChildAt(0) ?: return
422
+ child.layout(0, -hiddenTopPx, right - left, naturalHeightPx - hiddenTopPx)
423
+ }
424
+ }.apply {
425
+ clipChildren = true
426
+ clipToPadding = true
427
+ }
428
+ private var initialHeaderInsertionHandled = false
218
429
  private var containerSlotRelayoutPending = false
219
430
  private var containerSlotRelayoutScheduled = false
220
431
  private val headerSlotAdapter = NativeListContainerSlotAdapter()
221
432
  private val emptySlotAdapter = NativeListContainerSlotAdapter()
433
+ private val structuralSpacerView = View(context)
434
+ private val structuralSpacerAdapter = NativeListContainerSlotAdapter()
435
+ private val expandedContentAdapter = NativeListContainerSlotAdapter()
436
+ private val structureToggleAdapter = NativeListContainerSlotAdapter()
437
+ private val disclosureInsetView = View(context)
438
+ private val disclosureInsetAdapter = NativeListContainerSlotAdapter()
222
439
  private val footerSlotAdapter = NativeListContainerSlotAdapter()
223
- private val scrollContentAdapter = ConcatAdapter(headerSlotAdapter, adapter, emptySlotAdapter, footerSlotAdapter)
440
+ private val sidecarSpacerView = View(context)
441
+ private val sidecarSpacerAdapter = NativeListContainerSlotAdapter()
442
+ private val scrollContentAdapter = ConcatAdapter(
443
+ headerSlotAdapter, adapter, emptySlotAdapter, structuralSpacerAdapter,
444
+ expandedContentAdapter, structureToggleAdapter, disclosureInsetAdapter,
445
+ footerSlotAdapter, sidecarSpacerAdapter,
446
+ )
224
447
 
225
448
  private val homeOffsetDiagnosticEnabled =
226
449
  context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0
@@ -238,7 +461,8 @@ class NativeListView(
238
461
  headerSlotAdapter -> 0
239
462
  adapter -> 1
240
463
  emptySlotAdapter -> 2
241
- footerSlotAdapter -> 3
464
+ structuralSpacerAdapter -> 3
465
+ footerSlotAdapter -> 4
242
466
  else -> -1
243
467
  }
244
468
  val focused = recyclerView.findFocus()
@@ -248,7 +472,7 @@ class NativeListView(
248
472
  "seq=${++homeOffsetDiagnosticSequence} wallMs=${System.currentTimeMillis()} monoMs=${SystemClock.uptimeMillis()} " +
249
473
  "list=${System.identityHashCode(this)} view=${System.identityHashCode(recyclerView)} tag=$id " +
250
474
  "generation=${config?.generation} configuredCount=${config?.items?.size} " +
251
- "counts=${headerSlotAdapter.itemCount},${adapter.itemCount},${emptySlotAdapter.itemCount},${footerSlotAdapter.itemCount} " +
475
+ "counts=${headerSlotAdapter.itemCount},${adapter.itemCount},${emptySlotAdapter.itemCount},${structuralSpacerAdapter.itemCount},${footerSlotAdapter.itemCount} " +
252
476
  "total=${scrollContentAdapter.itemCount} pendingCommand=${pendingScrollRequest?.javaClass?.simpleName ?: "none"} " +
253
477
  "stateCount=${state?.itemCount} preLayout=${state?.isPreLayout} structureChanged=${state?.didStructureChange()} predictive=${state?.willRunPredictiveAnimations()} " +
254
478
  "first=$first last=${layoutManager.findLastVisibleItemPosition()} " +
@@ -277,23 +501,283 @@ class NativeListView(
277
501
  scheduleContainerSlotRelayout()
278
502
  }
279
503
 
280
- fun setContainerSlotHeightsJson(json: String) {
504
+ fun setContainerSlotHeightsJson(json: String, upcomingSnapshotJson: String? = null) {
281
505
  val values = runCatching { JSONArray(json) }.getOrNull() ?: return
282
- if (values.length() != 3) return
283
- for (index in 0..2) {
506
+ if (values.length() != 4 && values.length() != 6) return
507
+ val nextHeights = IntArray(6)
508
+ for (index in 0 until values.length()) {
284
509
  val value = values.optDouble(index)
285
510
  if (!value.isFinite() || value < 0) return
511
+ nextHeights[index] = (value * density).roundToInt()
512
+ }
513
+ val disclosureTail = structuralTail != null && config?.disclosure != null &&
514
+ !structuralTailFinalizing
515
+ if (disclosureTail && upcomingSnapshotJson != null &&
516
+ (nextHeights[2] != slotHeights[2] || nextHeights[5] != slotHeights[5] ||
517
+ nextHeights[4] < disclosurePresentedContentPx)) {
518
+ // Nitro delivers both setters in this UI turn. Let the complete new snapshot
519
+ // replace the old command before deciding whether its geometry is supported.
520
+ batchedDisclosureGeometryInvalid = true
521
+ for (index in 0..5) slotHeights[index] = nextHeights[index]
522
+ acceptedFooterNaturalHeightPx = nextHeights[2]
523
+ return
286
524
  }
525
+ val unsupportedDisclosureGeometry = disclosureTail &&
526
+ (nextHeights[2] != slotHeights[2] || nextHeights[5] != slotHeights[5] ||
527
+ nextHeights[4] < disclosurePresentedContentPx)
528
+ if (unsupportedDisclosureGeometry) {
529
+ // A changing fixed footer/toggle or a shrinking mounted C cannot be represented
530
+ // by the current visual segment. Commit the accepted endpoint before ACK.
531
+ structuralFooterCompensatedHeightPx = null
532
+ acceptedFooterNaturalHeightPx = nextHeights[2]
533
+ for (index in 0..5) slotHeights[index] = nextHeights[index]
534
+ updateContainerSlots()
535
+ finishStructuralTail(interrupted = true)
536
+ return
537
+ }
538
+ if (disclosureTail && nextHeights[4] != slotHeights[4]) {
539
+ disclosureContentStartPx = disclosurePresentedContentPx
540
+ disclosureContentStartProgress =
541
+ (structuralAnimator?.animatedValue as? Float) ?: 0f
542
+ }
543
+ if (structuralTail != null && structuralTailRowsInAdapterPx > 0 &&
544
+ listOf(0, 1, 3).all { slotHeights[it] == nextHeights[it] } &&
545
+ (pendingPreparingFooterFrame != null ||
546
+ (!structuralTailFinalizing && slotHeights[2] != nextHeights[2]))) {
547
+ enqueuePreparingFooterFrame(nextHeights, nextHeights[2])
548
+ return
549
+ }
550
+ pendingPreparingFooterFrame?.takeIf {
551
+ structuralTailRowsInAdapterPx > 0 && it.footer === containerSlots.getOrNull(2)
552
+ }?.let { pending ->
553
+ val preservesNewerHeight = nextHeights[2] == slotHeights[2] &&
554
+ pending.naturalHeight != nextHeights[2]
555
+ pendingPreparingFooterFrame = pending.copy(
556
+ heights = nextHeights.copyOf(),
557
+ naturalHeight = if (preservesNewerHeight) pending.naturalHeight else nextHeights[2],
558
+ observedNativeHeight = pending.observedNativeHeight.takeIf {
559
+ preservesNewerHeight || pending.naturalHeight == nextHeights[2]
560
+ },
561
+ )
562
+ }
563
+ if (structuralTailPreparing && (0..3).any { index ->
564
+ slotHeights[index] != nextHeights[index]
565
+ }) invalidateTailForContainerGeometry()
566
+ if (structuralTail != null && listOf(0, 1, 3).any { index ->
567
+ slotHeights[index] != nextHeights[index]
568
+ }) finishStructuralTail(interrupted = true)
569
+ val footerHeightPx = nextHeights[2]
570
+ if (footerHeightPx != slotHeights[2]) {
571
+ containerSlots.getOrNull(2)?.measuredHeight?.takeIf { it > 0 && it != footerHeightPx }
572
+ ?.let { structuralFooterObservedNativeHeightPx = it }
573
+ reconcileStructuralFooterHeight(footerHeightPx)
574
+ acceptedFooterNaturalHeightPx = footerHeightPx
575
+ } else if (acceptedFooterNaturalHeightPx == null) {
576
+ acceptedFooterNaturalHeightPx = footerHeightPx
577
+ }
578
+ val hiddenDisclosureContentOnlyChange = config?.disclosure?.expanded == false &&
579
+ !disclosureTransitioning && structuralTail == null &&
580
+ !structuralTailPreparing && !structuralTailFinalizing &&
581
+ disclosurePresentedContentPx == 0 && disclosurePresentedInsetPx == 0 &&
582
+ expandedContentAdapter.itemCount == 0 &&
583
+ slotHeights[4] != nextHeights[4] &&
584
+ (0..5).all { index -> index == 4 || slotHeights[index] == nextHeights[index] }
287
585
  var changed = false
288
- for (index in 0..2) {
289
- val height = (values.getDouble(index) * density).roundToInt()
586
+ for (index in 0..5) {
587
+ val height = nextHeights[index]
290
588
  if (slotHeights[index] != height) changed = true
291
589
  slotHeights[index] = height
292
590
  }
591
+ if (hiddenDisclosureContentOnlyChange) {
592
+ expandedContentHost.naturalHeightPx = slotHeights[4]
593
+ layoutExpandedContentHostNow()
594
+ return
595
+ }
293
596
  updateContainerSlots()
597
+ if (structuralTail != null) updateStructuralTailTarget()
598
+ updateSidecarGeometry()
599
+ scheduleSidecarSpacer()
294
600
  if (changed) scheduleContainerSlotRelayout()
295
601
  }
296
602
 
603
+ private fun enqueuePreparingFooterFrame(
604
+ heights: IntArray,
605
+ naturalHeight: Int,
606
+ observedNativeHeight: Int? = null,
607
+ ) {
608
+ val footer = containerSlots.getOrNull(2)
609
+ val existing = pendingPreparingFooterFrame?.takeIf { it.footer === footer }
610
+ val preservesNewerHeight = existing != null && observedNativeHeight == null &&
611
+ naturalHeight == slotHeights[2] && existing.naturalHeight != naturalHeight
612
+ val acceptedHeight = if (preservesNewerHeight) existing.naturalHeight else naturalHeight
613
+ val observedHeight = observedNativeHeight ?:
614
+ existing?.observedNativeHeight?.takeIf { preservesNewerHeight || it == acceptedHeight }
615
+ pendingPreparingFooterFrame = PendingPreparingFooterFrame(
616
+ heights.copyOf(), acceptedHeight, observedHeight,
617
+ existing?.ownerOffset ?: structuralTailStartOffset,
618
+ structuralTransitionEpoch, footer, existing?.handoffOnly == true,
619
+ )
620
+ if (!commitPreparingFooterFrame() && pendingPreparingFooterFrame?.handoffOnly != true) {
621
+ schedulePreparingFooterFrame()
622
+ }
623
+ }
624
+
625
+ private fun schedulePreparingFooterFrame() {
626
+ if (preparingFooterFrameScheduled) return
627
+ preparingFooterFrameScheduled = true
628
+ recyclerView.post {
629
+ preparingFooterFrameScheduled = false
630
+ if (!commitPreparingFooterFrame()) recyclerView.postInvalidateOnAnimation()
631
+ }
632
+ recyclerView.postInvalidateOnAnimation()
633
+ }
634
+
635
+ private fun reconcileStructuralFooterHeight(nextHeightPx: Int) {
636
+ if (structuralTail != null) {
637
+ if (!structuralTailFinalizing) {
638
+ val delta = (structuralFooterCompensatedHeightPx ?:
639
+ acceptedFooterNaturalHeightPx ?: slotHeights[2]) - nextHeightPx
640
+ if (delta != 0) {
641
+ if (structuralTailPreparing) {
642
+ invalidateTailForContainerGeometry()
643
+ return
644
+ }
645
+ structuralFooterCompensatedHeightPx = nextHeightPx
646
+ val compensated = structuralTailSignedExtentPx + delta
647
+ structuralTailStartProgress = (structuralAnimator?.animatedValue as? Float) ?: 0f
648
+ structuralTailStartExtentPx = compensated
649
+ if (structuralTailRowsInAdapterPx == 0) structuralTailStartOffset = tailScrollExtentPx()
650
+ setStructuralTailExtent(compensated)
651
+ if (structuralTailRowsInAdapterPx == 0) updateStructuralTailWindow()
652
+ }
653
+ }
654
+ return
655
+ }
656
+ val previousHeightPx = structuralFooterCompensatedHeightPx ?:
657
+ acceptedFooterNaturalHeightPx ?: slotHeights[2]
658
+ val footerDelta = previousHeightPx - nextHeightPx
659
+ if (footerDelta == 0) return
660
+ if (pendingStructuralTransition != null || structuralAnimator != null || structuralFooterHoldTop != null) {
661
+ structuralFooterCompensatedHeightPx = nextHeightPx
662
+ }
663
+ if (pendingStructuralTransition != null) {
664
+ pendingStructuralTransition = pendingStructuralTransition?.let {
665
+ val updated = it.copy(
666
+ footerStartTop = it.footerStartTop?.plus(footerDelta),
667
+ heldHeightPx = (it.heldHeightPx + footerDelta).coerceAtLeast(0),
668
+ )
669
+ if (updated.spacerInserted) setStructuralSpacerHeight(updated.heldHeightPx)
670
+ updated
671
+ }
672
+ structuralFooterHoldTop = structuralFooterHoldTop?.plus(footerDelta)
673
+ updateStructuralFooterHoldPosition()
674
+ } else if (structuralFooterHoldTop != null && structuralAnimator == null) {
675
+ setStructuralSpacerHeight(structuralSpacerHeightPx + footerDelta)
676
+ structuralFooterHoldTop = structuralFooterHoldTop?.plus(footerDelta)
677
+ updateStructuralFooterHoldPosition()
678
+ } else if (structuralAnimator != null) {
679
+ structuralStartSpacerPx = (structuralStartSpacerPx + footerDelta).coerceAtLeast(0)
680
+ structuralFooterVisualStartTop = structuralFooterVisualStartTop?.plus(footerDelta)
681
+ val fraction = (structuralAnimator?.animatedValue as? Float) ?: 0f
682
+ setStructuralSpacerHeight((structuralStartSpacerPx * (1f - fraction)).roundToInt())
683
+ updateStructuralFooterVisualPosition()
684
+ }
685
+ }
686
+
687
+ fun setSidecarLayoutJson(json: String) {
688
+ val next = if (json.isEmpty()) null else {
689
+ val value = runCatching { JSONObject(json) }.getOrNull() ?: return
690
+ val width = value.optDouble("width")
691
+ val gap = value.optDouble("gap")
692
+ val maxWidth = value.optDouble("maxContentWidth")
693
+ if (!width.isFinite() || width <= 0 || !gap.isFinite() || gap < 0 ||
694
+ !maxWidth.isFinite() || maxWidth <= width + gap) return
695
+ SidecarLayout((width * density).roundToInt(), (gap * density).roundToInt(),
696
+ (maxWidth * density).roundToInt())
697
+ }
698
+ if (next == sidecarLayout) return
699
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
700
+ sidecarLayout = next
701
+ config?.let(::updateLayout)
702
+ updateSidecarGeometry()
703
+ scheduleSidecarSpacer()
704
+ }
705
+
706
+ private fun sidecarBaseInsetPx(): Int {
707
+ val layout = sidecarLayout ?: return 0
708
+ val width = recyclerView.width
709
+ return max(0, (width - minOf(width, layout.maxContentWidth)) / 2)
710
+ }
711
+
712
+ private fun updateSidecarGeometry() {
713
+ val layout = sidecarLayout
714
+ val root = containerSlots.getOrNull(3)
715
+ if (root !== sidecarHost.getChildAt(0)) {
716
+ sidecarHost.removeAllViews()
717
+ (root?.parent as? ViewGroup)?.removeView(root)
718
+ if (root != null) sidecarHost.addView(root)
719
+ }
720
+ val params = sidecarHost.layoutParams as? FrameLayout.LayoutParams
721
+ ?: FrameLayout.LayoutParams(0, 0, Gravity.TOP or Gravity.RIGHT)
722
+ val nextWidth = layout?.width ?: 0
723
+ val nextHeight = if (layout != null) slotHeights[3] else 0
724
+ val isRtl = layoutDirection == LAYOUT_DIRECTION_RTL
725
+ val nextGravity = Gravity.TOP or (if (isRtl) Gravity.LEFT else Gravity.RIGHT)
726
+ val nextSideMargin = sidecarBaseInsetPx()
727
+ if (params.width != nextWidth || params.height != nextHeight ||
728
+ params.gravity != nextGravity ||
729
+ params.leftMargin != (if (isRtl) nextSideMargin else 0) ||
730
+ params.rightMargin != (if (isRtl) 0 else nextSideMargin)) {
731
+ params.width = nextWidth
732
+ params.height = nextHeight
733
+ params.gravity = nextGravity
734
+ params.leftMargin = if (isRtl) nextSideMargin else 0
735
+ params.rightMargin = if (isRtl) 0 else nextSideMargin
736
+ sidecarHost.layoutParams = params
737
+ }
738
+ sidecarHost.visibility = if (layout != null && root != null && slotHeights[3] > 0) VISIBLE else GONE
739
+ updateSidecarPosition()
740
+ }
741
+
742
+ private fun updateSidecarPosition(resync: Boolean = false) {
743
+ if (sidecarLayout == null) return
744
+ if (resync) (if (structuralTail == null) measuredScrollDistancePx()
745
+ else structuralTailMeasuredScrollDistancePx())?.let { logicalScrollDistancePx = it }
746
+ sidecarHost.translationY = (recyclerView.paddingTop - logicalScrollDistancePx).toFloat()
747
+ }
748
+
749
+ private fun sidecarLeftExtentPx(): Int =
750
+ (nativeListScrollPrefixPx(
751
+ scrollContentAdapter.itemCount - sidecarSpacerAdapter.itemCount,
752
+ layoutManager.spanCount,
753
+ layoutManager.spanSizeLookup::getSpanSize,
754
+ if (structuralTail == null) ::estimatedScrollExtentPx else ::structuralTailRowOrSlotExtentPx,
755
+ ) + recyclerView.paddingTop + recyclerView.paddingBottom)
756
+ .coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
757
+
758
+ private fun scheduleSidecarSpacer() {
759
+ if (sidecarLayout == null && sidecarSpacerHeightPx == 0) return
760
+ if (disposed || sidecarSpacerScheduled) return
761
+ sidecarSpacerScheduled = true
762
+ recyclerView.post {
763
+ sidecarSpacerScheduled = false
764
+ updateSidecarSpacerNow()
765
+ }
766
+ }
767
+
768
+ private fun updateSidecarSpacerNow() {
769
+ if (disposed || recyclerView.width <= 0 || recyclerView.height <= 0) return
770
+ val desired = if (sidecarLayout != null) {
771
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
772
+ } else 0
773
+ val leftExtent = sidecarLeftExtentPx()
774
+ val next = (desired - leftExtent).coerceAtLeast(0)
775
+ if (abs(next - sidecarSpacerHeightPx) <= 1) return
776
+ sidecarSpacerHeightPx = next
777
+ sidecarSpacerAdapter.update(sidecarSpacerView, next, next > 0)
778
+ recyclerView.requestLayout()
779
+ }
780
+
297
781
  private fun scheduleContainerSlotRelayout() {
298
782
  if (disposed) return
299
783
  containerSlotRelayoutPending = true
@@ -314,14 +798,171 @@ class NativeListView(
314
798
 
315
799
  private fun updateContainerSlots() {
316
800
  homeOffsetDiagnostic("slots-before")
801
+ val headerWasAbsent = headerSlotAdapter.itemCount == 0
802
+ val firstVisible = layoutManager.findFirstVisibleItemPosition()
803
+ val firstView = layoutManager.findViewByPosition(firstVisible)
804
+ val restoreInitialHeaderTop = !initialHeaderInsertionHandled && headerWasAbsent &&
805
+ layoutManager.orientation == RecyclerView.VERTICAL &&
806
+ adapter.itemCount > 0 && readingIntentEpoch == 0L && pendingScrollRequest == null &&
807
+ acceptedScrollRequest == null && !executingScrollCommand &&
808
+ recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE && firstVisible == 0 &&
809
+ firstView != null && abs(layoutManager.getDecoratedTop(firstView) - recyclerView.paddingTop) <= 1 &&
810
+ !recyclerView.canScrollVertically(-1)
317
811
  headerSlotAdapter.update(containerSlots.getOrNull(0), slotHeights[0], true)
318
812
  emptySlotAdapter.update(containerSlots.getOrNull(1), slotHeights[1], config?.items?.isEmpty() != false)
319
- footerSlotAdapter.update(containerSlots.getOrNull(2), slotHeights[2], true)
813
+ syncDisclosurePresentation()
814
+ syncFooterPresentation()
815
+ updateSidecarGeometry()
816
+ if (headerWasAbsent && headerSlotAdapter.itemCount > 0) {
817
+ initialHeaderInsertionHandled = true
818
+ if (restoreInitialHeaderTop) {
819
+ // RecyclerView otherwise keeps the first body row at the top when this slot arrives late.
820
+ layoutManager.scrollToPositionWithOffset(0, 0)
821
+ }
822
+ }
320
823
  homeOffsetDiagnostic("slots-after")
321
824
  layoutManager.spanSizeLookup.invalidateSpanIndexCache()
322
825
  recyclerView.requestLayout()
323
826
  }
324
827
 
828
+ private fun disclosureInsetExtentPx(): Int =
829
+ ((config?.disclosure?.expandedTrailingInset ?: 0.0) * density)
830
+ .coerceIn(0.0, Int.MAX_VALUE.toDouble()).roundToInt()
831
+
832
+ private fun settleDisclosureCommand(status: String) {
833
+ val id = activeDisclosureTransitionId ?: return
834
+ if (disposed || id == settledDisclosureTransitionId ||
835
+ config?.structuralTransition?.id != id || structuralTail != null) return
836
+ settledDisclosureTransitionId = id
837
+ activeDisclosureTransitionId = null
838
+ onStructuralTransitionSettled?.invoke(JSONObject().apply {
839
+ put("transitionId", id)
840
+ put("status", status)
841
+ put("settledExpanded", config?.disclosure?.expanded == true)
842
+ }.toString())
843
+ }
844
+
845
+ private fun presentAcceptedDisclosureEndpoint(next: NativeListConfig) {
846
+ val disclosure = next.disclosure ?: return
847
+ disclosureFraction = if (disclosure.expanded) 1f else 0f
848
+ disclosurePresentedContentPx = if (disclosure.expanded) slotHeights[4] else 0
849
+ syncDisclosurePresentation()
850
+ }
851
+
852
+ private fun syncDisclosurePresentation() {
853
+ val disclosure = config?.disclosure
854
+ if (disclosure == null) {
855
+ disclosurePresentedContentPx = 0
856
+ disclosurePresentedInsetPx = 0
857
+ expandedContentAdapter.update(null, 0, false)
858
+ structureToggleAdapter.update(null, 0, false)
859
+ disclosureInsetAdapter.update(null, 0, false)
860
+ return
861
+ }
862
+ val content = containerSlots.getOrNull(4)
863
+ if (expandedContentHost.getChildAt(0) !== content) {
864
+ expandedContentHost.removeAllViews()
865
+ if (content != null) {
866
+ (content.parent as? ViewGroup)?.removeView(content)
867
+ expandedContentHost.addView(content, FrameLayout.LayoutParams(
868
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
869
+ }
870
+ }
871
+ expandedContentHost.naturalHeightPx = slotHeights[4]
872
+ val fraction = disclosureFraction.coerceIn(0f, 1f)
873
+ val contentHeight = if (disclosureTransitioning) disclosurePresentedContentPx else
874
+ if (disclosure.expanded) slotHeights[4] else 0
875
+ disclosurePresentedContentPx = contentHeight
876
+ disclosurePresentedInsetPx = (disclosureInsetExtentPx() * fraction).roundToInt()
877
+ val interactive = disclosure.expanded && !disclosureTransitioning && fraction >= 1f
878
+ expandedContentHost.importantForAccessibility = if (interactive)
879
+ View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
880
+ else View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
881
+ expandedContentAdapter.update(if (content == null) null else expandedContentHost,
882
+ contentHeight, true)
883
+ structureToggleAdapter.update(containerSlots.getOrNull(5), slotHeights[5], true)
884
+ disclosureInsetAdapter.update(disclosureInsetView,
885
+ disclosurePresentedInsetPx, true)
886
+ if (content != null) layoutExpandedContentHostNow()
887
+ }
888
+
889
+ private fun layoutExpandedContentHostNow() {
890
+ val wrapper = expandedContentHost
891
+ val child = wrapper.getChildAt(0) ?: return
892
+ val width = wrapper.width.takeIf { it > 0 } ?: wrapper.measuredWidth.takeIf { it > 0 } ?: return
893
+ val height = disclosurePresentedContentPx
894
+ if (!wrapper.isLayoutRequested && wrapper.measuredWidth == width &&
895
+ wrapper.measuredHeight == height && wrapper.height == height &&
896
+ child.left == 0 && child.top == 0 && child.right == width &&
897
+ child.bottom == wrapper.naturalHeightPx) return
898
+ wrapper.forceLayout()
899
+ wrapper.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
900
+ View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY))
901
+ wrapper.layout(wrapper.left, wrapper.top, wrapper.left + width, wrapper.top + height)
902
+ }
903
+
904
+ private fun syncFooterPresentation() {
905
+ val footer = containerSlots.getOrNull(2)
906
+ if (footerPresentationHost.getChildAt(0) !== footer) {
907
+ invalidateTailForContainerGeometry()
908
+ structuralFooterCompensatedHeightPx = null
909
+ structuralFooterObservedNativeHeightPx = null
910
+ acceptedFooterNaturalHeightPx = null
911
+ footerPresentationHost.removeAllViews()
912
+ if (footer != null) {
913
+ (footer.parent as? ViewGroup)?.removeView(footer)
914
+ footerPresentationHost.addView(footer, FrameLayout.LayoutParams(
915
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
916
+ }
917
+ }
918
+ val naturalHeight = footerNaturalHeightPx()
919
+ val hiddenTop = footerHiddenTopPx()
920
+ if (footerPresentationHost.naturalHeightPx != naturalHeight ||
921
+ footerPresentationHost.hiddenTopPx != hiddenTop) {
922
+ footerPresentationHost.naturalHeightPx = naturalHeight
923
+ footerPresentationHost.hiddenTopPx = hiddenTop
924
+ footerPresentationHost.requestLayout()
925
+ }
926
+ footerSlotAdapter.update(if (footer == null) null else footerPresentationHost,
927
+ naturalHeight - hiddenTop, true)
928
+ if (footer != null) layoutFooterPresentationHostNow()
929
+ }
930
+
931
+ private fun layoutFooterPresentationHostNow() {
932
+ val wrapper = footerPresentationHost
933
+ val child = wrapper.getChildAt(0) ?: return
934
+ val width = wrapper.width.takeIf { it > 0 } ?: wrapper.measuredWidth.takeIf { it > 0 } ?: return
935
+ val height = footerPresentedHeightPx()
936
+ val childTop = -wrapper.hiddenTopPx
937
+ val childBottom = wrapper.naturalHeightPx - wrapper.hiddenTopPx
938
+ if (!wrapper.isLayoutRequested && wrapper.measuredWidth == width &&
939
+ wrapper.measuredHeight == height && wrapper.height == height &&
940
+ child.left == 0 && child.top == childTop && child.right == width &&
941
+ child.bottom == childBottom) return
942
+ wrapper.forceLayout()
943
+ wrapper.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
944
+ View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY))
945
+ wrapper.layout(wrapper.left, wrapper.top, wrapper.left + width, wrapper.top + height)
946
+ }
947
+
948
+ private fun invalidateTailForContainerGeometry() {
949
+ pendingPreparingFooterFrame = null
950
+ if (structuralTail == null) return
951
+ if (!structuralTailFinalizing) finishStructuralTail(interrupted = true)
952
+ structuralFooterCompensatedHeightPx = null
953
+ structuralTailSignedExtentPx = structuralTailRowsInAdapterPx + structuralSpacerHeightPx
954
+ }
955
+
956
+ private fun footerNaturalHeightPx(): Int = if (structuralTail == null)
957
+ acceptedFooterNaturalHeightPx ?: slotHeights[2] else
958
+ structuralFooterCompensatedHeightPx ?: acceptedFooterNaturalHeightPx ?: slotHeights[2]
959
+
960
+ private fun footerHiddenTopPx(): Int = if (structuralTail == null) 0 else
961
+ (structuralTailRowsInAdapterPx - structuralTailSignedExtentPx)
962
+ .coerceIn(0, footerNaturalHeightPx())
963
+
964
+ private fun footerPresentedHeightPx(): Int = footerNaturalHeightPx() - footerHiddenTopPx()
965
+
325
966
  private fun scrollPositionForRow(index: Int): Int = index + headerSlotAdapter.itemCount
326
967
 
327
968
  private fun recordLaidOutRowExtent(child: View, extentPx: Int) {
@@ -345,7 +986,23 @@ class NativeListView(
345
986
  if (position < headerCount) return slotHeights[0]
346
987
  val row = position - headerCount
347
988
  if (row >= adapter.itemCount) {
348
- return if (row - adapter.itemCount < emptySlotAdapter.itemCount) slotHeights[1] else slotHeights[2]
989
+ val slot = row - adapter.itemCount
990
+ return when {
991
+ slot < emptySlotAdapter.itemCount -> slotHeights[1]
992
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount -> structuralSpacerHeightPx
993
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
994
+ expandedContentAdapter.itemCount -> disclosurePresentedContentPx
995
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
996
+ expandedContentAdapter.itemCount + structureToggleAdapter.itemCount -> slotHeights[5]
997
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
998
+ expandedContentAdapter.itemCount + structureToggleAdapter.itemCount +
999
+ disclosureInsetAdapter.itemCount ->
1000
+ disclosurePresentedInsetPx
1001
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
1002
+ expandedContentAdapter.itemCount + structureToggleAdapter.itemCount +
1003
+ disclosureInsetAdapter.itemCount + footerSlotAdapter.itemCount -> footerPresentedHeightPx()
1004
+ else -> sidecarSpacerHeightPx
1005
+ }
349
1006
  }
350
1007
  val item = adapter.itemAt(row)
351
1008
  item?.key?.let(measuredRowExtentsPx::get)?.let { return it }
@@ -354,6 +1011,847 @@ class NativeListView(
354
1011
  return if (measuredRowExtentsPx.isEmpty()) 0 else (measuredRowExtentSumPx / measuredRowExtentsPx.size).toInt()
355
1012
  }
356
1013
 
1014
+ private fun estimatedItemExtentPx(item: NativeListItem): Int {
1015
+ measuredRowExtentsPx[item.key]?.let { return it }
1016
+ val explicit = item.styledHeight ?: item.json.optDouble("height").takeIf { it.isFinite() }
1017
+ if (explicit != null) return (explicit * density).roundToInt()
1018
+ return if (measuredRowExtentsPx.isEmpty()) dp(56)
1019
+ else (measuredRowExtentSumPx / measuredRowExtentsPx.size).toInt()
1020
+ }
1021
+
1022
+ private fun setStructuralSpacerHeight(heightPx: Int) {
1023
+ val next = heightPx.coerceAtLeast(0)
1024
+ if (next == structuralSpacerHeightPx) return
1025
+ structuralSpacerHeightPx = next
1026
+ structuralSpacerAdapter.update(structuralSpacerView, next, true)
1027
+ layoutManager.spanSizeLookup.invalidateSpanIndexCache()
1028
+ }
1029
+
1030
+ private fun setStructuralTailExtent(extentPx: Int) {
1031
+ structuralTailSignedExtentPx = extentPx
1032
+ setStructuralSpacerHeight((extentPx - structuralTailRowsInAdapterPx).coerceAtLeast(0))
1033
+ syncFooterPresentation()
1034
+ }
1035
+
1036
+ private fun prefixTailCount(old: NativeListConfig, next: NativeListConfig): Int? {
1037
+ if (old.orientation != "vertical" || next.orientation != "vertical" ||
1038
+ old.layout != next.layout || next.layout !in setOf("linear", "table") ||
1039
+ old.itemSpacing != next.itemSpacing ||
1040
+ old.contentPadding != next.contentPadding ||
1041
+ old.contentPaddingTop != next.contentPaddingTop ||
1042
+ old.contentPaddingBottom != next.contentPaddingBottom ||
1043
+ old.contentPaddingHorizontal != next.contentPaddingHorizontal ||
1044
+ old.theme?.toString() != next.theme?.toString() ||
1045
+ old.listStyle?.toString() != next.listStyle?.toString() ||
1046
+ old.items.size == next.items.size ||
1047
+ old.reorderable || next.reorderable ||
1048
+ structuralTailFinalizing || structuralTailRowsInAdapterPx > 0 ||
1049
+ old.items.any { it.usesSelectorSourceScale } !=
1050
+ next.items.any { it.usesSelectorSourceScale } ||
1051
+ (structuralAnimator != null && structuralTail == null) ||
1052
+ old.items.any { !it.hasExplicitHeight } ||
1053
+ next.items.any { !it.hasExplicitHeight } ||
1054
+ old.items.any { it.type !in setOf("identity", "dataRow") } ||
1055
+ next.items.any { it.type !in setOf("identity", "dataRow") } ||
1056
+ old.items.any { it.type == "sectionHeader" } ||
1057
+ next.items.any { it.type == "sectionHeader" }) return null
1058
+ val prefix = minOf(old.items.size, next.items.size)
1059
+ if (prefix == 0) return null
1060
+ if (structuralTail != null && prefix != structuralTail?.prefixCount) return null
1061
+ for (index in 0 until prefix) {
1062
+ val before = old.items[index]
1063
+ val after = next.items[index]
1064
+ if (before.key != after.key || before.rendererKey != after.rendererKey ||
1065
+ explicitTailRowHeight(before) != explicitTailRowHeight(after) ||
1066
+ explicitTailRowSpacingPx(before, old.itemSpacing) !=
1067
+ explicitTailRowSpacingPx(after, next.itemSpacing)) return null
1068
+ }
1069
+ return prefix
1070
+ }
1071
+
1072
+ private fun explicitTailRowHeight(item: NativeListItem): Int =
1073
+ item.styledHeight?.let { (it * density).roundToInt() } ?: run {
1074
+ val value = item.json.optDouble("height")
1075
+ when (item.json.optString("heightRounding")) {
1076
+ "floor" -> (value * density).toInt()
1077
+ "nearest" -> (value * density).roundToInt()
1078
+ else -> if (usesSelectorSourceScale || item.usesSelectorSourceScale)
1079
+ (item.json.optInt("height") * density).roundToInt()
1080
+ else NativeListScale.dp(resources, item.json.optInt("height"))
1081
+ }
1082
+ }
1083
+
1084
+ private fun explicitTailRowSpacingPx(item: NativeListItem, spacing: Int): Int {
1085
+ if (item.type == "identity" &&
1086
+ item.json.optString("presentation") == "walletSidebar") {
1087
+ val height = item.styledHeight ?: item.json.optDouble("height")
1088
+ return ((height + spacing) * density).roundToInt() -
1089
+ (height * density).roundToInt()
1090
+ }
1091
+ return dp(spacing)
1092
+ }
1093
+
1094
+ private fun exceedsStructuralTailHostLimit(
1095
+ old: NativeListConfig,
1096
+ next: NativeListConfig,
1097
+ prefixCount: Int,
1098
+ ): Boolean {
1099
+ val items = (if (old.items.size > next.items.size) old.items else next.items)
1100
+ .drop(prefixCount)
1101
+ if (items.size <= 128) return false
1102
+ val starts = LongArray(items.size)
1103
+ val heights = IntArray(items.size)
1104
+ var cursor = 0L
1105
+ items.forEachIndexed { index, item ->
1106
+ starts[index] = cursor
1107
+ heights[index] = explicitTailRowHeight(item)
1108
+ cursor += heights[index] + explicitTailRowSpacingPx(item, next.itemSpacing)
1109
+ }
1110
+ val window = 3L * recyclerView.height
1111
+ return (0..(items.size - 129)).any { first ->
1112
+ starts[first + 128] - (starts[first] + heights[first]) <= window
1113
+ }
1114
+ }
1115
+
1116
+ private fun clearStructuralTail() {
1117
+ pendingPreparingFooterFrame = null
1118
+ structuralTail?.hosts?.values?.forEach { host ->
1119
+ structuralTailLayer.removeView(host)
1120
+ host.recycle()
1121
+ host.dispose()
1122
+ }
1123
+ structuralTail = null
1124
+ structuralTailFinalizing = false
1125
+ structuralTailPreparing = false
1126
+ structuralFooterCompensatedHeightPx = null
1127
+ structuralTailRowsInAdapterPx = 0
1128
+ setStructuralTailExtent(0)
1129
+ structuralTailLayer.removeAllViews()
1130
+ structuralTailLayer.visibility = GONE
1131
+ structuralTailLayer.layoutParams?.let { params ->
1132
+ params.width = 0
1133
+ params.height = 0
1134
+ structuralTailLayer.layoutParams = params
1135
+ }
1136
+ structuralTailLayer.forceLayout()
1137
+ structuralTailLayer.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY),
1138
+ View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY))
1139
+ structuralTailLayer.layout(0, 0, 0, 0)
1140
+ }
1141
+
1142
+ private fun structuralTailRowOrSlotExtentPx(position: Int): Int {
1143
+ val row = position - headerSlotAdapter.itemCount
1144
+ val item = adapter.itemAt(row)
1145
+ if (row < 0 || item == null || !item.hasExplicitHeight) return estimatedScrollExtentPx(position)
1146
+ return explicitTailRowHeight(item) +
1147
+ explicitTailRowSpacingPx(item, config?.itemSpacing ?: 0)
1148
+ }
1149
+
1150
+ private fun structuralTailMeasuredScrollDistancePx(): Int? {
1151
+ if (layoutManager.orientation != RecyclerView.VERTICAL) return null
1152
+ val first = layoutManager.findFirstVisibleItemPosition()
1153
+ if (first == RecyclerView.NO_POSITION) return null
1154
+ val view = layoutManager.findViewByPosition(first) ?: return null
1155
+ val prefix = nativeListScrollPrefixPx(first, layoutManager.spanCount,
1156
+ layoutManager.spanSizeLookup::getSpanSize, ::structuralTailRowOrSlotExtentPx)
1157
+ val topMargin = (view.layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin ?: 0
1158
+ val top = layoutManager.getDecoratedTop(view) - topMargin
1159
+ return (prefix + recyclerView.paddingTop - top).coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
1160
+ }
1161
+
1162
+ private fun tailScrollExtentPx(): Int =
1163
+ (if (structuralTail != null) structuralTailMeasuredScrollDistancePx()
1164
+ else measuredScrollDistancePx()) ?: logicalScrollDistancePx
1165
+
1166
+ private fun updateStructuralTailWindow() {
1167
+ val tail = structuralTail ?: return
1168
+ if (structuralTailFinalizing || structuralTailRowsInAdapterPx > 0) return
1169
+ val scroll = tailScrollExtentPx()
1170
+ val viewport = recyclerView.height
1171
+ if (viewport <= 0) return
1172
+ val y = recyclerView.top + recyclerView.paddingTop + structuralTailStartContentY - scroll
1173
+ val width = (recyclerView.width - recyclerView.paddingLeft - recyclerView.paddingRight).coerceAtLeast(0)
1174
+ val params = structuralTailLayer.layoutParams as FrameLayout.LayoutParams
1175
+ val left = recyclerView.left + recyclerView.paddingLeft
1176
+ if (params.width != width || params.height != structuralSpacerHeightPx ||
1177
+ params.leftMargin != left || params.topMargin != y) {
1178
+ params.width = width
1179
+ params.height = structuralSpacerHeightPx
1180
+ params.leftMargin = left
1181
+ params.topMargin = y
1182
+ structuralTailLayer.layoutParams = params
1183
+ }
1184
+ structuralTailLayer.visibility = VISIBLE
1185
+ val low = (-y - viewport).coerceAtLeast(0)
1186
+ val high = minOf(structuralSpacerHeightPx, -y + 2 * viewport)
1187
+ var first = 0
1188
+ var end = tail.items.size
1189
+ while (first < end) {
1190
+ val middle = (first + end) / 2
1191
+ if (tail.starts[middle] + tail.heights[middle] < low) first = middle + 1
1192
+ else end = middle
1193
+ }
1194
+ var last = first
1195
+ end = tail.items.size
1196
+ while (last < end) {
1197
+ val middle = (last + end) / 2
1198
+ if (tail.starts[middle] <= high) last = middle + 1
1199
+ else end = middle
1200
+ }
1201
+ if (last - first > 128) {
1202
+ finishStructuralTail(interrupted = false)
1203
+ return
1204
+ }
1205
+ tail.hosts.keys.filter { it < first || it >= last }.forEach { index ->
1206
+ val host = tail.hosts.remove(index) ?: return@forEach
1207
+ structuralTailLayer.removeView(host)
1208
+ host.recycle()
1209
+ host.dispose()
1210
+ }
1211
+ for (index in first until last) {
1212
+ if (tail.hosts.containsKey(index)) continue
1213
+ val item = tail.items[index]
1214
+ val host = NativeListRendererRegistry.create(reactContext, item.rendererKey.ordinal, fonts)
1215
+ host.listStyle = config?.listStyle
1216
+ host.bind(item, config?.theme, config?.layout ?: "linear", "vertical",
1217
+ tail.prefixCount + index, item.json.optBoolean("selected") ||
1218
+ (config?.selectedKeys?.contains(item.key) == true), adapter.checkboxState,
1219
+ useSourceScale = usesSelectorSourceScale)
1220
+ host.isClickable = false
1221
+ host.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
1222
+ structuralTailLayer.addView(host, FrameLayout.LayoutParams(width, tail.heights[index],
1223
+ Gravity.TOP or Gravity.LEFT).apply { topMargin = tail.starts[index] })
1224
+ tail.hosts[index] = host
1225
+ tail.peakHosts = maxOf(tail.peakHosts, tail.hosts.size)
1226
+ }
1227
+ val height = structuralSpacerHeightPx
1228
+ val needsMeasure = structuralTailLayer.isLayoutRequested ||
1229
+ structuralTailLayer.measuredWidth != width ||
1230
+ structuralTailLayer.measuredHeight != height ||
1231
+ tail.hosts.values.any { it.isLayoutRequested }
1232
+ if (needsMeasure) {
1233
+ structuralTailLayer.measure(
1234
+ MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
1235
+ MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
1236
+ )
1237
+ }
1238
+ if (needsMeasure || structuralTailLayer.left != left || structuralTailLayer.top != y ||
1239
+ structuralTailLayer.right != left + width || structuralTailLayer.bottom != y + height) {
1240
+ structuralTailLayer.layout(left, y, left + width, y + height)
1241
+ }
1242
+ }
1243
+
1244
+ private fun updateStructuralTailTarget() {
1245
+ val tail = structuralTail ?: return
1246
+ val disclosure = config?.disclosure
1247
+ val finalChrome = if (disclosure == null) 0 else
1248
+ slotHeights[5] + if (disclosure.expanded) slotHeights[4] + disclosureInsetExtentPx() else 0
1249
+ val leftHeight = recyclerView.paddingTop + structuralTailStartContentY + tail.finalExtent +
1250
+ finalChrome + footerNaturalHeightPx() + recyclerView.paddingBottom
1251
+ val sidecarHeight = if (sidecarLayout == null) 0 else
1252
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1253
+ val maximum = (maxOf(leftHeight, sidecarHeight) - recyclerView.height).coerceAtLeast(0)
1254
+ var target = structuralTailStartOffset.coerceIn(0, maximum)
1255
+ if (tail.finalExtent == 0 && disclosure != null && slotHeights[5] > 0) {
1256
+ val toggleTop = recyclerView.paddingTop + structuralTailStartContentY
1257
+ val toggleBottom = toggleTop + slotHeights[5]
1258
+ val sticky = stickyHeaderHost.height
1259
+ val lower = toggleBottom - recyclerView.height + recyclerView.paddingBottom
1260
+ val upper = toggleTop - recyclerView.paddingTop - sticky
1261
+ target = if (lower <= upper) target.coerceIn(lower, upper) else upper
1262
+ } else if (tail.finalExtent == 0 && footerNaturalHeightPx() > 0) {
1263
+ val footerTop = recyclerView.paddingTop + structuralTailStartContentY
1264
+ val footerBottom = footerTop + footerNaturalHeightPx()
1265
+ val sticky = stickyHeaderHost.height
1266
+ val lower = footerBottom - recyclerView.height + recyclerView.paddingBottom
1267
+ val upper = footerTop - recyclerView.paddingTop - sticky
1268
+ target = if (lower <= upper) target.coerceIn(lower, upper) else upper
1269
+ }
1270
+ structuralTailTargetOffset = target.coerceIn(0, maximum)
1271
+ }
1272
+
1273
+ private fun positionSettledDisclosureToggle() {
1274
+ if (recyclerView.width <= 0 || recyclerView.height <= 0 ||
1275
+ structureToggleAdapter.itemCount == 0 || slotHeights[5] <= 0 ||
1276
+ recyclerView.scrollState != RecyclerView.SCROLL_STATE_IDLE ||
1277
+ pendingScrollRequest != null || acceptedScrollRequest != null ||
1278
+ executingScrollCommand) return
1279
+ val togglePosition = headerSlotAdapter.itemCount + adapter.itemCount +
1280
+ emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
1281
+ expandedContentAdapter.itemCount
1282
+ val toggleTop = (recyclerView.paddingTop.toLong() +
1283
+ nativeListScrollPrefixPx(togglePosition, layoutManager.spanCount,
1284
+ layoutManager.spanSizeLookup::getSpanSize, ::structuralTailRowOrSlotExtentPx))
1285
+ .coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
1286
+ val stickyTop = recyclerView.paddingTop + stickyHeaderHost.height
1287
+ val lower = toggleTop + slotHeights[5] - recyclerView.height + recyclerView.paddingBottom
1288
+ val upper = toggleTop - stickyTop
1289
+ val sidecarBottom = if (sidecarLayout == null) 0 else
1290
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1291
+ val leftExtent = (nativeListScrollPrefixPx(
1292
+ scrollContentAdapter.itemCount - sidecarSpacerAdapter.itemCount,
1293
+ layoutManager.spanCount, layoutManager.spanSizeLookup::getSpanSize,
1294
+ ::structuralTailRowOrSlotExtentPx) +
1295
+ recyclerView.paddingTop + recyclerView.paddingBottom)
1296
+ .coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
1297
+ val maximum = (maxOf(leftExtent, sidecarBottom) - recyclerView.height).coerceAtLeast(0)
1298
+ val current = structuralTailMeasuredScrollDistancePx() ?: tailScrollExtentPx()
1299
+ val target = (if (lower <= upper) current.coerceIn(lower, upper) else upper)
1300
+ .coerceIn(0, maximum)
1301
+ val ownsCommand = !structuralTailCommandActive
1302
+ if (ownsCommand) {
1303
+ notifyScrollCommand(false, 0)
1304
+ notifyScrollCommand(false, 1)
1305
+ }
1306
+ try {
1307
+ recyclerView.scrollBy(0, target - current)
1308
+ relayoutRecyclerViewImmediately()
1309
+ } finally {
1310
+ if (ownsCommand) notifyScrollCommand(false, 2)
1311
+ }
1312
+ }
1313
+
1314
+ private fun finishStructuralTail(interrupted: Boolean) {
1315
+ val next = config ?: return
1316
+ if (structuralTail == null || structuralTailFinalizing) return
1317
+ structuralTailFinalizing = true
1318
+ val epoch = ++structuralTransitionEpoch
1319
+ pendingPreparingFooterFrame = pendingPreparingFooterFrame?.takeIf {
1320
+ it.footer === containerSlots.getOrNull(2)
1321
+ }?.copy(epoch = epoch, handoffOnly = true)
1322
+ structuralAnimator?.cancel()
1323
+ structuralAnimator = null
1324
+ recyclerView.itemAnimator = null
1325
+ structuralFooterHoldTop = null
1326
+ structuralFooterVisualStartTop = null
1327
+ structuralFooterVisualEndTop = null
1328
+ footerSlotAdapter.setVisualTranslationY(0f)
1329
+ if (interrupted && structuralTailCommandActive) {
1330
+ structuralTailCommandActive = false
1331
+ notifyScrollCommand(false, 2)
1332
+ }
1333
+ adapter.submitList(next.items) {
1334
+ if (epoch != structuralTransitionEpoch || disposed) return@submitList
1335
+ fun handoff() {
1336
+ if (epoch != structuralTransitionEpoch || disposed) return
1337
+ if (recyclerView.isComputingLayout) {
1338
+ recyclerView.post { handoff() }
1339
+ return
1340
+ }
1341
+ val acceptedPendingFooter = acceptPendingFooterValues(adjustTailStart = false)
1342
+ presentAcceptedDisclosureEndpoint(next)
1343
+ if (recyclerView.width <= 0 || recyclerView.height <= 0) {
1344
+ clearStructuralTail()
1345
+ if (acceptedPendingFooter) updateContainerSlots()
1346
+ if (structuralTailCommandActive) {
1347
+ structuralTailCommandActive = false
1348
+ notifyScrollCommand(false, 2)
1349
+ }
1350
+ if (next.disclosure != null) {
1351
+ disclosureTransitioning = false
1352
+ syncDisclosurePresentation()
1353
+ settleDisclosureCommand(if (interrupted) "interrupted" else "completed")
1354
+ }
1355
+ scheduleVisibleEvent()
1356
+ checkEndReached()
1357
+ return
1358
+ }
1359
+ structuralTailRowsInAdapterPx = 0
1360
+ setStructuralTailExtent(0)
1361
+ updateSidecarSpacerNow()
1362
+ relayoutRecyclerViewImmediately()
1363
+ if (epoch != structuralTransitionEpoch || disposed) return
1364
+ if (!interrupted && recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE) {
1365
+ val sidecarBottom = if (sidecarLayout == null) 0 else
1366
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1367
+ val maximum = (maxOf(sidecarLeftExtentPx(), sidecarBottom) -
1368
+ recyclerView.height).coerceAtLeast(0)
1369
+ val target = structuralTailTargetOffset.coerceIn(0, maximum)
1370
+ recyclerView.scrollBy(0, target - tailScrollExtentPx())
1371
+ }
1372
+ if (epoch != structuralTransitionEpoch || disposed) return
1373
+ clearStructuralTail()
1374
+ if (acceptedPendingFooter) updateContainerSlots()
1375
+ performPendingScrollIfNeeded()
1376
+ if (structuralTailCommandActive) {
1377
+ structuralTailCommandActive = false
1378
+ notifyScrollCommand(false, 2)
1379
+ }
1380
+ if (next.disclosure != null) {
1381
+ disclosureTransitioning = false
1382
+ syncDisclosurePresentation()
1383
+ settleDisclosureCommand(if (interrupted) "interrupted" else "completed")
1384
+ }
1385
+ scheduleVisibleEvent()
1386
+ checkEndReached()
1387
+ }
1388
+ handoff()
1389
+ }
1390
+ }
1391
+
1392
+ private fun discardStructuralTail() {
1393
+ if (structuralTail == null) return
1394
+ structuralTransitionEpoch += 1
1395
+ structuralAnimator?.cancel()
1396
+ structuralAnimator = null
1397
+ if (structuralTailCommandActive) {
1398
+ structuralTailCommandActive = false
1399
+ notifyScrollCommand(false, 2)
1400
+ }
1401
+ clearStructuralTail()
1402
+ setStructuralSpacerHeight(0)
1403
+ }
1404
+
1405
+ private fun holdStructuralTailUntilListCommit(): Int {
1406
+ val epoch = ++structuralTransitionEpoch
1407
+ pendingPreparingFooterFrame = pendingPreparingFooterFrame?.takeIf {
1408
+ it.footer === containerSlots.getOrNull(2)
1409
+ }?.copy(epoch = epoch, handoffOnly = true)
1410
+ structuralAnimator?.cancel()
1411
+ structuralAnimator = null
1412
+ structuralTailFinalizing = true
1413
+ if (structuralTailCommandActive) {
1414
+ structuralTailCommandActive = false
1415
+ notifyScrollCommand(false, 2)
1416
+ }
1417
+ return epoch
1418
+ }
1419
+
1420
+ private fun completeHeldTailCommit(
1421
+ next: NativeListConfig,
1422
+ epoch: Int,
1423
+ completion: () -> Unit,
1424
+ positionToggle: Boolean,
1425
+ ) {
1426
+ if (epoch != structuralTransitionEpoch || disposed) return
1427
+ if (recyclerView.isComputingLayout) {
1428
+ recyclerView.post { completeHeldTailCommit(next, epoch, completion, positionToggle) }
1429
+ return
1430
+ }
1431
+ val acceptedPendingFooter = acceptPendingFooterValues(adjustTailStart = false)
1432
+ presentAcceptedDisclosureEndpoint(next)
1433
+ structuralTailRowsInAdapterPx = 0
1434
+ setStructuralTailExtent(0)
1435
+ if (acceptedPendingFooter) updateContainerSlots()
1436
+ updateSidecarSpacerNow()
1437
+ relayoutRecyclerViewImmediately()
1438
+ if (positionToggle) positionSettledDisclosureToggle()
1439
+ if (epoch != structuralTransitionEpoch || disposed) return
1440
+ clearStructuralTail()
1441
+ disclosureTransitioning = false
1442
+ syncDisclosurePresentation()
1443
+ completion()
1444
+ }
1445
+
1446
+ private fun applyStructuralTailFrame(tail: StructuralTail, epoch: Int, progress: Float): Boolean {
1447
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail ||
1448
+ structuralTailFinalizing) return true
1449
+ if (recyclerView.isComputingLayout) return false
1450
+ val segmentProgress = if (structuralTailStartProgress >= 1f) 1f else
1451
+ ((progress - structuralTailStartProgress) /
1452
+ (1f - structuralTailStartProgress)).coerceIn(0f, 1f)
1453
+ config?.disclosure?.let { disclosure ->
1454
+ val target = if (disclosure.expanded) 1f else 0f
1455
+ disclosureFraction = disclosureStartFraction +
1456
+ (target - disclosureStartFraction) * segmentProgress
1457
+ val contentProgress = if (disclosureContentStartProgress >= 1f) 1f else
1458
+ ((progress - disclosureContentStartProgress) /
1459
+ (1f - disclosureContentStartProgress)).coerceIn(0f, 1f)
1460
+ val contentTarget = if (disclosure.expanded) slotHeights[4] else 0
1461
+ disclosurePresentedContentPx = (disclosureContentStartPx +
1462
+ (contentTarget - disclosureContentStartPx) * contentProgress).roundToInt()
1463
+ syncDisclosurePresentation()
1464
+ }
1465
+ setStructuralTailExtent((structuralTailStartExtentPx +
1466
+ (tail.finalExtent - structuralTailStartExtentPx) * segmentProgress).roundToInt())
1467
+ updateSidecarSpacerNow()
1468
+ relayoutRecyclerViewImmediately()
1469
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail) return true
1470
+ if (!structuralScrollInterrupted && recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE) {
1471
+ val sidecarBottom = if (sidecarLayout == null) 0 else
1472
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1473
+ val maximum = (maxOf(sidecarLeftExtentPx(), sidecarBottom) -
1474
+ recyclerView.height).coerceAtLeast(0)
1475
+ val desired = (structuralTailStartOffset +
1476
+ (structuralTailTargetOffset - structuralTailStartOffset) * segmentProgress)
1477
+ .roundToInt().coerceIn(0, maximum)
1478
+ val requestedScroll = desired - tailScrollExtentPx()
1479
+ recyclerView.scrollBy(0, requestedScroll)
1480
+ }
1481
+ updateStructuralTailWindow()
1482
+ return true
1483
+ }
1484
+
1485
+ private fun commitPreparingFooterFrame(): Boolean {
1486
+ val pending = pendingPreparingFooterFrame ?: return true
1487
+ if (structuralTail == null || structuralTailRowsInAdapterPx <= 0 ||
1488
+ pending.epoch != structuralTransitionEpoch || disposed ||
1489
+ pending.footer !== containerSlots.getOrNull(2)) {
1490
+ if (pendingPreparingFooterFrame === pending) pendingPreparingFooterFrame = null
1491
+ return true
1492
+ }
1493
+ if (pending.handoffOnly || recyclerView.isComputingLayout) return false
1494
+ pendingPreparingFooterFrame = null
1495
+ if (pending.observedNativeHeight != null) {
1496
+ structuralFooterObservedNativeHeightPx = pending.observedNativeHeight
1497
+ } else {
1498
+ containerSlots.getOrNull(2)?.measuredHeight
1499
+ ?.takeIf { it > 0 && it != pending.naturalHeight }
1500
+ ?.let { structuralFooterObservedNativeHeightPx = it }
1501
+ }
1502
+ reconcileStructuralFooterHeight(pending.naturalHeight)
1503
+ acceptedFooterNaturalHeightPx = pending.naturalHeight
1504
+ for (index in 0..5) slotHeights[index] = pending.heights[index]
1505
+ updateContainerSlots()
1506
+ updateStructuralTailTarget()
1507
+ updateSidecarGeometry()
1508
+ updateSidecarSpacerNow()
1509
+ relayoutRecyclerViewImmediately()
1510
+ if (pending.epoch != structuralTransitionEpoch || disposed ||
1511
+ pending.footer !== containerSlots.getOrNull(2)) {
1512
+ return pendingPreparingFooterFrame == null
1513
+ }
1514
+ val sidecarBottom = if (sidecarLayout == null) 0 else
1515
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1516
+ val maximum = (maxOf(sidecarLeftExtentPx(), sidecarBottom) -
1517
+ recyclerView.height).coerceAtLeast(0)
1518
+ val desired = pending.ownerOffset.coerceIn(0, maximum)
1519
+ recyclerView.scrollBy(0, desired - tailScrollExtentPx())
1520
+ relayoutRecyclerViewImmediately()
1521
+ updateStructuralTailWindow()
1522
+ return pendingPreparingFooterFrame == null
1523
+ }
1524
+
1525
+ private fun acceptPendingFooterValues(adjustTailStart: Boolean): Boolean {
1526
+ val pending = pendingPreparingFooterFrame ?: return false
1527
+ if (pending.footer !== containerSlots.getOrNull(2) || disposed ||
1528
+ pending.epoch != structuralTransitionEpoch) {
1529
+ pendingPreparingFooterFrame = null
1530
+ return false
1531
+ }
1532
+ val latestNativeHeight = if (pending.observedNativeHeight != null)
1533
+ pending.footer?.measuredHeight?.takeIf { it > 0 } else null
1534
+ val naturalHeight = if (latestNativeHeight != null &&
1535
+ latestNativeHeight != pending.observedNativeHeight) {
1536
+ (ceil(latestNativeHeight / density.toDouble()) * density).roundToInt()
1537
+ } else pending.naturalHeight
1538
+ if (adjustTailStart) {
1539
+ val previousHeight = structuralFooterCompensatedHeightPx ?:
1540
+ acceptedFooterNaturalHeightPx ?: slotHeights[2]
1541
+ val delta = previousHeight - naturalHeight
1542
+ structuralTailSignedExtentPx += delta
1543
+ structuralTailStartExtentPx += delta
1544
+ }
1545
+ structuralFooterObservedNativeHeightPx = latestNativeHeight ?:
1546
+ containerSlots.getOrNull(2)?.measuredHeight?.takeIf {
1547
+ it > 0 && it != naturalHeight
1548
+ }
1549
+ acceptedFooterNaturalHeightPx = naturalHeight
1550
+ structuralFooterCompensatedHeightPx = naturalHeight
1551
+ for (index in 0..5) slotHeights[index] = pending.heights[index]
1552
+ pendingPreparingFooterFrame = null
1553
+ return true
1554
+ }
1555
+
1556
+ private fun startPrefixTailTransition(
1557
+ previous: NativeListConfig,
1558
+ next: NativeListConfig,
1559
+ transition: NativeListConfig.StructuralTransition,
1560
+ prefixCount: Int,
1561
+ ) {
1562
+ val previousTail = structuralTail
1563
+ val carriedExtent = previousTail?.let { structuralTailSignedExtentPx }
1564
+ val startOffset = structuralTailMeasuredScrollDistancePx() ?: tailScrollExtentPx()
1565
+ if (previousTail == null) {
1566
+ cancelStructuralTransition()
1567
+ } else {
1568
+ structuralTransitionEpoch += 1
1569
+ structuralAnimator?.cancel()
1570
+ structuralAnimator = null
1571
+ if (structuralTailCommandActive) {
1572
+ structuralTailCommandActive = false
1573
+ notifyScrollCommand(false, 2)
1574
+ }
1575
+ // The old presentation remains visible until the new prefix and spacer commit together.
1576
+ structuralTailPreparing = true
1577
+ }
1578
+ val epoch = structuralTransitionEpoch
1579
+ val collapsing = previous.items.size > next.items.size
1580
+ val items = (if (collapsing) previous.items else next.items)
1581
+ .drop(prefixCount).toMutableList()
1582
+ val heights = IntArray(items.size) { explicitTailRowHeight(items[it]) }
1583
+ val spacings = IntArray(items.size) {
1584
+ explicitTailRowSpacingPx(items[it], next.itemSpacing)
1585
+ }
1586
+ val tail = StructuralTail(items, heights, spacings, prefixCount,
1587
+ if (collapsing) 0 else heights.sum() + spacings.sum())
1588
+ val startExtent = carriedExtent ?: if (collapsing) tail.extent else 0
1589
+ disclosureStartFraction = disclosureFraction
1590
+ if (next.disclosure != null) {
1591
+ disclosureContentStartPx = disclosurePresentedContentPx
1592
+ disclosureContentStartProgress = 0f
1593
+ disclosureTransitioning = true
1594
+ }
1595
+ val startContentY = (if (headerSlotAdapter.itemCount > 0) slotHeights[0] else 0) +
1596
+ next.items.take(prefixCount).sumOf {
1597
+ explicitTailRowHeight(it) + explicitTailRowSpacingPx(it, next.itemSpacing)
1598
+ }
1599
+ if (previousTail == null) {
1600
+ structuralTail = tail
1601
+ structuralTailRowsInAdapterPx = if (collapsing) tail.extent else 0
1602
+ structuralTailStartExtentPx = startExtent
1603
+ structuralTailStartProgress = 0f
1604
+ structuralTailStartContentY = startContentY
1605
+ structuralTailStartOffset = startOffset
1606
+ structuralTailTargetOffset = startOffset
1607
+ setStructuralTailExtent(startExtent)
1608
+ }
1609
+ structuralScrollInterrupted = false
1610
+ structuralFooterCompensatedHeightPx = null
1611
+ recyclerView.itemAnimator = null
1612
+ acceptRowIndex(next, previous)
1613
+ config = next
1614
+ pruneMeasuredRowExtents(next.items)
1615
+ updateContainerSlots()
1616
+ usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
1617
+ adapter.usesSelectorSourceScale = usesSelectorSourceScale
1618
+ adapter.theme = next.theme
1619
+ adapter.listStyle = next.listStyle
1620
+ adapter.layout = next.layout
1621
+ adapter.orientation = next.orientation
1622
+ adapter.selectedKeys = next.selectedKeys
1623
+ if (previous.generation != next.generation) endReachedGeneration = null
1624
+ configureSectionIndex(next)
1625
+ updateLayout(next)
1626
+ bindFooter(next)
1627
+ updateReordering(next)
1628
+ refreshLayout.isEnabled = next.pullToRefresh
1629
+ refreshLayout.setDistanceToTriggerSync(
1630
+ next.refreshTriggerDistance?.let { (it * density).roundToInt() }
1631
+ ?: defaultRefreshTriggerDistancePx,
1632
+ )
1633
+ refreshLayout.isRefreshing = next.refreshing
1634
+ structuralTailCommandActive = true
1635
+ notifyScrollCommand(false, 0)
1636
+ notifyScrollCommand(false, 1)
1637
+ adapter.submitList(next.items.take(prefixCount)) {
1638
+ fun commitPrefix() {
1639
+ if (epoch != structuralTransitionEpoch || disposed ||
1640
+ structuralTail !== (previousTail ?: tail) || structuralTailFinalizing) return
1641
+ if (recyclerView.isComputingLayout) {
1642
+ recyclerView.post { commitPrefix() }
1643
+ return
1644
+ }
1645
+ if (previousTail != null) {
1646
+ clearStructuralTail()
1647
+ structuralTail = tail
1648
+ structuralTailStartExtentPx = startExtent
1649
+ structuralTailStartProgress = 0f
1650
+ structuralTailStartContentY = startContentY
1651
+ structuralTailStartOffset = startOffset
1652
+ structuralTailTargetOffset = startOffset
1653
+ }
1654
+ acceptPendingFooterValues(adjustTailStart = true)
1655
+ structuralTailPreparing = false
1656
+ structuralTailRowsInAdapterPx = 0
1657
+ setStructuralTailExtent(structuralTailStartExtentPx)
1658
+ updateStructuralTailTarget()
1659
+ if (recyclerView.width <= 0 || recyclerView.height <= 0) {
1660
+ finishStructuralTail(interrupted = false)
1661
+ return
1662
+ }
1663
+ applyStructuralTailFrame(tail, epoch, 0f)
1664
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail ||
1665
+ structuralTailFinalizing) return
1666
+ var lastAppliedProgress = 0f
1667
+ var frameScheduled = false
1668
+ fun applyProgress(progress: Float) {
1669
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail ||
1670
+ structuralTailFinalizing) return
1671
+ val nextProgress = maxOf(progress, lastAppliedProgress)
1672
+ if (!applyStructuralTailFrame(tail, epoch, nextProgress)) {
1673
+ if (!frameScheduled) {
1674
+ frameScheduled = true
1675
+ recyclerView.post {
1676
+ frameScheduled = false
1677
+ val current = structuralAnimator?.animatedValue as? Float ?: nextProgress
1678
+ applyProgress(current)
1679
+ }
1680
+ }
1681
+ return
1682
+ }
1683
+ lastAppliedProgress = nextProgress
1684
+ }
1685
+ structuralAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
1686
+ duration = transition.durationMs
1687
+ interpolator = android.view.animation.AccelerateDecelerateInterpolator()
1688
+ addUpdateListener { animation ->
1689
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail) return@addUpdateListener
1690
+ if (Build.VERSION.SDK_INT >= 26 && !ValueAnimator.areAnimatorsEnabled()) {
1691
+ finishStructuralTail(interrupted = false)
1692
+ return@addUpdateListener
1693
+ }
1694
+ applyProgress(animation.animatedValue as Float)
1695
+ }
1696
+ addListener(object : AnimatorListenerAdapter() {
1697
+ override fun onAnimationEnd(animation: Animator) {
1698
+ if (epoch == structuralTransitionEpoch && structuralTail === tail)
1699
+ finishStructuralTail(interrupted = structuralScrollInterrupted)
1700
+ }
1701
+ })
1702
+ start()
1703
+ }
1704
+ }
1705
+ commitPrefix()
1706
+ }
1707
+ }
1708
+
1709
+ private fun updatePrefixTailSnapshot(
1710
+ previous: NativeListConfig,
1711
+ next: NativeListConfig,
1712
+ acceptIndex: Boolean = false,
1713
+ ): Boolean {
1714
+ val tail = structuralTail ?: return false
1715
+ if (structuralTailPreparing || structuralTailFinalizing ||
1716
+ structuralTailRowsInAdapterPx > 0 ||
1717
+ previous.items.size != next.items.size ||
1718
+ previous.disclosure != next.disclosure ||
1719
+ previous.layout != next.layout || previous.orientation != next.orientation ||
1720
+ previous.theme?.toString() != next.theme?.toString() ||
1721
+ previous.listStyle?.toString() != next.listStyle?.toString() ||
1722
+ previous.itemSpacing != next.itemSpacing ||
1723
+ previous.contentPadding != next.contentPadding ||
1724
+ previous.contentPaddingTop != next.contentPaddingTop ||
1725
+ previous.contentPaddingBottom != next.contentPaddingBottom ||
1726
+ previous.contentPaddingHorizontal != next.contentPaddingHorizontal) return false
1727
+ for (index in next.items.indices) {
1728
+ val before = previous.items[index]
1729
+ val after = next.items[index]
1730
+ if (before.key != after.key || before.rendererKey != after.rendererKey ||
1731
+ !after.hasExplicitHeight || explicitTailRowHeight(before) != explicitTailRowHeight(after) ||
1732
+ explicitTailRowSpacingPx(before, previous.itemSpacing) !=
1733
+ explicitTailRowSpacingPx(after, next.itemSpacing))
1734
+ return false
1735
+ }
1736
+ if (acceptIndex) acceptRowIndex(next, previous)
1737
+ config = next
1738
+ adapter.selectedKeys = next.selectedKeys
1739
+ adapter.submitList(next.items.take(tail.prefixCount)) {
1740
+ if (structuralTail !== tail || disposed) return@submitList
1741
+ scheduleVisibleEvent()
1742
+ }
1743
+ if (tail.finalExtent > 0) {
1744
+ for (index in tail.items.indices) {
1745
+ val item = next.items[tail.prefixCount + index]
1746
+ if (tail.items[index].content == item.content) continue
1747
+ tail.items[index] = item
1748
+ tail.hosts[index]?.let { host ->
1749
+ host.bind(item, next.theme, next.layout, "vertical", tail.prefixCount + index,
1750
+ item.json.optBoolean("selected") || next.selectedKeys.contains(item.key),
1751
+ adapter.checkboxState, useSourceScale = usesSelectorSourceScale)
1752
+ host.isClickable = false
1753
+ }
1754
+ }
1755
+ }
1756
+ bindFooter(next)
1757
+ updateStructuralTailTarget()
1758
+ return true
1759
+ }
1760
+
1761
+ private fun updateStructuralFooterHoldPosition() {
1762
+ val targetTop = structuralFooterHoldTop ?: return
1763
+ if (footerSlotAdapter.itemCount == 0) return
1764
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1765
+ layoutManager.findViewByPosition(footerPosition)?.let { footer ->
1766
+ footerSlotAdapter.setVisualTranslationY((targetTop - layoutManager.getDecoratedTop(footer)).toFloat())
1767
+ }
1768
+ }
1769
+
1770
+ private fun updateStructuralFooterVisualPosition() {
1771
+ val startTop = structuralFooterVisualStartTop ?: return
1772
+ val endTop = structuralFooterVisualEndTop ?: return
1773
+ if (footerSlotAdapter.itemCount == 0) return
1774
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1775
+ layoutManager.findViewByPosition(footerPosition)?.let { footer ->
1776
+ val desiredTop = startTop + (endTop - startTop) * structuralFooterVisualProgress
1777
+ footerSlotAdapter.setVisualTranslationY(desiredTop - layoutManager.getDecoratedTop(footer))
1778
+ }
1779
+ }
1780
+
1781
+ private fun cancelStructuralTransition() {
1782
+ if (structuralTail != null) discardStructuralTail()
1783
+ structuralTransitionEpoch += 1
1784
+ pendingStructuralTransition = null
1785
+ pendingStructuralStartScheduled = false
1786
+ structuralAnimator?.cancel()
1787
+ structuralAnimator = null
1788
+ recyclerView.itemAnimator = null
1789
+ setStructuralSpacerHeight(0)
1790
+ footerSlotAdapter.setVisualTranslationY(0f)
1791
+ structuralFooterHoldTop = null
1792
+ structuralFooterVisualStartTop = null
1793
+ structuralFooterVisualEndTop = null
1794
+ structuralFooterVisualProgress = 0f
1795
+ structuralFooterCompensatedHeightPx = null
1796
+ structuralStartSpacerPx = 0
1797
+ }
1798
+
1799
+ private fun startPendingStructuralTransition() {
1800
+ val pending = pendingStructuralTransition ?: return
1801
+ if (pending.epoch != structuralTransitionEpoch || disposed || pendingStructuralStartScheduled) return
1802
+ val expected = config?.items?.map { it.key } ?: return
1803
+ if (adapter.currentList.map { it.key } != expected) return
1804
+ pendingStructuralStartScheduled = true
1805
+ recyclerView.postOnAnimation {
1806
+ if (pending.epoch != structuralTransitionEpoch) return@postOnAnimation
1807
+ pendingStructuralStartScheduled = false
1808
+ val latest = pendingStructuralTransition
1809
+ if (latest?.epoch == pending.epoch && !disposed) {
1810
+ if (recyclerView.isComputingLayout) {
1811
+ startPendingStructuralTransition()
1812
+ return@postOnAnimation
1813
+ }
1814
+ alignPendingStructuralAnchor(latest)
1815
+ if (latest.anchorTop != null || (latest.collapsing && latest.footerStartTop != null)) {
1816
+ relayoutRecyclerViewImmediately()
1817
+ }
1818
+ pendingStructuralTransition = null
1819
+ startStructuralTransition(
1820
+ latest.transition, latest.epoch, latest.anchorKey, latest.anchorTop,
1821
+ latest.footerStartTop,
1822
+ )
1823
+ }
1824
+ }
1825
+ }
1826
+
1827
+ private fun alignPendingStructuralFooter(pending: PendingStructuralTransition): Boolean {
1828
+ val top = pending.footerStartTop ?: return false
1829
+ if (!pending.collapsing || !pending.spacerInserted || footerSlotAdapter.itemCount == 0 || structuralScrollInterrupted) return false
1830
+ if (pending.footerAnchorAppliedTop == top) return false
1831
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1832
+ layoutManager.scrollToPositionWithOffset(footerPosition, top - recyclerView.paddingTop)
1833
+ pendingStructuralTransition = pending.copy(footerAnchorAppliedTop = top)
1834
+ return true
1835
+ }
1836
+
1837
+ private fun alignPendingStructuralRow(pending: PendingStructuralTransition): Boolean {
1838
+ val key = pending.anchorKey ?: return false
1839
+ val top = pending.anchorTop ?: return false
1840
+ if (structuralScrollInterrupted || pending.rowAnchorAppliedTop == top) return false
1841
+ val desiredItems = config?.items ?: return false
1842
+ val rowIndex = desiredItems.indexOfFirst { it.key == key }
1843
+ if (rowIndex < 0 || adapter.itemCount != desiredItems.size ||
1844
+ adapter.currentList.getOrNull(rowIndex)?.key != key) return false
1845
+ layoutManager.scrollToPositionWithOffset(scrollPositionForRow(rowIndex), top - recyclerView.paddingTop)
1846
+ pendingStructuralTransition = pending.copy(rowAnchorAppliedTop = top)
1847
+ return true
1848
+ }
1849
+
1850
+ private fun alignPendingStructuralAnchor(pending: PendingStructuralTransition) {
1851
+ if (pending.anchorTop != null) alignPendingStructuralRow(pending)
1852
+ else alignPendingStructuralFooter(pending)
1853
+ }
1854
+
357
1855
  private fun measuredScrollDistancePx(): Int? {
358
1856
  if (layoutManager.orientation != RecyclerView.VERTICAL) return null
359
1857
  val first = layoutManager.findFirstVisibleItemPosition()
@@ -527,6 +2025,39 @@ class NativeListView(
527
2025
  override fun onDetachedFromWindow() { down?.recycle(); down = null; super.onDetachedFromWindow() }
528
2026
  }
529
2027
  private val stickyPreDraw = android.view.ViewTreeObserver.OnPreDrawListener {
2028
+ if (!commitPreparingFooterFrame()) {
2029
+ if (pendingPreparingFooterFrame?.handoffOnly != true) schedulePreparingFooterFrame()
2030
+ return@OnPreDrawListener false
2031
+ }
2032
+ if (pendingStructuralTransition != null || structuralAnimator != null || structuralTail != null) {
2033
+ val measuredHeightPx = containerSlots.getOrNull(2)?.measuredHeight ?: 0
2034
+ if (measuredHeightPx > 0 && measuredHeightPx != structuralFooterObservedNativeHeightPx) {
2035
+ // React layout can change the footer's contents before its onLayout height reaches JS.
2036
+ val roundedDip = ceil(measuredHeightPx / density.toDouble())
2037
+ val naturalHeight = (roundedDip * density).roundToInt()
2038
+ if (structuralTail != null && config?.disclosure != null &&
2039
+ naturalHeight != footerNaturalHeightPx()) {
2040
+ structuralFooterObservedNativeHeightPx = measuredHeightPx
2041
+ acceptedFooterNaturalHeightPx = naturalHeight
2042
+ structuralFooterCompensatedHeightPx = null
2043
+ finishStructuralTail(interrupted = true)
2044
+ return@OnPreDrawListener false
2045
+ }
2046
+ if (structuralTail != null && structuralTailRowsInAdapterPx > 0 &&
2047
+ !structuralTailFinalizing) {
2048
+ enqueuePreparingFooterFrame(slotHeights.copyOf(), naturalHeight,
2049
+ observedNativeHeight = measuredHeightPx)
2050
+ if (pendingPreparingFooterFrame != null) return@OnPreDrawListener false
2051
+ } else {
2052
+ structuralFooterObservedNativeHeightPx = measuredHeightPx
2053
+ reconcileStructuralFooterHeight(naturalHeight)
2054
+ acceptedFooterNaturalHeightPx = naturalHeight
2055
+ if (structuralTail == null || structuralTailFinalizing) syncFooterPresentation()
2056
+ }
2057
+ }
2058
+ }
2059
+ if (structuralTail != null && !structuralTailFinalizing) layoutFooterPresentationHostNow()
2060
+ if (config?.disclosure != null) layoutExpandedContentHostNow()
530
2061
  updateStickyHeader()
531
2062
  finishScrollCommandIfSettled()
532
2063
  true
@@ -584,6 +2115,17 @@ class NativeListView(
584
2115
  private var lastMarketPaginationAnchorLogAtMs = 0L
585
2116
  private var disposed = false
586
2117
  private var resourcesDisposed = false
2118
+ private var acceptedKeyIndex: Map<String, Int>? = null
2119
+
2120
+ private fun acceptRowIndex(next: NativeListConfig, previous: NativeListConfig?) {
2121
+ if (previous != null && acceptedKeyIndex != null &&
2122
+ previous.generation == next.generation && previous.items.size == next.items.size &&
2123
+ previous.items.indices.all { index ->
2124
+ previous.items[index].key == next.items[index].key &&
2125
+ previous.items[index].type == next.items[index].type
2126
+ }) return
2127
+ acceptedKeyIndex = next.items.withIndex().associate { it.value.key to it.index }
2128
+ }
587
2129
 
588
2130
  init {
589
2131
  orientation = VERTICAL
@@ -595,7 +2137,7 @@ class NativeListView(
595
2137
  recyclerView.addItemDecoration(reorderPlaceholderDecoration)
596
2138
  // OneKey patch: full-width selector header backgrounds do not change row content insets.
597
2139
  recyclerView.addItemDecoration(SelectorBackgroundDecoration(adapter))
598
- recyclerView.addItemDecoration(ContainerSlotInsetDecoration { slotInsetPx })
2140
+ recyclerView.addItemDecoration(ContainerSlotInsetDecoration { slotInsetPx to slotRightInsetPx })
599
2141
  if (homeOffsetDiagnosticEnabled) layoutManager.onDiagnosticLayout = ::homeOffsetDiagnostic
600
2142
  layoutManager.onBeforeDataLayout = {
601
2143
  if (pendingBodyStartEpoch == readingIntentEpoch && adapter.itemCount > 0 && pendingScrollRequest == null) {
@@ -603,10 +2145,14 @@ class NativeListView(
603
2145
  pendingBodyStartEpoch = null
604
2146
  homeOffsetDiagnostic("first-fill-body-start")
605
2147
  }
2148
+ pendingStructuralTransition?.let(::alignPendingStructuralAnchor)
606
2149
  }
607
2150
  layoutManager.onChildLaidOut = ::recordLaidOutRowExtent
608
2151
  layoutManager.onLayoutPassCompleted = {
2152
+ if (structuralFooterHoldTop != null) updateStructuralFooterHoldPosition()
2153
+ else if (structuralAnimator != null) updateStructuralFooterVisualPosition()
609
2154
  emitScrollPositionThresholdIfNeeded(resync = true)
2155
+ updateSidecarPosition(resync = true)
610
2156
  if (containerSlotRelayoutPending) scheduleContainerSlotRelayout()
611
2157
  if (commandLayoutRequest === acceptedScrollRequest) commandLayoutRequest = null
612
2158
  finishScrollCommandIfSettled()
@@ -618,7 +2164,7 @@ class NativeListView(
618
2164
  val rowPosition = rowPositionForScroll(position)
619
2165
  if (rowPosition !in 0 until adapter.itemCount) return layoutManager.spanCount
620
2166
  val type = adapter.itemAt(rowPosition)?.type
621
- return if (type == "sectionHeader" || type == "system" || type == "action") {
2167
+ return if (type == "sectionHeader" || type == "system" || type == "action" || type == "buttonGroup") {
622
2168
  layoutManager.spanCount
623
2169
  } else {
624
2170
  1
@@ -636,6 +2182,9 @@ class NativeListView(
636
2182
  FrameLayout.LayoutParams.MATCH_PARENT,
637
2183
  ),
638
2184
  )
2185
+ contentContainer.addView(structuralTailLayer, FrameLayout.LayoutParams(0, 0, Gravity.TOP or Gravity.LEFT))
2186
+ contentContainer.addView(sidecarHost,
2187
+ FrameLayout.LayoutParams(0, 0, Gravity.TOP or Gravity.RIGHT))
639
2188
  stickyHeaderHost.visibility = GONE
640
2189
  stickyHeaderHost.addView(stickyHeaderView, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT))
641
2190
  contentContainer.addView(stickyHeaderHost, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.TOP))
@@ -700,6 +2249,9 @@ class NativeListView(
700
2249
  recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
701
2250
  override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
702
2251
  if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
2252
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
2253
+ if (structuralAnimator != null || pendingStructuralTransition != null)
2254
+ structuralScrollInterrupted = true
703
2255
  cancelExecutingScrollCommand()
704
2256
  readingIntentEpoch++
705
2257
  pendingBodyStartEpoch = null
@@ -724,6 +2276,21 @@ class NativeListView(
724
2276
 
725
2277
  override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
726
2278
  logicalScrollDistancePx = (logicalScrollDistancePx + dy).coerceAtLeast(0)
2279
+ if (structuralScrollInterrupted && dy != 0) {
2280
+ if (pendingStructuralTransition != null) {
2281
+ pendingStructuralTransition = pendingStructuralTransition?.let {
2282
+ it.copy(footerStartTop = it.footerStartTop?.minus(dy))
2283
+ }
2284
+ structuralFooterHoldTop = structuralFooterHoldTop?.minus(dy)
2285
+ updateStructuralFooterHoldPosition()
2286
+ } else if (structuralAnimator != null) {
2287
+ structuralFooterVisualStartTop = structuralFooterVisualStartTop?.minus(dy)
2288
+ structuralFooterVisualEndTop = structuralFooterVisualEndTop?.minus(dy)
2289
+ updateStructuralFooterVisualPosition()
2290
+ }
2291
+ }
2292
+ updateSidecarPosition()
2293
+ if (structuralTail != null) updateStructuralTailWindow()
727
2294
  emitScrollPositionThresholdIfNeeded(resync = dx == 0 && dy == 0)
728
2295
  if (dx != 0 || dy != 0) invalidateActionAnchor("scroll")
729
2296
  syncSectionIndexToVisibleRows()
@@ -781,6 +2348,11 @@ class NativeListView(
781
2348
  }
782
2349
  val nextWidth = right - left
783
2350
  val nextHeight = bottom - top
2351
+ val widthChanged = lastLayoutWidth != nextWidth
2352
+ val directionChanged = layoutDirection != lastLayoutDirection
2353
+ if (structuralTail != null && lastLayoutWidth >= 0 &&
2354
+ (widthChanged || lastLayoutHeight != nextHeight || directionChanged))
2355
+ finishStructuralTail(interrupted = true)
784
2356
  if (
785
2357
  lastLayoutWidth >= 0 &&
786
2358
  (nextWidth != lastLayoutWidth || nextHeight != lastLayoutHeight || layoutDirection != lastLayoutDirection)
@@ -790,6 +2362,9 @@ class NativeListView(
790
2362
  lastLayoutWidth = nextWidth
791
2363
  lastLayoutHeight = nextHeight
792
2364
  lastLayoutDirection = layoutDirection
2365
+ if ((widthChanged || directionChanged) && sidecarLayout != null) config?.let(::updateLayout)
2366
+ updateSidecarGeometry()
2367
+ scheduleSidecarSpacer()
793
2368
  updateSectionIndexAttachment()
794
2369
  performPendingScrollIfNeeded()
795
2370
  }
@@ -821,6 +2396,27 @@ class NativeListView(
821
2396
  }
822
2397
 
823
2398
  override fun onDetachedFromWindow() {
2399
+ val disclosureId = activeDisclosureTransitionId
2400
+ if (structuralTail != null) {
2401
+ discardStructuralTail()
2402
+ val epoch = structuralTransitionEpoch
2403
+ config?.let { accepted ->
2404
+ adapter.submitList(accepted.items) {
2405
+ if (!disposed && epoch == structuralTransitionEpoch &&
2406
+ activeDisclosureTransitionId == disclosureId && disclosureId != null) {
2407
+ disclosureFraction = if (accepted.disclosure?.expanded == true) 1f else 0f
2408
+ disclosureTransitioning = false
2409
+ syncDisclosurePresentation()
2410
+ settleDisclosureCommand("interrupted")
2411
+ }
2412
+ }
2413
+ }
2414
+ } else if (disclosureId != null && !disposed) {
2415
+ disclosureFraction = if (config?.disclosure?.expanded == true) 1f else 0f
2416
+ disclosureTransitioning = false
2417
+ syncDisclosurePresentation()
2418
+ settleDisclosureCommand("interrupted")
2419
+ }
824
2420
  val cancelTag = R.id.onekey_native_scroll_coordinator_command_cancel_listener
825
2421
  if (recyclerView.getTag(cancelTag) === coordinatorCommandCancelListener) recyclerView.setTag(cancelTag, null)
826
2422
  cancelExecutingScrollCommand()
@@ -844,6 +2440,85 @@ class NativeListView(
844
2440
  homeOffsetDiagnostic("snapshot-before-nextCount=${next.items.size}")
845
2441
  invalidateActionAnchor("snapshot")
846
2442
  val previous = config
2443
+ val transition = next.structuralTransition
2444
+ val isNewTransition = transition != null && transition.id != consumedStructuralTransitionId
2445
+ if (transition != null) consumedStructuralTransitionId = transition.id
2446
+ val disclosureGeometryInvalid = batchedDisclosureGeometryInvalid ||
2447
+ (!isNewTransition && structuralTail != null &&
2448
+ previous?.disclosure != next.disclosure)
2449
+ batchedDisclosureGeometryInvalid = false
2450
+ if (!isNewTransition &&
2451
+ (next.disclosure == null || previous?.disclosure?.expanded != next.disclosure.expanded)) {
2452
+ activeDisclosureTransitionId = null
2453
+ }
2454
+ val oldKeys = previous?.items?.map { it.key } ?: emptyList()
2455
+ val nextKeys = next.items.map { it.key }
2456
+ if (next.disclosure != null && isNewTransition && previous != null) {
2457
+ activeDisclosureTransitionId = transition?.id
2458
+ directDisclosureStatus = if (oldKeys == nextKeys || nextKeys.isEmpty() ||
2459
+ transition?.durationMs == 0L ||
2460
+ (Build.VERSION.SDK_INT >= 26 && !ValueAnimator.areAnimatorsEnabled()))
2461
+ "completed" else "interrupted"
2462
+ } else if (next.disclosure == null) {
2463
+ activeDisclosureTransitionId = null
2464
+ }
2465
+ val positionDirectCollapse = isNewTransition && !disclosureGeometryInvalid &&
2466
+ next.disclosure?.expanded == false && directDisclosureStatus == "completed"
2467
+ var animateStructure = !disclosureGeometryInvalid && previous != null &&
2468
+ isNewTransition && oldKeys != nextKeys &&
2469
+ previous.orientation == "vertical" &&
2470
+ (previous.layout == "linear" || previous.layout == "table") &&
2471
+ next.orientation == "vertical" && (next.layout == "linear" || next.layout == "table") &&
2472
+ (transition?.durationMs ?: 0) > 0 &&
2473
+ (if (Build.VERSION.SDK_INT >= 26) ValueAnimator.areAnimatorsEnabled() else
2474
+ android.provider.Settings.Global.getFloat(context.contentResolver, "animator_duration_scale", 1f) > 0f)
2475
+ val prefixCount = if (animateStructure && previous != null && recyclerView.width > 0 &&
2476
+ recyclerView.height > 0) prefixTailCount(previous, next) else null
2477
+ val exceedsTailHostLimit = prefixCount != null && previous != null &&
2478
+ exceedsStructuralTailHostLimit(previous, next, prefixCount)
2479
+ if (exceedsTailHostLimit) animateStructure = false
2480
+ if (next.disclosure != null && prefixCount == null) animateStructure = false
2481
+ if (prefixCount != null && !exceedsTailHostLimit && previous != null && transition != null) {
2482
+ startPrefixTailTransition(previous, next, transition, prefixCount)
2483
+ return
2484
+ }
2485
+ var heldTailEpoch: Int? = null
2486
+ if (structuralTail != null) {
2487
+ if (!disclosureGeometryInvalid && !animateStructure && oldKeys == nextKeys &&
2488
+ (Build.VERSION.SDK_INT < 26 || ValueAnimator.areAnimatorsEnabled()) &&
2489
+ previous != null && updatePrefixTailSnapshot(previous, next, acceptIndex = true)) {
2490
+ return
2491
+ }
2492
+ heldTailEpoch = holdStructuralTailUntilListCommit()
2493
+ // Keep the accepted presentation until the full adapter list has committed.
2494
+ animateStructure = false
2495
+ }
2496
+ val nextKeySet = nextKeys.toHashSet()
2497
+ val visibleAnchor = if (animateStructure) {
2498
+ val first = layoutManager.findFirstVisibleItemPosition()
2499
+ val last = layoutManager.findLastVisibleItemPosition()
2500
+ (first..last).firstNotNullOfOrNull { position ->
2501
+ val rowIndex = rowPositionForScroll(position)
2502
+ oldKeys.getOrNull(rowIndex)?.takeIf(nextKeySet::contains)?.let { key ->
2503
+ layoutManager.findViewByPosition(position)?.let { key to layoutManager.getDecoratedTop(it) }
2504
+ }
2505
+ }
2506
+ } else null
2507
+ val anchorKey = visibleAnchor?.first ?: transition?.anchorKey?.takeIf(nextKeySet::contains)
2508
+ val anchorTop = visibleAnchor?.second
2509
+ val footerStartTop = if (animateStructure && footerSlotAdapter.itemCount > 0) {
2510
+ layoutManager.findViewByPosition(scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount)?.let {
2511
+ layoutManager.getDecoratedTop(it) + it.translationY.roundToInt()
2512
+ }
2513
+ } else null
2514
+ val oldKeySet = oldKeys.toHashSet()
2515
+ val removedExtent = if (animateStructure) previous?.items?.sumOf { item ->
2516
+ if (nextKeySet.contains(item.key)) 0 else estimatedItemExtentPx(item)
2517
+ } ?: 0 else 0
2518
+ val addedExtent = if (animateStructure) next.items.sumOf { item ->
2519
+ if (oldKeySet.contains(item.key)) 0 else estimatedItemExtentPx(item)
2520
+ } else 0
2521
+ if (!animateStructure && oldKeys != nextKeys && heldTailEpoch == null) cancelStructuralTransition()
847
2522
  if (previous?.items?.isEmpty() == true && next.items.isNotEmpty() && adapter.itemCount == 0 &&
848
2523
  pendingScrollRequest == null && recyclerView.scrollState != RecyclerView.SCROLL_STATE_DRAGGING &&
849
2524
  !recyclerView.canScrollVertically(-1) && layoutManager.findFirstVisibleItemPosition() == 0) {
@@ -866,7 +2541,12 @@ class NativeListView(
866
2541
  previous.items[index].content != next.items[index].content
867
2542
  }
868
2543
  }.toSet()
2544
+ acceptRowIndex(next, previous)
869
2545
  config = next
2546
+ if (heldTailEpoch == null) {
2547
+ disclosureFraction = if (next.disclosure?.expanded == true) 1f else 0f
2548
+ disclosureTransitioning = false
2549
+ }
870
2550
  updateContainerSlots()
871
2551
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
872
2552
  adapter.usesSelectorSourceScale = usesSelectorSourceScale
@@ -879,14 +2559,29 @@ class NativeListView(
879
2559
  // outside the adapter, so a listStyle-only snapshot must rebind it here.
880
2560
  if (previous.listStyle?.toString() != next.listStyle?.toString()) bindFooter(next)
881
2561
  adapter.submitList(next.items) {
882
- homeOffsetDiagnostic("snapshot-stable-submit-commit")
883
- // OneKey patch: DiffUtil has dispatched its payloads; release the old serialized rows.
884
- next.items.forEach { it.selectionUpdateFromContent = null }
885
- recyclerView.post {
886
- bindVisibleSelection(changedSummaryKeys)
887
- bindFooterSelection()
888
- performPendingScrollIfNeeded()
2562
+ val committed: () -> Unit = {
2563
+ homeOffsetDiagnostic("snapshot-stable-submit-commit")
2564
+ // OneKey patch: DiffUtil has dispatched its payloads; release the old serialized rows.
2565
+ next.items.forEach { it.selectionUpdateFromContent = null }
2566
+ recyclerView.post {
2567
+ scheduleSidecarSpacer()
2568
+ startPendingStructuralTransition()
2569
+ bindVisibleSelection(changedSummaryKeys)
2570
+ bindFooterSelection()
2571
+ performPendingScrollIfNeeded()
2572
+ if (next.disclosure != null && (isNewTransition || disclosureGeometryInvalid) &&
2573
+ transition != null && activeDisclosureTransitionId == transition.id) {
2574
+ relayoutRecyclerViewImmediately()
2575
+ if (positionDirectCollapse && heldTailEpoch == null)
2576
+ positionSettledDisclosureToggle()
2577
+ settleDisclosureCommand(if (disclosureGeometryInvalid) "interrupted" else
2578
+ directDisclosureStatus)
2579
+ }
2580
+ }
889
2581
  }
2582
+ if (heldTailEpoch != null) completeHeldTailCommit(next, heldTailEpoch, committed,
2583
+ positionDirectCollapse)
2584
+ else committed()
890
2585
  }
891
2586
  return
892
2587
  }
@@ -905,7 +2600,12 @@ class NativeListView(
905
2600
  layoutManager.getDecoratedTop(it) - recyclerView.paddingTop
906
2601
  }
907
2602
  } else null
2603
+ acceptRowIndex(next, previous)
908
2604
  config = next
2605
+ if (heldTailEpoch == null) {
2606
+ disclosureFraction = if (next.disclosure?.expanded == true) 1f else 0f
2607
+ disclosureTransitioning = false
2608
+ }
909
2609
  pruneMeasuredRowExtents(next.items)
910
2610
  updateContainerSlots()
911
2611
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
@@ -919,16 +2619,61 @@ class NativeListView(
919
2619
  adapter.selectedKeys = next.selectedKeys
920
2620
  configureSectionIndex(next)
921
2621
  updateLayout(next)
2622
+ if (animateStructure && transition != null) {
2623
+ structuralTransitionEpoch += 1
2624
+ pendingStructuralStartScheduled = false
2625
+ structuralAnimator?.cancel()
2626
+ structuralAnimator = null
2627
+ structuralScrollInterrupted = false
2628
+ structuralFooterHoldTop = footerStartTop
2629
+ structuralFooterCompensatedHeightPx = slotHeights[2]
2630
+ val held = (structuralSpacerHeightPx + removedExtent - addedExtent).coerceAtLeast(0)
2631
+ pendingStructuralTransition = PendingStructuralTransition(
2632
+ transition, structuralTransitionEpoch, anchorKey, anchorTop, footerStartTop, held,
2633
+ removedExtent > addedExtent,
2634
+ )
2635
+ recyclerView.itemAnimator = DefaultItemAnimator().apply {
2636
+ addDuration = transition.durationMs
2637
+ removeDuration = transition.durationMs
2638
+ moveDuration = 0
2639
+ changeDuration = 0
2640
+ supportsChangeAnimations = false
2641
+ }
2642
+ }
922
2643
  adapter.submitList(next.items) {
923
- homeOffsetDiagnostic("snapshot-submit-commit-marketAnchor=${marketStartOffset != null}")
924
- if (marketStartOffset != null) {
925
- layoutManager.scrollToPositionWithOffset(scrollPositionForRow(0), marketStartOffset)
2644
+ val committed: () -> Unit = {
2645
+ pendingStructuralTransition?.takeIf { it.epoch == structuralTransitionEpoch }?.let {
2646
+ setStructuralSpacerHeight(it.heldHeightPx)
2647
+ pendingStructuralTransition = it.copy(spacerInserted = true)
2648
+ pendingStructuralTransition?.let(::alignPendingStructuralAnchor)
2649
+ }
2650
+ homeOffsetDiagnostic("snapshot-submit-commit-marketAnchor=${marketStartOffset != null}")
2651
+ if (marketStartOffset != null) {
2652
+ layoutManager.scrollToPositionWithOffset(scrollPositionForRow(0), marketStartOffset)
2653
+ }
2654
+ relayoutContents(preserveMarketPaginationAnchor)
2655
+ scheduleSidecarSpacer()
2656
+ startPendingStructuralTransition()
2657
+ performPendingScrollIfNeeded()
2658
+ syncSectionIndexToVisibleRows()
2659
+ scheduleVisibleEvent()
2660
+ if (next.items.isNotEmpty()) checkEndReached()
2661
+ if (next.disclosure != null && (isNewTransition || disclosureGeometryInvalid) &&
2662
+ transition != null && activeDisclosureTransitionId == transition.id) {
2663
+ recyclerView.post {
2664
+ if (!disposed && activeDisclosureTransitionId == transition.id) {
2665
+ relayoutRecyclerViewImmediately()
2666
+ if (positionDirectCollapse && heldTailEpoch == null)
2667
+ positionSettledDisclosureToggle()
2668
+ settleDisclosureCommand(if (disclosureGeometryInvalid) "interrupted" else
2669
+ directDisclosureStatus)
2670
+ }
2671
+ }
2672
+ }
926
2673
  }
927
- relayoutContents(preserveMarketPaginationAnchor)
928
- performPendingScrollIfNeeded()
929
- syncSectionIndexToVisibleRows()
930
- scheduleVisibleEvent()
931
- if (next.items.isNotEmpty()) checkEndReached()
2674
+ if (heldTailEpoch != null) completeHeldTailCommit(next, heldTailEpoch, committed,
2675
+ positionDirectCollapse)
2676
+ else committed()
932
2677
  }
933
2678
  refreshLayout.isEnabled = next.pullToRefresh
934
2679
  refreshLayout.setDistanceToTriggerSync(next.refreshTriggerDistance?.let { (it * density).roundToInt() } ?: defaultRefreshTriggerDistancePx)
@@ -937,6 +2682,85 @@ class NativeListView(
937
2682
  updateReordering(next)
938
2683
  }
939
2684
 
2685
+ private fun startStructuralTransition(
2686
+ transition: NativeListConfig.StructuralTransition,
2687
+ epoch: Int,
2688
+ anchorKey: String?,
2689
+ anchorTop: Int?,
2690
+ footerStartTop: Int?,
2691
+ ) {
2692
+ structuralFooterHoldTop = null
2693
+ val startSpacer = structuralSpacerHeightPx
2694
+ structuralStartSpacerPx = startSpacer
2695
+ structuralFooterVisualStartTop = footerStartTop
2696
+ structuralFooterVisualProgress = 0f
2697
+ val startOffset = measuredScrollDistancePx()?.also { logicalScrollDistancePx = it }
2698
+ ?: logicalScrollDistancePx
2699
+ val anchorIndex = anchorKey?.let { key -> adapter.currentList.indexOfFirst { it.key == key } }
2700
+ val currentAnchorTop = anchorIndex?.takeIf { it >= 0 }?.let { index ->
2701
+ layoutManager.findViewByPosition(scrollPositionForRow(index))?.let(layoutManager::getDecoratedTop)
2702
+ }
2703
+ val anchorDelta = if (anchorTop != null && currentAnchorTop != null) currentAnchorTop - anchorTop else 0
2704
+ val leftFinal = (sidecarLeftExtentPx() - startSpacer).coerceAtLeast(0)
2705
+ val sidecarBottom = if (sidecarLayout != null)
2706
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom else 0
2707
+ val finalMax = (max(leftFinal, sidecarBottom) - recyclerView.height).coerceAtLeast(0)
2708
+ var targetOffset = (startOffset + anchorDelta).coerceIn(0, finalMax)
2709
+ if (anchorTop == null && anchorIndex != null && anchorIndex >= 0) {
2710
+ val fallbackTop = nativeListScrollPrefixPx(
2711
+ scrollPositionForRow(anchorIndex),
2712
+ layoutManager.spanCount,
2713
+ layoutManager.spanSizeLookup::getSpanSize,
2714
+ ::estimatedScrollExtentPx,
2715
+ ).coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
2716
+ targetOffset = minOf(targetOffset, fallbackTop)
2717
+ }
2718
+ structuralFooterVisualEndTop = if (footerStartTop != null && footerSlotAdapter.itemCount > 0) {
2719
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
2720
+ val finalPrefix = nativeListScrollPrefixPx(
2721
+ footerPosition,
2722
+ layoutManager.spanCount,
2723
+ layoutManager.spanSizeLookup::getSpanSize,
2724
+ ::estimatedScrollExtentPx,
2725
+ ) - startSpacer
2726
+ (finalPrefix + recyclerView.paddingTop - targetOffset)
2727
+ .coerceIn(Int.MIN_VALUE.toLong(), Int.MAX_VALUE.toLong()).toInt()
2728
+ } else null
2729
+ structuralAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
2730
+ duration = transition.durationMs
2731
+ interpolator = android.view.animation.AccelerateDecelerateInterpolator()
2732
+ addUpdateListener { animation ->
2733
+ if (epoch != structuralTransitionEpoch || disposed) return@addUpdateListener
2734
+ val fraction = animation.animatedValue as Float
2735
+ structuralFooterVisualProgress = fraction
2736
+ setStructuralSpacerHeight((structuralStartSpacerPx * (1f - fraction)).roundToInt())
2737
+ measuredScrollDistancePx()?.let { logicalScrollDistancePx = it }
2738
+ val finalLeftExtent = (sidecarLeftExtentPx() - structuralSpacerHeightPx).coerceAtLeast(0)
2739
+ val finalMaximum = (max(finalLeftExtent, sidecarBottom) - recyclerView.height).coerceAtLeast(0)
2740
+ val desired = (startOffset + (minOf(targetOffset, finalMaximum) - startOffset) * fraction).roundToInt()
2741
+ if (!structuralScrollInterrupted && recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE)
2742
+ recyclerView.scrollBy(0, desired - logicalScrollDistancePx)
2743
+ updateStructuralFooterVisualPosition()
2744
+ }
2745
+ addListener(object : AnimatorListenerAdapter() {
2746
+ override fun onAnimationEnd(animation: Animator) {
2747
+ if (epoch != structuralTransitionEpoch) return
2748
+ structuralAnimator = null
2749
+ recyclerView.itemAnimator = null
2750
+ setStructuralSpacerHeight(0)
2751
+ scheduleSidecarSpacer()
2752
+ footerSlotAdapter.setVisualTranslationY(0f)
2753
+ structuralFooterVisualStartTop = null
2754
+ structuralFooterVisualEndTop = null
2755
+ structuralFooterVisualProgress = 0f
2756
+ structuralFooterCompensatedHeightPx = null
2757
+ structuralStartSpacerPx = 0
2758
+ }
2759
+ })
2760
+ start()
2761
+ }
2762
+ }
2763
+
940
2764
  private fun captureVisibleMarketAnchor(): VisibleMarketAnchor? {
941
2765
  val position = rowPositionForScroll(layoutManager.findFirstVisibleItemPosition()).coerceAtLeast(0)
942
2766
  if (position == RecyclerView.NO_POSITION) return null
@@ -1111,20 +2935,22 @@ class NativeListView(
1111
2935
 
1112
2936
  fun applyPatches(patchesJson: String) {
1113
2937
  val current = config ?: return
2938
+ val indexByKey = acceptedKeyIndex ?: return
1114
2939
  val patches = try {
1115
2940
  JSONArray(patchesJson)
1116
2941
  } catch (_: Exception) {
1117
2942
  return
1118
2943
  }
1119
- val indexByKey = current.items.withIndex().associate { it.value.key to it.index }
1120
2944
  val pending = ArrayList<Pair<Int, JSONObject>>(patches.length())
1121
2945
  val seen = HashSet<String>()
1122
2946
  for (index in 0 until patches.length()) {
1123
2947
  val patch = patches.optJSONObject(index) ?: return
1124
2948
  val key = patch.optString("key")
1125
2949
  val itemIndex = indexByKey[key] ?: return
2950
+ val item = current.items.getOrNull(itemIndex) ?: return
2951
+ if (item.key != key) return
1126
2952
  if (!seen.add(key)) return
1127
- if (patch.optString("type") != current.items[itemIndex].type) return
2953
+ if (patch.optString("type") != item.type) return
1128
2954
  val changes = patch.optJSONObject("changes") ?: return
1129
2955
  pending.add(itemIndex to changes)
1130
2956
  }
@@ -1148,12 +2974,23 @@ class NativeListView(
1148
2974
  }
1149
2975
  if (!marketQuoteOnly) invalidateActionAnchor("snapshot")
1150
2976
  val next = current.copy(items = nextItems, selectedKeys = selected)
2977
+ if (structuralTail != null && updatePrefixTailSnapshot(current, next)) return
2978
+ val heldTailEpoch = if (structuralTail != null) holdStructuralTailUntilListCommit() else null
1151
2979
  config = next
1152
2980
  updateContainerSlots()
1153
2981
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
1154
2982
  adapter.usesSelectorSourceScale = usesSelectorSourceScale
1155
2983
  adapter.selectedKeys = selected
1156
- adapter.submitList(nextItems) { relayoutContents() }
2984
+ adapter.submitList(nextItems) {
2985
+ if (heldTailEpoch != null) {
2986
+ if (heldTailEpoch != structuralTransitionEpoch || disposed) return@submitList
2987
+ val acceptedPendingFooter = acceptPendingFooterValues(adjustTailStart = false)
2988
+ clearStructuralTail()
2989
+ if (acceptedPendingFooter) updateContainerSlots()
2990
+ setStructuralSpacerHeight(0)
2991
+ }
2992
+ relayoutContents()
2993
+ }
1157
2994
  bindFooter(next)
1158
2995
  }
1159
2996
 
@@ -1215,6 +3052,7 @@ class NativeListView(
1215
3052
  is ScrollRequest.End -> true
1216
3053
  }
1217
3054
  if (!valid) return
3055
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
1218
3056
  executingScrollCommand = false
1219
3057
  dispatchingScrollRequest = null
1220
3058
  commandLayoutRequest = null
@@ -1240,6 +3078,7 @@ class NativeListView(
1240
3078
 
1241
3079
  private val coordinatorCommandCancelListener = Runnable {
1242
3080
  if (disposed) return@Runnable
3081
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
1243
3082
  pendingScrollRequest = null
1244
3083
  readingIntentEpoch++
1245
3084
  pendingBodyStartEpoch = null
@@ -1353,7 +3192,8 @@ class NativeListView(
1353
3192
  }
1354
3193
  is ScrollRequest.End -> {
1355
3194
  val finalSlotHeight = when {
1356
- footerSlotAdapter.itemCount > 0 -> slotHeights[2]
3195
+ sidecarSpacerAdapter.itemCount > 0 -> sidecarSpacerHeightPx
3196
+ footerSlotAdapter.itemCount > 0 -> footerPresentedHeightPx()
1357
3197
  emptySlotAdapter.itemCount > 0 -> slotHeights[1]
1358
3198
  adapter.itemCount == 0 && headerSlotAdapter.itemCount > 0 -> slotHeights[0]
1359
3199
  else -> null
@@ -1648,6 +3488,8 @@ class NativeListView(
1648
3488
  fun dispose() {
1649
3489
  if (disposed) return
1650
3490
  disposed = true
3491
+ acceptedKeyIndex = null
3492
+ if (structuralTail != null) discardStructuralTail()
1651
3493
  val cancelTag = R.id.onekey_native_scroll_coordinator_command_cancel_listener
1652
3494
  if (recyclerView.getTag(cancelTag) === coordinatorCommandCancelListener) recyclerView.setTag(cancelTag, null)
1653
3495
  containerSlotRelayoutPending = false
@@ -1658,6 +3500,8 @@ class NativeListView(
1658
3500
  private fun disposeResources() {
1659
3501
  if (resourcesDisposed) return
1660
3502
  resourcesDisposed = true
3503
+ cancelStructuralTransition()
3504
+ recyclerView.itemAnimator = null
1661
3505
  stopSectionIndexAttachmentTracking()
1662
3506
  scheduleSectionIndexAttachmentToList()
1663
3507
  stopReorderRelayoutLoop()
@@ -1722,12 +3566,26 @@ class NativeListView(
1722
3566
  val coordinatorBottomPadding = (recyclerView.paddingBottom - configuredBottomPaddingPx).coerceAtLeast(0)
1723
3567
  // Slot roots are laid out by React at the unscaled JS inset, without the index gutter.
1724
3568
  slotInsetPx = (horizontalPadding * density).roundToInt()
3569
+ val sidecar = sidecarLayout
3570
+ val contentWidth = recyclerView.width
3571
+ if (sidecar != null && contentWidth > 0) {
3572
+ slotInsetPx = (contentWidth - minOf(contentWidth, sidecar.maxContentWidth)) / 2
3573
+ }
3574
+ val sidecarSpace = (sidecar?.width ?: 0) + (sidecar?.gap ?: 0)
3575
+ val baseSlotInset = slotInsetPx
3576
+ if (sidecar != null && layoutDirection == LAYOUT_DIRECTION_RTL) {
3577
+ slotInsetPx += sidecarSpace
3578
+ slotRightInsetPx = baseSlotInset
3579
+ } else {
3580
+ slotRightInsetPx = baseSlotInset + sidecarSpace
3581
+ }
1725
3582
  configuredTopPaddingPx = dp(topPadding)
1726
3583
  configuredBottomPaddingPx = dp(bottomPadding)
1727
3584
  recyclerView.setPaddingRelative(
1728
- dp(horizontalPadding),
3585
+ if (sidecar == null) dp(horizontalPadding) else baseSlotInset + dp(horizontalPadding),
1729
3586
  configuredTopPaddingPx + coordinatorTopPadding,
1730
- dp(horizontalPadding + indexGutter),
3587
+ if (sidecar == null) dp(horizontalPadding + indexGutter)
3588
+ else baseSlotInset + sidecarSpace + dp(horizontalPadding + indexGutter),
1731
3589
  configuredBottomPaddingPx + coordinatorBottomPadding,
1732
3590
  )
1733
3591
  recyclerView.clipToPadding = false
@@ -2117,15 +3975,16 @@ class NativeListView(
2117
3975
  actionAnchor = record
2118
3976
  // OneKey patch: selector menus anchor to the glyph slot, not its expanded press target.
2119
3977
  val anchorInset = origin.anchorInsetPixels
3978
+ val helpBounds = (origin.sourceView as? NativeListTextView)?.helpAnchorBounds
2120
3979
  return JSONObject()
2121
3980
  .put("token", token)
2122
3981
  .put(
2123
3982
  "windowRect",
2124
3983
  JSONObject()
2125
- .put("x", (location[0] + anchorInset) / density)
2126
- .put("y", (location[1] + anchorInset) / density)
2127
- .put("width", (origin.sourceView.width - anchorInset * 2) / density)
2128
- .put("height", (origin.sourceView.height - anchorInset * 2) / density),
3984
+ .put("x", (location[0] + (helpBounds?.left ?: anchorInset.toFloat())) / density)
3985
+ .put("y", (location[1] + (helpBounds?.top ?: anchorInset.toFloat())) / density)
3986
+ .put("width", (helpBounds?.width() ?: (origin.sourceView.width - anchorInset * 2).toFloat()) / density)
3987
+ .put("height", (helpBounds?.height() ?: (origin.sourceView.height - anchorInset * 2).toFloat()) / density),
2129
3988
  )
2130
3989
  .put("source", origin.source)
2131
3990
  .put("generation", generation)
@@ -2666,6 +4525,7 @@ class NativeListView(
2666
4525
  if (from != RecyclerView.NO_POSITION && to != RecyclerView.NO_POSITION && from != to && reordered != null) {
2667
4526
  val moved = reordered.getOrNull(to)
2668
4527
  if (moved != null) {
4528
+ acceptedKeyIndex = reordered.withIndex().associate { it.value.key to it.index }
2669
4529
  config = config?.copy(items = reordered)
2670
4530
  val payload = JSONObject()
2671
4531
  .put("key", moved.key)
@@ -2849,6 +4709,7 @@ class NativeListView(
2849
4709
  }
2850
4710
 
2851
4711
  private fun checkEndReached() {
4712
+ if (structuralTail != null) return
2852
4713
  val current = config ?: return
2853
4714
  if (!current.loadMore || current.generation == endReachedGeneration || adapter.itemCount == 0) return
2854
4715
  val manager = recyclerView.layoutManager as? LinearLayoutManager ?: return
@@ -3354,7 +5215,7 @@ private class ItemSpacingDecoration(
3354
5215
  * from each edge. Row padding may be scaled or widened by the section-index gutter, so slot
3355
5216
  * holders offset themselves (possibly negatively) back to the JavaScript inset.
3356
5217
  */
3357
- private class ContainerSlotInsetDecoration(private val insetPx: () -> Int) : RecyclerView.ItemDecoration() {
5218
+ private class ContainerSlotInsetDecoration(private val insetsPx: () -> Pair<Int, Int>) : RecyclerView.ItemDecoration() {
3358
5219
  override fun getItemOffsets(
3359
5220
  outRect: android.graphics.Rect,
3360
5221
  view: View,
@@ -3362,9 +5223,9 @@ private class ContainerSlotInsetDecoration(private val insetPx: () -> Int) : Rec
3362
5223
  state: RecyclerView.State,
3363
5224
  ) {
3364
5225
  if (parent.getChildViewHolder(view) !is NativeListContainerSlotAdapter.Holder) return
3365
- val inset = insetPx()
3366
- outRect.left = inset - parent.paddingLeft
3367
- outRect.right = inset - parent.paddingRight
5226
+ val (leftInset, rightInset) = insetsPx()
5227
+ outRect.left = leftInset - parent.paddingLeft
5228
+ outRect.right = rightInset - parent.paddingRight
3368
5229
  }
3369
5230
  }
3370
5231