@onekeyfe/react-native-native-list 6.7.0-15 → 6.7.0-17

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 +187 -1
  9. package/android/src/main/java/com/onekey/nativelist/NativeListLeadingVisual.kt +59 -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 +47 -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 +1877 -41
  19. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingVisualClipPolicyTest.kt +44 -0
  20. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +1 -0
  21. package/docs/ROW_TEMPLATES.md +60 -9
  22. package/docs/SPEC.md +434 -5
  23. package/docs/STYLE_SPEC.md +6 -0
  24. package/ios/HybridNativeList.swift +17 -2
  25. package/ios/NativeListAccessoryStack.swift +227 -39
  26. package/ios/NativeListActivityDetailsView.swift +18 -8
  27. package/ios/NativeListActivityRenderer.swift +8 -2
  28. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  29. package/ios/NativeListDataRowRenderer.swift +155 -27
  30. package/ios/NativeListDesignAssets.swift +3 -0
  31. package/ios/NativeListIdentityRenderer.swift +166 -30
  32. package/ios/NativeListLeadingVisual.swift +49 -14
  33. package/ios/NativeListMessageRenderer.swift +34 -1
  34. package/ios/NativeListModels.swift +42 -2
  35. package/ios/NativeListRendererRegistry.swift +1 -0
  36. package/ios/NativeListResolvedText.swift +2 -1
  37. package/ios/NativeListRowHost.swift +14 -0
  38. package/ios/NativeListSectionHeaderRenderer.swift +88 -0
  39. package/ios/RNCNativeListView.swift +1002 -53
  40. package/ios/Resources/NativeListIcons.xcassets/onekey_crypto_coin_outline.imageset/Contents.json +15 -0
  41. package/ios/Resources/NativeListIcons.xcassets/onekey_crypto_coin_outline.imageset/icon.svg +4 -0
  42. package/ios/Resources/NativeListIcons.xcassets/onekey_gas_solid.imageset/Contents.json +15 -0
  43. package/ios/Resources/NativeListIcons.xcassets/onekey_gas_solid.imageset/icon.svg +3 -0
  44. package/ios/Resources/NativeListIcons.xcassets/onekey_refresh_ccw_outline.imageset/Contents.json +15 -0
  45. package/ios/Resources/NativeListIcons.xcassets/onekey_refresh_ccw_outline.imageset/icon.svg +3 -0
  46. package/ios/tests/NativeListActivityPresentationTests.swift +56 -0
  47. package/ios/tests/NativeListLifecycleTests.swift +2494 -3
  48. package/lib/module/NativeList.js +171 -28
  49. package/lib/module/NativeList.web.js +54 -4
  50. package/lib/module/models.js +1 -0
  51. package/lib/module/selection.js +1 -1
  52. package/lib/module/validation.js +331 -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 +1 -1
  79. package/lib/typescript/src/models.d.ts +105 -9
  80. package/lib/typescript/src/validation.d.ts +10 -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 +307 -44
  102. package/src/NativeList.types.ts +22 -0
  103. package/src/NativeList.web.tsx +75 -8
  104. package/src/index.ts +1 -0
  105. package/src/models.ts +117 -3
  106. package/src/selection.ts +1 -0
  107. package/src/validation.ts +742 -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
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
286
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,841 @@ 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
+ config = next
1613
+ pruneMeasuredRowExtents(next.items)
1614
+ updateContainerSlots()
1615
+ usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
1616
+ adapter.usesSelectorSourceScale = usesSelectorSourceScale
1617
+ adapter.theme = next.theme
1618
+ adapter.listStyle = next.listStyle
1619
+ adapter.layout = next.layout
1620
+ adapter.orientation = next.orientation
1621
+ adapter.selectedKeys = next.selectedKeys
1622
+ if (previous.generation != next.generation) endReachedGeneration = null
1623
+ configureSectionIndex(next)
1624
+ updateLayout(next)
1625
+ bindFooter(next)
1626
+ updateReordering(next)
1627
+ refreshLayout.isEnabled = next.pullToRefresh
1628
+ refreshLayout.setDistanceToTriggerSync(
1629
+ next.refreshTriggerDistance?.let { (it * density).roundToInt() }
1630
+ ?: defaultRefreshTriggerDistancePx,
1631
+ )
1632
+ refreshLayout.isRefreshing = next.refreshing
1633
+ structuralTailCommandActive = true
1634
+ notifyScrollCommand(false, 0)
1635
+ notifyScrollCommand(false, 1)
1636
+ adapter.submitList(next.items.take(prefixCount)) {
1637
+ fun commitPrefix() {
1638
+ if (epoch != structuralTransitionEpoch || disposed ||
1639
+ structuralTail !== (previousTail ?: tail) || structuralTailFinalizing) return
1640
+ if (recyclerView.isComputingLayout) {
1641
+ recyclerView.post { commitPrefix() }
1642
+ return
1643
+ }
1644
+ if (previousTail != null) {
1645
+ clearStructuralTail()
1646
+ structuralTail = tail
1647
+ structuralTailStartExtentPx = startExtent
1648
+ structuralTailStartProgress = 0f
1649
+ structuralTailStartContentY = startContentY
1650
+ structuralTailStartOffset = startOffset
1651
+ structuralTailTargetOffset = startOffset
1652
+ }
1653
+ acceptPendingFooterValues(adjustTailStart = true)
1654
+ structuralTailPreparing = false
1655
+ structuralTailRowsInAdapterPx = 0
1656
+ setStructuralTailExtent(structuralTailStartExtentPx)
1657
+ updateStructuralTailTarget()
1658
+ if (recyclerView.width <= 0 || recyclerView.height <= 0) {
1659
+ finishStructuralTail(interrupted = false)
1660
+ return
1661
+ }
1662
+ applyStructuralTailFrame(tail, epoch, 0f)
1663
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail ||
1664
+ structuralTailFinalizing) return
1665
+ var lastAppliedProgress = 0f
1666
+ var frameScheduled = false
1667
+ fun applyProgress(progress: Float) {
1668
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail ||
1669
+ structuralTailFinalizing) return
1670
+ val nextProgress = maxOf(progress, lastAppliedProgress)
1671
+ if (!applyStructuralTailFrame(tail, epoch, nextProgress)) {
1672
+ if (!frameScheduled) {
1673
+ frameScheduled = true
1674
+ recyclerView.post {
1675
+ frameScheduled = false
1676
+ val current = structuralAnimator?.animatedValue as? Float ?: nextProgress
1677
+ applyProgress(current)
1678
+ }
1679
+ }
1680
+ return
1681
+ }
1682
+ lastAppliedProgress = nextProgress
1683
+ }
1684
+ structuralAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
1685
+ duration = transition.durationMs
1686
+ interpolator = android.view.animation.AccelerateDecelerateInterpolator()
1687
+ addUpdateListener { animation ->
1688
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail) return@addUpdateListener
1689
+ if (Build.VERSION.SDK_INT >= 26 && !ValueAnimator.areAnimatorsEnabled()) {
1690
+ finishStructuralTail(interrupted = false)
1691
+ return@addUpdateListener
1692
+ }
1693
+ applyProgress(animation.animatedValue as Float)
1694
+ }
1695
+ addListener(object : AnimatorListenerAdapter() {
1696
+ override fun onAnimationEnd(animation: Animator) {
1697
+ if (epoch == structuralTransitionEpoch && structuralTail === tail)
1698
+ finishStructuralTail(interrupted = structuralScrollInterrupted)
1699
+ }
1700
+ })
1701
+ start()
1702
+ }
1703
+ }
1704
+ commitPrefix()
1705
+ }
1706
+ }
1707
+
1708
+ private fun updatePrefixTailSnapshot(previous: NativeListConfig, next: NativeListConfig): Boolean {
1709
+ val tail = structuralTail ?: return false
1710
+ if (structuralTailPreparing || structuralTailFinalizing ||
1711
+ structuralTailRowsInAdapterPx > 0 ||
1712
+ previous.items.size != next.items.size ||
1713
+ previous.disclosure != next.disclosure ||
1714
+ previous.layout != next.layout || previous.orientation != next.orientation ||
1715
+ previous.theme?.toString() != next.theme?.toString() ||
1716
+ previous.listStyle?.toString() != next.listStyle?.toString() ||
1717
+ previous.itemSpacing != next.itemSpacing ||
1718
+ previous.contentPadding != next.contentPadding ||
1719
+ previous.contentPaddingTop != next.contentPaddingTop ||
1720
+ previous.contentPaddingBottom != next.contentPaddingBottom ||
1721
+ previous.contentPaddingHorizontal != next.contentPaddingHorizontal) return false
1722
+ for (index in next.items.indices) {
1723
+ val before = previous.items[index]
1724
+ val after = next.items[index]
1725
+ if (before.key != after.key || before.rendererKey != after.rendererKey ||
1726
+ !after.hasExplicitHeight || explicitTailRowHeight(before) != explicitTailRowHeight(after) ||
1727
+ explicitTailRowSpacingPx(before, previous.itemSpacing) !=
1728
+ explicitTailRowSpacingPx(after, next.itemSpacing))
1729
+ return false
1730
+ }
1731
+ config = next
1732
+ adapter.selectedKeys = next.selectedKeys
1733
+ adapter.submitList(next.items.take(tail.prefixCount)) {
1734
+ if (structuralTail !== tail || disposed) return@submitList
1735
+ scheduleVisibleEvent()
1736
+ }
1737
+ if (tail.finalExtent > 0) {
1738
+ for (index in tail.items.indices) {
1739
+ val item = next.items[tail.prefixCount + index]
1740
+ if (tail.items[index].content == item.content) continue
1741
+ tail.items[index] = item
1742
+ tail.hosts[index]?.let { host ->
1743
+ host.bind(item, next.theme, next.layout, "vertical", tail.prefixCount + index,
1744
+ item.json.optBoolean("selected") || next.selectedKeys.contains(item.key),
1745
+ adapter.checkboxState, useSourceScale = usesSelectorSourceScale)
1746
+ host.isClickable = false
1747
+ }
1748
+ }
1749
+ }
1750
+ bindFooter(next)
1751
+ updateStructuralTailTarget()
1752
+ return true
1753
+ }
1754
+
1755
+ private fun updateStructuralFooterHoldPosition() {
1756
+ val targetTop = structuralFooterHoldTop ?: return
1757
+ if (footerSlotAdapter.itemCount == 0) return
1758
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1759
+ layoutManager.findViewByPosition(footerPosition)?.let { footer ->
1760
+ footerSlotAdapter.setVisualTranslationY((targetTop - layoutManager.getDecoratedTop(footer)).toFloat())
1761
+ }
1762
+ }
1763
+
1764
+ private fun updateStructuralFooterVisualPosition() {
1765
+ val startTop = structuralFooterVisualStartTop ?: return
1766
+ val endTop = structuralFooterVisualEndTop ?: return
1767
+ if (footerSlotAdapter.itemCount == 0) return
1768
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1769
+ layoutManager.findViewByPosition(footerPosition)?.let { footer ->
1770
+ val desiredTop = startTop + (endTop - startTop) * structuralFooterVisualProgress
1771
+ footerSlotAdapter.setVisualTranslationY(desiredTop - layoutManager.getDecoratedTop(footer))
1772
+ }
1773
+ }
1774
+
1775
+ private fun cancelStructuralTransition() {
1776
+ if (structuralTail != null) discardStructuralTail()
1777
+ structuralTransitionEpoch += 1
1778
+ pendingStructuralTransition = null
1779
+ pendingStructuralStartScheduled = false
1780
+ structuralAnimator?.cancel()
1781
+ structuralAnimator = null
1782
+ recyclerView.itemAnimator = null
1783
+ setStructuralSpacerHeight(0)
1784
+ footerSlotAdapter.setVisualTranslationY(0f)
1785
+ structuralFooterHoldTop = null
1786
+ structuralFooterVisualStartTop = null
1787
+ structuralFooterVisualEndTop = null
1788
+ structuralFooterVisualProgress = 0f
1789
+ structuralFooterCompensatedHeightPx = null
1790
+ structuralStartSpacerPx = 0
1791
+ }
1792
+
1793
+ private fun startPendingStructuralTransition() {
1794
+ val pending = pendingStructuralTransition ?: return
1795
+ if (pending.epoch != structuralTransitionEpoch || disposed || pendingStructuralStartScheduled) return
1796
+ val expected = config?.items?.map { it.key } ?: return
1797
+ if (adapter.currentList.map { it.key } != expected) return
1798
+ pendingStructuralStartScheduled = true
1799
+ recyclerView.postOnAnimation {
1800
+ if (pending.epoch != structuralTransitionEpoch) return@postOnAnimation
1801
+ pendingStructuralStartScheduled = false
1802
+ val latest = pendingStructuralTransition
1803
+ if (latest?.epoch == pending.epoch && !disposed) {
1804
+ if (recyclerView.isComputingLayout) {
1805
+ startPendingStructuralTransition()
1806
+ return@postOnAnimation
1807
+ }
1808
+ alignPendingStructuralAnchor(latest)
1809
+ if (latest.anchorTop != null || (latest.collapsing && latest.footerStartTop != null)) {
1810
+ relayoutRecyclerViewImmediately()
1811
+ }
1812
+ pendingStructuralTransition = null
1813
+ startStructuralTransition(
1814
+ latest.transition, latest.epoch, latest.anchorKey, latest.anchorTop,
1815
+ latest.footerStartTop,
1816
+ )
1817
+ }
1818
+ }
1819
+ }
1820
+
1821
+ private fun alignPendingStructuralFooter(pending: PendingStructuralTransition): Boolean {
1822
+ val top = pending.footerStartTop ?: return false
1823
+ if (!pending.collapsing || !pending.spacerInserted || footerSlotAdapter.itemCount == 0 || structuralScrollInterrupted) return false
1824
+ if (pending.footerAnchorAppliedTop == top) return false
1825
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1826
+ layoutManager.scrollToPositionWithOffset(footerPosition, top - recyclerView.paddingTop)
1827
+ pendingStructuralTransition = pending.copy(footerAnchorAppliedTop = top)
1828
+ return true
1829
+ }
1830
+
1831
+ private fun alignPendingStructuralRow(pending: PendingStructuralTransition): Boolean {
1832
+ val key = pending.anchorKey ?: return false
1833
+ val top = pending.anchorTop ?: return false
1834
+ if (structuralScrollInterrupted || pending.rowAnchorAppliedTop == top) return false
1835
+ val desiredItems = config?.items ?: return false
1836
+ val rowIndex = desiredItems.indexOfFirst { it.key == key }
1837
+ if (rowIndex < 0 || adapter.itemCount != desiredItems.size ||
1838
+ adapter.currentList.getOrNull(rowIndex)?.key != key) return false
1839
+ layoutManager.scrollToPositionWithOffset(scrollPositionForRow(rowIndex), top - recyclerView.paddingTop)
1840
+ pendingStructuralTransition = pending.copy(rowAnchorAppliedTop = top)
1841
+ return true
1842
+ }
1843
+
1844
+ private fun alignPendingStructuralAnchor(pending: PendingStructuralTransition) {
1845
+ if (pending.anchorTop != null) alignPendingStructuralRow(pending)
1846
+ else alignPendingStructuralFooter(pending)
1847
+ }
1848
+
357
1849
  private fun measuredScrollDistancePx(): Int? {
358
1850
  if (layoutManager.orientation != RecyclerView.VERTICAL) return null
359
1851
  val first = layoutManager.findFirstVisibleItemPosition()
@@ -527,6 +2019,39 @@ class NativeListView(
527
2019
  override fun onDetachedFromWindow() { down?.recycle(); down = null; super.onDetachedFromWindow() }
528
2020
  }
529
2021
  private val stickyPreDraw = android.view.ViewTreeObserver.OnPreDrawListener {
2022
+ if (!commitPreparingFooterFrame()) {
2023
+ if (pendingPreparingFooterFrame?.handoffOnly != true) schedulePreparingFooterFrame()
2024
+ return@OnPreDrawListener false
2025
+ }
2026
+ if (pendingStructuralTransition != null || structuralAnimator != null || structuralTail != null) {
2027
+ val measuredHeightPx = containerSlots.getOrNull(2)?.measuredHeight ?: 0
2028
+ if (measuredHeightPx > 0 && measuredHeightPx != structuralFooterObservedNativeHeightPx) {
2029
+ // React layout can change the footer's contents before its onLayout height reaches JS.
2030
+ val roundedDip = ceil(measuredHeightPx / density.toDouble())
2031
+ val naturalHeight = (roundedDip * density).roundToInt()
2032
+ if (structuralTail != null && config?.disclosure != null &&
2033
+ naturalHeight != footerNaturalHeightPx()) {
2034
+ structuralFooterObservedNativeHeightPx = measuredHeightPx
2035
+ acceptedFooterNaturalHeightPx = naturalHeight
2036
+ structuralFooterCompensatedHeightPx = null
2037
+ finishStructuralTail(interrupted = true)
2038
+ return@OnPreDrawListener false
2039
+ }
2040
+ if (structuralTail != null && structuralTailRowsInAdapterPx > 0 &&
2041
+ !structuralTailFinalizing) {
2042
+ enqueuePreparingFooterFrame(slotHeights.copyOf(), naturalHeight,
2043
+ observedNativeHeight = measuredHeightPx)
2044
+ if (pendingPreparingFooterFrame != null) return@OnPreDrawListener false
2045
+ } else {
2046
+ structuralFooterObservedNativeHeightPx = measuredHeightPx
2047
+ reconcileStructuralFooterHeight(naturalHeight)
2048
+ acceptedFooterNaturalHeightPx = naturalHeight
2049
+ if (structuralTail == null || structuralTailFinalizing) syncFooterPresentation()
2050
+ }
2051
+ }
2052
+ }
2053
+ if (structuralTail != null && !structuralTailFinalizing) layoutFooterPresentationHostNow()
2054
+ if (config?.disclosure != null) layoutExpandedContentHostNow()
530
2055
  updateStickyHeader()
531
2056
  finishScrollCommandIfSettled()
532
2057
  true
@@ -595,7 +2120,7 @@ class NativeListView(
595
2120
  recyclerView.addItemDecoration(reorderPlaceholderDecoration)
596
2121
  // OneKey patch: full-width selector header backgrounds do not change row content insets.
597
2122
  recyclerView.addItemDecoration(SelectorBackgroundDecoration(adapter))
598
- recyclerView.addItemDecoration(ContainerSlotInsetDecoration { slotInsetPx })
2123
+ recyclerView.addItemDecoration(ContainerSlotInsetDecoration { slotInsetPx to slotRightInsetPx })
599
2124
  if (homeOffsetDiagnosticEnabled) layoutManager.onDiagnosticLayout = ::homeOffsetDiagnostic
600
2125
  layoutManager.onBeforeDataLayout = {
601
2126
  if (pendingBodyStartEpoch == readingIntentEpoch && adapter.itemCount > 0 && pendingScrollRequest == null) {
@@ -603,10 +2128,14 @@ class NativeListView(
603
2128
  pendingBodyStartEpoch = null
604
2129
  homeOffsetDiagnostic("first-fill-body-start")
605
2130
  }
2131
+ pendingStructuralTransition?.let(::alignPendingStructuralAnchor)
606
2132
  }
607
2133
  layoutManager.onChildLaidOut = ::recordLaidOutRowExtent
608
2134
  layoutManager.onLayoutPassCompleted = {
2135
+ if (structuralFooterHoldTop != null) updateStructuralFooterHoldPosition()
2136
+ else if (structuralAnimator != null) updateStructuralFooterVisualPosition()
609
2137
  emitScrollPositionThresholdIfNeeded(resync = true)
2138
+ updateSidecarPosition(resync = true)
610
2139
  if (containerSlotRelayoutPending) scheduleContainerSlotRelayout()
611
2140
  if (commandLayoutRequest === acceptedScrollRequest) commandLayoutRequest = null
612
2141
  finishScrollCommandIfSettled()
@@ -618,7 +2147,7 @@ class NativeListView(
618
2147
  val rowPosition = rowPositionForScroll(position)
619
2148
  if (rowPosition !in 0 until adapter.itemCount) return layoutManager.spanCount
620
2149
  val type = adapter.itemAt(rowPosition)?.type
621
- return if (type == "sectionHeader" || type == "system" || type == "action") {
2150
+ return if (type == "sectionHeader" || type == "system" || type == "action" || type == "buttonGroup") {
622
2151
  layoutManager.spanCount
623
2152
  } else {
624
2153
  1
@@ -636,6 +2165,9 @@ class NativeListView(
636
2165
  FrameLayout.LayoutParams.MATCH_PARENT,
637
2166
  ),
638
2167
  )
2168
+ contentContainer.addView(structuralTailLayer, FrameLayout.LayoutParams(0, 0, Gravity.TOP or Gravity.LEFT))
2169
+ contentContainer.addView(sidecarHost,
2170
+ FrameLayout.LayoutParams(0, 0, Gravity.TOP or Gravity.RIGHT))
639
2171
  stickyHeaderHost.visibility = GONE
640
2172
  stickyHeaderHost.addView(stickyHeaderView, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT))
641
2173
  contentContainer.addView(stickyHeaderHost, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.TOP))
@@ -700,6 +2232,9 @@ class NativeListView(
700
2232
  recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
701
2233
  override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
702
2234
  if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
2235
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
2236
+ if (structuralAnimator != null || pendingStructuralTransition != null)
2237
+ structuralScrollInterrupted = true
703
2238
  cancelExecutingScrollCommand()
704
2239
  readingIntentEpoch++
705
2240
  pendingBodyStartEpoch = null
@@ -724,6 +2259,21 @@ class NativeListView(
724
2259
 
725
2260
  override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
726
2261
  logicalScrollDistancePx = (logicalScrollDistancePx + dy).coerceAtLeast(0)
2262
+ if (structuralScrollInterrupted && dy != 0) {
2263
+ if (pendingStructuralTransition != null) {
2264
+ pendingStructuralTransition = pendingStructuralTransition?.let {
2265
+ it.copy(footerStartTop = it.footerStartTop?.minus(dy))
2266
+ }
2267
+ structuralFooterHoldTop = structuralFooterHoldTop?.minus(dy)
2268
+ updateStructuralFooterHoldPosition()
2269
+ } else if (structuralAnimator != null) {
2270
+ structuralFooterVisualStartTop = structuralFooterVisualStartTop?.minus(dy)
2271
+ structuralFooterVisualEndTop = structuralFooterVisualEndTop?.minus(dy)
2272
+ updateStructuralFooterVisualPosition()
2273
+ }
2274
+ }
2275
+ updateSidecarPosition()
2276
+ if (structuralTail != null) updateStructuralTailWindow()
727
2277
  emitScrollPositionThresholdIfNeeded(resync = dx == 0 && dy == 0)
728
2278
  if (dx != 0 || dy != 0) invalidateActionAnchor("scroll")
729
2279
  syncSectionIndexToVisibleRows()
@@ -781,6 +2331,11 @@ class NativeListView(
781
2331
  }
782
2332
  val nextWidth = right - left
783
2333
  val nextHeight = bottom - top
2334
+ val widthChanged = lastLayoutWidth != nextWidth
2335
+ val directionChanged = layoutDirection != lastLayoutDirection
2336
+ if (structuralTail != null && lastLayoutWidth >= 0 &&
2337
+ (widthChanged || lastLayoutHeight != nextHeight || directionChanged))
2338
+ finishStructuralTail(interrupted = true)
784
2339
  if (
785
2340
  lastLayoutWidth >= 0 &&
786
2341
  (nextWidth != lastLayoutWidth || nextHeight != lastLayoutHeight || layoutDirection != lastLayoutDirection)
@@ -790,6 +2345,9 @@ class NativeListView(
790
2345
  lastLayoutWidth = nextWidth
791
2346
  lastLayoutHeight = nextHeight
792
2347
  lastLayoutDirection = layoutDirection
2348
+ if ((widthChanged || directionChanged) && sidecarLayout != null) config?.let(::updateLayout)
2349
+ updateSidecarGeometry()
2350
+ scheduleSidecarSpacer()
793
2351
  updateSectionIndexAttachment()
794
2352
  performPendingScrollIfNeeded()
795
2353
  }
@@ -821,6 +2379,27 @@ class NativeListView(
821
2379
  }
822
2380
 
823
2381
  override fun onDetachedFromWindow() {
2382
+ val disclosureId = activeDisclosureTransitionId
2383
+ if (structuralTail != null) {
2384
+ discardStructuralTail()
2385
+ val epoch = structuralTransitionEpoch
2386
+ config?.let { accepted ->
2387
+ adapter.submitList(accepted.items) {
2388
+ if (!disposed && epoch == structuralTransitionEpoch &&
2389
+ activeDisclosureTransitionId == disclosureId && disclosureId != null) {
2390
+ disclosureFraction = if (accepted.disclosure?.expanded == true) 1f else 0f
2391
+ disclosureTransitioning = false
2392
+ syncDisclosurePresentation()
2393
+ settleDisclosureCommand("interrupted")
2394
+ }
2395
+ }
2396
+ }
2397
+ } else if (disclosureId != null && !disposed) {
2398
+ disclosureFraction = if (config?.disclosure?.expanded == true) 1f else 0f
2399
+ disclosureTransitioning = false
2400
+ syncDisclosurePresentation()
2401
+ settleDisclosureCommand("interrupted")
2402
+ }
824
2403
  val cancelTag = R.id.onekey_native_scroll_coordinator_command_cancel_listener
825
2404
  if (recyclerView.getTag(cancelTag) === coordinatorCommandCancelListener) recyclerView.setTag(cancelTag, null)
826
2405
  cancelExecutingScrollCommand()
@@ -844,6 +2423,83 @@ class NativeListView(
844
2423
  homeOffsetDiagnostic("snapshot-before-nextCount=${next.items.size}")
845
2424
  invalidateActionAnchor("snapshot")
846
2425
  val previous = config
2426
+ val transition = next.structuralTransition
2427
+ val isNewTransition = transition != null && transition.id != consumedStructuralTransitionId
2428
+ if (transition != null) consumedStructuralTransitionId = transition.id
2429
+ val disclosureGeometryInvalid = batchedDisclosureGeometryInvalid ||
2430
+ (!isNewTransition && structuralTail != null &&
2431
+ previous?.disclosure != next.disclosure)
2432
+ batchedDisclosureGeometryInvalid = false
2433
+ if (!isNewTransition &&
2434
+ (next.disclosure == null || previous?.disclosure?.expanded != next.disclosure.expanded)) {
2435
+ activeDisclosureTransitionId = null
2436
+ }
2437
+ val oldKeys = previous?.items?.map { it.key } ?: emptyList()
2438
+ val nextKeys = next.items.map { it.key }
2439
+ if (next.disclosure != null && isNewTransition && previous != null) {
2440
+ activeDisclosureTransitionId = transition?.id
2441
+ directDisclosureStatus = if (oldKeys == nextKeys || nextKeys.isEmpty() ||
2442
+ transition?.durationMs == 0L ||
2443
+ (Build.VERSION.SDK_INT >= 26 && !ValueAnimator.areAnimatorsEnabled()))
2444
+ "completed" else "interrupted"
2445
+ } else if (next.disclosure == null) {
2446
+ activeDisclosureTransitionId = null
2447
+ }
2448
+ val positionDirectCollapse = isNewTransition && !disclosureGeometryInvalid &&
2449
+ next.disclosure?.expanded == false && directDisclosureStatus == "completed"
2450
+ var animateStructure = !disclosureGeometryInvalid && previous != null &&
2451
+ isNewTransition && oldKeys != nextKeys &&
2452
+ previous.orientation == "vertical" &&
2453
+ (previous.layout == "linear" || previous.layout == "table") &&
2454
+ next.orientation == "vertical" && (next.layout == "linear" || next.layout == "table") &&
2455
+ (transition?.durationMs ?: 0) > 0 &&
2456
+ (if (Build.VERSION.SDK_INT >= 26) ValueAnimator.areAnimatorsEnabled() else
2457
+ android.provider.Settings.Global.getFloat(context.contentResolver, "animator_duration_scale", 1f) > 0f)
2458
+ val prefixCount = if (animateStructure && previous != null && recyclerView.width > 0 &&
2459
+ recyclerView.height > 0) prefixTailCount(previous, next) else null
2460
+ val exceedsTailHostLimit = prefixCount != null && previous != null &&
2461
+ exceedsStructuralTailHostLimit(previous, next, prefixCount)
2462
+ if (exceedsTailHostLimit) animateStructure = false
2463
+ if (next.disclosure != null && prefixCount == null) animateStructure = false
2464
+ if (prefixCount != null && !exceedsTailHostLimit && previous != null && transition != null) {
2465
+ startPrefixTailTransition(previous, next, transition, prefixCount)
2466
+ return
2467
+ }
2468
+ var heldTailEpoch: Int? = null
2469
+ if (structuralTail != null) {
2470
+ if (!disclosureGeometryInvalid && !animateStructure && oldKeys == nextKeys &&
2471
+ (Build.VERSION.SDK_INT < 26 || ValueAnimator.areAnimatorsEnabled()) &&
2472
+ previous != null && updatePrefixTailSnapshot(previous, next)) return
2473
+ heldTailEpoch = holdStructuralTailUntilListCommit()
2474
+ // Keep the accepted presentation until the full adapter list has committed.
2475
+ animateStructure = false
2476
+ }
2477
+ val nextKeySet = nextKeys.toHashSet()
2478
+ val visibleAnchor = if (animateStructure) {
2479
+ val first = layoutManager.findFirstVisibleItemPosition()
2480
+ val last = layoutManager.findLastVisibleItemPosition()
2481
+ (first..last).firstNotNullOfOrNull { position ->
2482
+ val rowIndex = rowPositionForScroll(position)
2483
+ oldKeys.getOrNull(rowIndex)?.takeIf(nextKeySet::contains)?.let { key ->
2484
+ layoutManager.findViewByPosition(position)?.let { key to layoutManager.getDecoratedTop(it) }
2485
+ }
2486
+ }
2487
+ } else null
2488
+ val anchorKey = visibleAnchor?.first ?: transition?.anchorKey?.takeIf(nextKeySet::contains)
2489
+ val anchorTop = visibleAnchor?.second
2490
+ val footerStartTop = if (animateStructure && footerSlotAdapter.itemCount > 0) {
2491
+ layoutManager.findViewByPosition(scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount)?.let {
2492
+ layoutManager.getDecoratedTop(it) + it.translationY.roundToInt()
2493
+ }
2494
+ } else null
2495
+ val oldKeySet = oldKeys.toHashSet()
2496
+ val removedExtent = if (animateStructure) previous?.items?.sumOf { item ->
2497
+ if (nextKeySet.contains(item.key)) 0 else estimatedItemExtentPx(item)
2498
+ } ?: 0 else 0
2499
+ val addedExtent = if (animateStructure) next.items.sumOf { item ->
2500
+ if (oldKeySet.contains(item.key)) 0 else estimatedItemExtentPx(item)
2501
+ } else 0
2502
+ if (!animateStructure && oldKeys != nextKeys && heldTailEpoch == null) cancelStructuralTransition()
847
2503
  if (previous?.items?.isEmpty() == true && next.items.isNotEmpty() && adapter.itemCount == 0 &&
848
2504
  pendingScrollRequest == null && recyclerView.scrollState != RecyclerView.SCROLL_STATE_DRAGGING &&
849
2505
  !recyclerView.canScrollVertically(-1) && layoutManager.findFirstVisibleItemPosition() == 0) {
@@ -867,6 +2523,10 @@ class NativeListView(
867
2523
  }
868
2524
  }.toSet()
869
2525
  config = next
2526
+ if (heldTailEpoch == null) {
2527
+ disclosureFraction = if (next.disclosure?.expanded == true) 1f else 0f
2528
+ disclosureTransitioning = false
2529
+ }
870
2530
  updateContainerSlots()
871
2531
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
872
2532
  adapter.usesSelectorSourceScale = usesSelectorSourceScale
@@ -879,14 +2539,29 @@ class NativeListView(
879
2539
  // outside the adapter, so a listStyle-only snapshot must rebind it here.
880
2540
  if (previous.listStyle?.toString() != next.listStyle?.toString()) bindFooter(next)
881
2541
  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()
2542
+ val committed: () -> Unit = {
2543
+ homeOffsetDiagnostic("snapshot-stable-submit-commit")
2544
+ // OneKey patch: DiffUtil has dispatched its payloads; release the old serialized rows.
2545
+ next.items.forEach { it.selectionUpdateFromContent = null }
2546
+ recyclerView.post {
2547
+ scheduleSidecarSpacer()
2548
+ startPendingStructuralTransition()
2549
+ bindVisibleSelection(changedSummaryKeys)
2550
+ bindFooterSelection()
2551
+ performPendingScrollIfNeeded()
2552
+ if (next.disclosure != null && (isNewTransition || disclosureGeometryInvalid) &&
2553
+ transition != null && activeDisclosureTransitionId == transition.id) {
2554
+ relayoutRecyclerViewImmediately()
2555
+ if (positionDirectCollapse && heldTailEpoch == null)
2556
+ positionSettledDisclosureToggle()
2557
+ settleDisclosureCommand(if (disclosureGeometryInvalid) "interrupted" else
2558
+ directDisclosureStatus)
2559
+ }
2560
+ }
889
2561
  }
2562
+ if (heldTailEpoch != null) completeHeldTailCommit(next, heldTailEpoch, committed,
2563
+ positionDirectCollapse)
2564
+ else committed()
890
2565
  }
891
2566
  return
892
2567
  }
@@ -906,6 +2581,10 @@ class NativeListView(
906
2581
  }
907
2582
  } else null
908
2583
  config = next
2584
+ if (heldTailEpoch == null) {
2585
+ disclosureFraction = if (next.disclosure?.expanded == true) 1f else 0f
2586
+ disclosureTransitioning = false
2587
+ }
909
2588
  pruneMeasuredRowExtents(next.items)
910
2589
  updateContainerSlots()
911
2590
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
@@ -919,16 +2598,61 @@ class NativeListView(
919
2598
  adapter.selectedKeys = next.selectedKeys
920
2599
  configureSectionIndex(next)
921
2600
  updateLayout(next)
2601
+ if (animateStructure && transition != null) {
2602
+ structuralTransitionEpoch += 1
2603
+ pendingStructuralStartScheduled = false
2604
+ structuralAnimator?.cancel()
2605
+ structuralAnimator = null
2606
+ structuralScrollInterrupted = false
2607
+ structuralFooterHoldTop = footerStartTop
2608
+ structuralFooterCompensatedHeightPx = slotHeights[2]
2609
+ val held = (structuralSpacerHeightPx + removedExtent - addedExtent).coerceAtLeast(0)
2610
+ pendingStructuralTransition = PendingStructuralTransition(
2611
+ transition, structuralTransitionEpoch, anchorKey, anchorTop, footerStartTop, held,
2612
+ removedExtent > addedExtent,
2613
+ )
2614
+ recyclerView.itemAnimator = DefaultItemAnimator().apply {
2615
+ addDuration = transition.durationMs
2616
+ removeDuration = transition.durationMs
2617
+ moveDuration = 0
2618
+ changeDuration = 0
2619
+ supportsChangeAnimations = false
2620
+ }
2621
+ }
922
2622
  adapter.submitList(next.items) {
923
- homeOffsetDiagnostic("snapshot-submit-commit-marketAnchor=${marketStartOffset != null}")
924
- if (marketStartOffset != null) {
925
- layoutManager.scrollToPositionWithOffset(scrollPositionForRow(0), marketStartOffset)
2623
+ val committed: () -> Unit = {
2624
+ pendingStructuralTransition?.takeIf { it.epoch == structuralTransitionEpoch }?.let {
2625
+ setStructuralSpacerHeight(it.heldHeightPx)
2626
+ pendingStructuralTransition = it.copy(spacerInserted = true)
2627
+ pendingStructuralTransition?.let(::alignPendingStructuralAnchor)
2628
+ }
2629
+ homeOffsetDiagnostic("snapshot-submit-commit-marketAnchor=${marketStartOffset != null}")
2630
+ if (marketStartOffset != null) {
2631
+ layoutManager.scrollToPositionWithOffset(scrollPositionForRow(0), marketStartOffset)
2632
+ }
2633
+ relayoutContents(preserveMarketPaginationAnchor)
2634
+ scheduleSidecarSpacer()
2635
+ startPendingStructuralTransition()
2636
+ performPendingScrollIfNeeded()
2637
+ syncSectionIndexToVisibleRows()
2638
+ scheduleVisibleEvent()
2639
+ if (next.items.isNotEmpty()) checkEndReached()
2640
+ if (next.disclosure != null && (isNewTransition || disclosureGeometryInvalid) &&
2641
+ transition != null && activeDisclosureTransitionId == transition.id) {
2642
+ recyclerView.post {
2643
+ if (!disposed && activeDisclosureTransitionId == transition.id) {
2644
+ relayoutRecyclerViewImmediately()
2645
+ if (positionDirectCollapse && heldTailEpoch == null)
2646
+ positionSettledDisclosureToggle()
2647
+ settleDisclosureCommand(if (disclosureGeometryInvalid) "interrupted" else
2648
+ directDisclosureStatus)
2649
+ }
2650
+ }
2651
+ }
926
2652
  }
927
- relayoutContents(preserveMarketPaginationAnchor)
928
- performPendingScrollIfNeeded()
929
- syncSectionIndexToVisibleRows()
930
- scheduleVisibleEvent()
931
- if (next.items.isNotEmpty()) checkEndReached()
2653
+ if (heldTailEpoch != null) completeHeldTailCommit(next, heldTailEpoch, committed,
2654
+ positionDirectCollapse)
2655
+ else committed()
932
2656
  }
933
2657
  refreshLayout.isEnabled = next.pullToRefresh
934
2658
  refreshLayout.setDistanceToTriggerSync(next.refreshTriggerDistance?.let { (it * density).roundToInt() } ?: defaultRefreshTriggerDistancePx)
@@ -937,6 +2661,85 @@ class NativeListView(
937
2661
  updateReordering(next)
938
2662
  }
939
2663
 
2664
+ private fun startStructuralTransition(
2665
+ transition: NativeListConfig.StructuralTransition,
2666
+ epoch: Int,
2667
+ anchorKey: String?,
2668
+ anchorTop: Int?,
2669
+ footerStartTop: Int?,
2670
+ ) {
2671
+ structuralFooterHoldTop = null
2672
+ val startSpacer = structuralSpacerHeightPx
2673
+ structuralStartSpacerPx = startSpacer
2674
+ structuralFooterVisualStartTop = footerStartTop
2675
+ structuralFooterVisualProgress = 0f
2676
+ val startOffset = measuredScrollDistancePx()?.also { logicalScrollDistancePx = it }
2677
+ ?: logicalScrollDistancePx
2678
+ val anchorIndex = anchorKey?.let { key -> adapter.currentList.indexOfFirst { it.key == key } }
2679
+ val currentAnchorTop = anchorIndex?.takeIf { it >= 0 }?.let { index ->
2680
+ layoutManager.findViewByPosition(scrollPositionForRow(index))?.let(layoutManager::getDecoratedTop)
2681
+ }
2682
+ val anchorDelta = if (anchorTop != null && currentAnchorTop != null) currentAnchorTop - anchorTop else 0
2683
+ val leftFinal = (sidecarLeftExtentPx() - startSpacer).coerceAtLeast(0)
2684
+ val sidecarBottom = if (sidecarLayout != null)
2685
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom else 0
2686
+ val finalMax = (max(leftFinal, sidecarBottom) - recyclerView.height).coerceAtLeast(0)
2687
+ var targetOffset = (startOffset + anchorDelta).coerceIn(0, finalMax)
2688
+ if (anchorTop == null && anchorIndex != null && anchorIndex >= 0) {
2689
+ val fallbackTop = nativeListScrollPrefixPx(
2690
+ scrollPositionForRow(anchorIndex),
2691
+ layoutManager.spanCount,
2692
+ layoutManager.spanSizeLookup::getSpanSize,
2693
+ ::estimatedScrollExtentPx,
2694
+ ).coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
2695
+ targetOffset = minOf(targetOffset, fallbackTop)
2696
+ }
2697
+ structuralFooterVisualEndTop = if (footerStartTop != null && footerSlotAdapter.itemCount > 0) {
2698
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
2699
+ val finalPrefix = nativeListScrollPrefixPx(
2700
+ footerPosition,
2701
+ layoutManager.spanCount,
2702
+ layoutManager.spanSizeLookup::getSpanSize,
2703
+ ::estimatedScrollExtentPx,
2704
+ ) - startSpacer
2705
+ (finalPrefix + recyclerView.paddingTop - targetOffset)
2706
+ .coerceIn(Int.MIN_VALUE.toLong(), Int.MAX_VALUE.toLong()).toInt()
2707
+ } else null
2708
+ structuralAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
2709
+ duration = transition.durationMs
2710
+ interpolator = android.view.animation.AccelerateDecelerateInterpolator()
2711
+ addUpdateListener { animation ->
2712
+ if (epoch != structuralTransitionEpoch || disposed) return@addUpdateListener
2713
+ val fraction = animation.animatedValue as Float
2714
+ structuralFooterVisualProgress = fraction
2715
+ setStructuralSpacerHeight((structuralStartSpacerPx * (1f - fraction)).roundToInt())
2716
+ measuredScrollDistancePx()?.let { logicalScrollDistancePx = it }
2717
+ val finalLeftExtent = (sidecarLeftExtentPx() - structuralSpacerHeightPx).coerceAtLeast(0)
2718
+ val finalMaximum = (max(finalLeftExtent, sidecarBottom) - recyclerView.height).coerceAtLeast(0)
2719
+ val desired = (startOffset + (minOf(targetOffset, finalMaximum) - startOffset) * fraction).roundToInt()
2720
+ if (!structuralScrollInterrupted && recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE)
2721
+ recyclerView.scrollBy(0, desired - logicalScrollDistancePx)
2722
+ updateStructuralFooterVisualPosition()
2723
+ }
2724
+ addListener(object : AnimatorListenerAdapter() {
2725
+ override fun onAnimationEnd(animation: Animator) {
2726
+ if (epoch != structuralTransitionEpoch) return
2727
+ structuralAnimator = null
2728
+ recyclerView.itemAnimator = null
2729
+ setStructuralSpacerHeight(0)
2730
+ scheduleSidecarSpacer()
2731
+ footerSlotAdapter.setVisualTranslationY(0f)
2732
+ structuralFooterVisualStartTop = null
2733
+ structuralFooterVisualEndTop = null
2734
+ structuralFooterVisualProgress = 0f
2735
+ structuralFooterCompensatedHeightPx = null
2736
+ structuralStartSpacerPx = 0
2737
+ }
2738
+ })
2739
+ start()
2740
+ }
2741
+ }
2742
+
940
2743
  private fun captureVisibleMarketAnchor(): VisibleMarketAnchor? {
941
2744
  val position = rowPositionForScroll(layoutManager.findFirstVisibleItemPosition()).coerceAtLeast(0)
942
2745
  if (position == RecyclerView.NO_POSITION) return null
@@ -1148,12 +2951,23 @@ class NativeListView(
1148
2951
  }
1149
2952
  if (!marketQuoteOnly) invalidateActionAnchor("snapshot")
1150
2953
  val next = current.copy(items = nextItems, selectedKeys = selected)
2954
+ if (structuralTail != null && updatePrefixTailSnapshot(current, next)) return
2955
+ val heldTailEpoch = if (structuralTail != null) holdStructuralTailUntilListCommit() else null
1151
2956
  config = next
1152
2957
  updateContainerSlots()
1153
2958
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
1154
2959
  adapter.usesSelectorSourceScale = usesSelectorSourceScale
1155
2960
  adapter.selectedKeys = selected
1156
- adapter.submitList(nextItems) { relayoutContents() }
2961
+ adapter.submitList(nextItems) {
2962
+ if (heldTailEpoch != null) {
2963
+ if (heldTailEpoch != structuralTransitionEpoch || disposed) return@submitList
2964
+ val acceptedPendingFooter = acceptPendingFooterValues(adjustTailStart = false)
2965
+ clearStructuralTail()
2966
+ if (acceptedPendingFooter) updateContainerSlots()
2967
+ setStructuralSpacerHeight(0)
2968
+ }
2969
+ relayoutContents()
2970
+ }
1157
2971
  bindFooter(next)
1158
2972
  }
1159
2973
 
@@ -1215,6 +3029,7 @@ class NativeListView(
1215
3029
  is ScrollRequest.End -> true
1216
3030
  }
1217
3031
  if (!valid) return
3032
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
1218
3033
  executingScrollCommand = false
1219
3034
  dispatchingScrollRequest = null
1220
3035
  commandLayoutRequest = null
@@ -1240,6 +3055,7 @@ class NativeListView(
1240
3055
 
1241
3056
  private val coordinatorCommandCancelListener = Runnable {
1242
3057
  if (disposed) return@Runnable
3058
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
1243
3059
  pendingScrollRequest = null
1244
3060
  readingIntentEpoch++
1245
3061
  pendingBodyStartEpoch = null
@@ -1353,7 +3169,8 @@ class NativeListView(
1353
3169
  }
1354
3170
  is ScrollRequest.End -> {
1355
3171
  val finalSlotHeight = when {
1356
- footerSlotAdapter.itemCount > 0 -> slotHeights[2]
3172
+ sidecarSpacerAdapter.itemCount > 0 -> sidecarSpacerHeightPx
3173
+ footerSlotAdapter.itemCount > 0 -> footerPresentedHeightPx()
1357
3174
  emptySlotAdapter.itemCount > 0 -> slotHeights[1]
1358
3175
  adapter.itemCount == 0 && headerSlotAdapter.itemCount > 0 -> slotHeights[0]
1359
3176
  else -> null
@@ -1648,6 +3465,7 @@ class NativeListView(
1648
3465
  fun dispose() {
1649
3466
  if (disposed) return
1650
3467
  disposed = true
3468
+ if (structuralTail != null) discardStructuralTail()
1651
3469
  val cancelTag = R.id.onekey_native_scroll_coordinator_command_cancel_listener
1652
3470
  if (recyclerView.getTag(cancelTag) === coordinatorCommandCancelListener) recyclerView.setTag(cancelTag, null)
1653
3471
  containerSlotRelayoutPending = false
@@ -1658,6 +3476,8 @@ class NativeListView(
1658
3476
  private fun disposeResources() {
1659
3477
  if (resourcesDisposed) return
1660
3478
  resourcesDisposed = true
3479
+ cancelStructuralTransition()
3480
+ recyclerView.itemAnimator = null
1661
3481
  stopSectionIndexAttachmentTracking()
1662
3482
  scheduleSectionIndexAttachmentToList()
1663
3483
  stopReorderRelayoutLoop()
@@ -1722,12 +3542,26 @@ class NativeListView(
1722
3542
  val coordinatorBottomPadding = (recyclerView.paddingBottom - configuredBottomPaddingPx).coerceAtLeast(0)
1723
3543
  // Slot roots are laid out by React at the unscaled JS inset, without the index gutter.
1724
3544
  slotInsetPx = (horizontalPadding * density).roundToInt()
3545
+ val sidecar = sidecarLayout
3546
+ val contentWidth = recyclerView.width
3547
+ if (sidecar != null && contentWidth > 0) {
3548
+ slotInsetPx = (contentWidth - minOf(contentWidth, sidecar.maxContentWidth)) / 2
3549
+ }
3550
+ val sidecarSpace = (sidecar?.width ?: 0) + (sidecar?.gap ?: 0)
3551
+ val baseSlotInset = slotInsetPx
3552
+ if (sidecar != null && layoutDirection == LAYOUT_DIRECTION_RTL) {
3553
+ slotInsetPx += sidecarSpace
3554
+ slotRightInsetPx = baseSlotInset
3555
+ } else {
3556
+ slotRightInsetPx = baseSlotInset + sidecarSpace
3557
+ }
1725
3558
  configuredTopPaddingPx = dp(topPadding)
1726
3559
  configuredBottomPaddingPx = dp(bottomPadding)
1727
3560
  recyclerView.setPaddingRelative(
1728
- dp(horizontalPadding),
3561
+ if (sidecar == null) dp(horizontalPadding) else baseSlotInset + dp(horizontalPadding),
1729
3562
  configuredTopPaddingPx + coordinatorTopPadding,
1730
- dp(horizontalPadding + indexGutter),
3563
+ if (sidecar == null) dp(horizontalPadding + indexGutter)
3564
+ else baseSlotInset + sidecarSpace + dp(horizontalPadding + indexGutter),
1731
3565
  configuredBottomPaddingPx + coordinatorBottomPadding,
1732
3566
  )
1733
3567
  recyclerView.clipToPadding = false
@@ -2117,15 +3951,16 @@ class NativeListView(
2117
3951
  actionAnchor = record
2118
3952
  // OneKey patch: selector menus anchor to the glyph slot, not its expanded press target.
2119
3953
  val anchorInset = origin.anchorInsetPixels
3954
+ val helpBounds = (origin.sourceView as? NativeListTextView)?.helpAnchorBounds
2120
3955
  return JSONObject()
2121
3956
  .put("token", token)
2122
3957
  .put(
2123
3958
  "windowRect",
2124
3959
  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),
3960
+ .put("x", (location[0] + (helpBounds?.left ?: anchorInset.toFloat())) / density)
3961
+ .put("y", (location[1] + (helpBounds?.top ?: anchorInset.toFloat())) / density)
3962
+ .put("width", (helpBounds?.width() ?: (origin.sourceView.width - anchorInset * 2).toFloat()) / density)
3963
+ .put("height", (helpBounds?.height() ?: (origin.sourceView.height - anchorInset * 2).toFloat()) / density),
2129
3964
  )
2130
3965
  .put("source", origin.source)
2131
3966
  .put("generation", generation)
@@ -2849,6 +4684,7 @@ class NativeListView(
2849
4684
  }
2850
4685
 
2851
4686
  private fun checkEndReached() {
4687
+ if (structuralTail != null) return
2852
4688
  val current = config ?: return
2853
4689
  if (!current.loadMore || current.generation == endReachedGeneration || adapter.itemCount == 0) return
2854
4690
  val manager = recyclerView.layoutManager as? LinearLayoutManager ?: return
@@ -3354,7 +5190,7 @@ private class ItemSpacingDecoration(
3354
5190
  * from each edge. Row padding may be scaled or widened by the section-index gutter, so slot
3355
5191
  * holders offset themselves (possibly negatively) back to the JavaScript inset.
3356
5192
  */
3357
- private class ContainerSlotInsetDecoration(private val insetPx: () -> Int) : RecyclerView.ItemDecoration() {
5193
+ private class ContainerSlotInsetDecoration(private val insetsPx: () -> Pair<Int, Int>) : RecyclerView.ItemDecoration() {
3358
5194
  override fun getItemOffsets(
3359
5195
  outRect: android.graphics.Rect,
3360
5196
  view: View,
@@ -3362,9 +5198,9 @@ private class ContainerSlotInsetDecoration(private val insetPx: () -> Int) : Rec
3362
5198
  state: RecyclerView.State,
3363
5199
  ) {
3364
5200
  if (parent.getChildViewHolder(view) !is NativeListContainerSlotAdapter.Holder) return
3365
- val inset = insetPx()
3366
- outRect.left = inset - parent.paddingLeft
3367
- outRect.right = inset - parent.paddingRight
5201
+ val (leftInset, rightInset) = insetsPx()
5202
+ outRect.left = leftInset - parent.paddingLeft
5203
+ outRect.right = rightInset - parent.paddingRight
3368
5204
  }
3369
5205
  }
3370
5206