@onekeyfe/react-native-native-list 6.7.0-5 → 6.7.0-51

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 (214) hide show
  1. package/README.md +312 -375
  2. package/android/src/main/java/com/onekey/nativelist/HybridNativeList.kt +14 -1
  3. package/android/src/main/java/com/onekey/nativelist/NativeListAccessoryStack.kt +250 -9
  4. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +35 -7
  5. package/android/src/main/java/com/onekey/nativelist/NativeListActivityRenderer.kt +25 -3
  6. package/android/src/main/java/com/onekey/nativelist/NativeListAdapter.kt +17 -1
  7. package/android/src/main/java/com/onekey/nativelist/NativeListButtonGroupRenderer.kt +102 -0
  8. package/android/src/main/java/com/onekey/nativelist/NativeListContainerSlotAdapter.kt +12 -0
  9. package/android/src/main/java/com/onekey/nativelist/NativeListDataRowRenderer.kt +102 -7
  10. package/android/src/main/java/com/onekey/nativelist/NativeListGeneratedIcons.kt +47 -0
  11. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +225 -11
  12. package/android/src/main/java/com/onekey/nativelist/NativeListLeadingVisual.kt +152 -33
  13. package/android/src/main/java/com/onekey/nativelist/NativeListMarketRenderer.kt +92 -28
  14. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPlaceholderView.kt +244 -0
  15. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPreviewSlot.kt +66 -31
  16. package/android/src/main/java/com/onekey/nativelist/NativeListMediaTileRenderer.kt +32 -11
  17. package/android/src/main/java/com/onekey/nativelist/NativeListMessageRenderer.kt +25 -0
  18. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +149 -3
  19. package/android/src/main/java/com/onekey/nativelist/NativeListPrimitives.kt +120 -287
  20. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRegistry.kt +2 -0
  21. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRowView.kt +7 -0
  22. package/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +3 -2
  23. package/android/src/main/java/com/onekey/nativelist/NativeListSectionHeaderRenderer.kt +69 -0
  24. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +55 -1
  25. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +1978 -136
  26. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListActivityHostClipPolicyTest.kt +35 -0
  27. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListIdentityTrailingAxisTest.kt +36 -0
  28. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingSlotFrameTest.kt +68 -0
  29. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingVisualClipPolicyTest.kt +44 -0
  30. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +10 -0
  31. package/docs/ROW_TEMPLATES.md +74 -13
  32. package/docs/SPEC.md +1232 -16
  33. package/docs/STYLE_SPEC.md +14 -0
  34. package/ios/HybridNativeList.swift +21 -2
  35. package/ios/NativeListAccessoryStack.swift +237 -51
  36. package/ios/NativeListActivityDetailsView.swift +30 -11
  37. package/ios/NativeListActivityRenderer.swift +8 -2
  38. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  39. package/ios/NativeListDataRowRenderer.swift +167 -30
  40. package/ios/NativeListDesignAssets.swift +13 -75
  41. package/ios/NativeListGeneratedIcons.swift +55 -0
  42. package/ios/NativeListIconBinding.swift +171 -0
  43. package/ios/NativeListIdentityRenderer.swift +256 -39
  44. package/ios/NativeListLeadingVisual.swift +127 -28
  45. package/ios/NativeListMarketRenderer.swift +120 -31
  46. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  47. package/ios/NativeListMediaPreviewSlot.swift +122 -61
  48. package/ios/NativeListMediaTileRenderer.swift +15 -11
  49. package/ios/NativeListMessageRenderer.swift +34 -1
  50. package/ios/NativeListMetricCardRenderer.swift +4 -2
  51. package/ios/NativeListModels.swift +42 -2
  52. package/ios/NativeListRendererRegistry.swift +1 -0
  53. package/ios/NativeListResolvedText.swift +2 -1
  54. package/ios/NativeListRowHost.swift +14 -0
  55. package/ios/NativeListSectionHeaderRenderer.swift +100 -4
  56. package/ios/RNCNativeListView.swift +1093 -59
  57. package/ios/tests/NativeListAccessoryStackTests.swift +101 -0
  58. package/ios/tests/NativeListAccountSelectorLayoutTests.swift +96 -0
  59. package/ios/tests/NativeListActivityPresentationTests.swift +153 -0
  60. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +81 -0
  61. package/ios/tests/NativeListLeadingVisualPairBackdropTests.swift +50 -0
  62. package/ios/tests/NativeListLifecycleTests.swift +2915 -4
  63. package/ios/tests/NativeListMarketMetricsTests.swift +117 -0
  64. package/ios/tests/NativeListMediaVisibilityTests.swift +26 -1
  65. package/ios/tests/NativeListSharedIconTests.swift +236 -0
  66. package/lib/module/NativeList.js +236 -38
  67. package/lib/module/NativeList.web.js +167 -46
  68. package/lib/module/index.js +1 -1
  69. package/lib/module/models.js +3 -0
  70. package/lib/module/selection.js +1 -1
  71. package/lib/module/validation.js +1246 -48
  72. package/lib/module/web/NativeListGeneratedIcons.js +31 -0
  73. package/lib/module/web/NativeListWebEngine.js +513 -275
  74. package/lib/module/web/templates/ActivityRowRenderer.js +12 -31
  75. package/lib/module/web/templates/ButtonGroupRowRenderer.js +47 -0
  76. package/lib/module/web/templates/DataRowRenderer.js +40 -5
  77. package/lib/module/web/templates/IdentityRowRenderer.js +158 -6
  78. package/lib/module/web/templates/MarketTableRowRenderer.js +36 -19
  79. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -25
  80. package/lib/module/web/templates/MessageRowRenderer.js +18 -2
  81. package/lib/module/web/templates/RowContainerStyle.js +1 -0
  82. package/lib/module/web/templates/RowRendererRegistry.js +3 -0
  83. package/lib/module/web/templates/SectionHeaderRowRenderer.js +36 -2
  84. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  85. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  86. package/lib/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  87. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  88. package/lib/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  89. package/lib/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  90. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  91. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  92. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  93. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  94. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  95. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  96. package/lib/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  97. package/lib/typescript/src/NativeList.d.ts +3 -3
  98. package/lib/typescript/src/NativeList.nitro.d.ts +2 -0
  99. package/lib/typescript/src/NativeList.types.d.ts +20 -2
  100. package/lib/typescript/src/index.d.ts +2 -2
  101. package/lib/typescript/src/models.d.ts +126 -17
  102. package/lib/typescript/src/validation.d.ts +20 -0
  103. package/lib/typescript/src/web/NativeListGeneratedIcons.d.ts +2 -0
  104. package/lib/typescript/src/web/NativeListWebEngine.d.ts +32 -1
  105. package/lib/typescript/src/web/templates/ButtonGroupRowRenderer.d.ts +14 -0
  106. package/lib/typescript/src/web/templates/IdentityRowRenderer.d.ts +1 -1
  107. package/lib/typescript/src/web/templates/MessageRowRenderer.d.ts +9 -3
  108. package/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  109. package/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  110. package/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  111. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  112. package/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  113. package/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  114. package/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  115. package/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  116. package/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  117. package/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  118. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  119. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  120. package/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  121. package/package.json +16 -10
  122. package/react-native-native-list.podspec +2 -6
  123. package/scripts/generate-icons.mjs +150 -0
  124. package/scripts/generate-icons.test.mjs +288 -0
  125. package/scripts/native-list-icons.json +260 -0
  126. package/src/NativeList.nitro.ts +2 -0
  127. package/src/NativeList.tsx +439 -91
  128. package/src/NativeList.types.ts +24 -2
  129. package/src/NativeList.web.tsx +295 -89
  130. package/src/index.ts +2 -0
  131. package/src/models.ts +263 -144
  132. package/src/selection.ts +1 -0
  133. package/src/validation.ts +3013 -152
  134. package/src/web/NativeListGeneratedIcons.ts +28 -0
  135. package/src/web/NativeListWebEngine.ts +818 -343
  136. package/src/web/templates/ActivityRowRenderer.ts +29 -59
  137. package/src/web/templates/ButtonGroupRowRenderer.ts +58 -0
  138. package/src/web/templates/DataRowRenderer.ts +93 -20
  139. package/src/web/templates/IdentityRowRenderer.ts +231 -6
  140. package/src/web/templates/MarketTableRowRenderer.ts +53 -33
  141. package/src/web/templates/MediaTileRowRenderer.ts +90 -28
  142. package/src/web/templates/MessageRowRenderer.ts +23 -7
  143. package/src/web/templates/RowContainerStyle.ts +2 -0
  144. package/src/web/templates/RowRendererRegistry.ts +11 -1
  145. package/src/web/templates/SectionHeaderRowRenderer.ts +47 -4
  146. package/ios/Resources/NativeListIcons.xcassets/Contents.json +0 -1
  147. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/Contents.json +0 -1
  148. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/icon.svg +0 -1
  149. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/Contents.json +0 -1
  150. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/icon.svg +0 -1
  151. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/Contents.json +0 -1
  152. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/icon.svg +0 -1
  153. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/Contents.json +0 -1
  154. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/icon.svg +0 -1
  155. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/Contents.json +0 -1
  156. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/icon.svg +0 -1
  157. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/Contents.json +0 -1
  158. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/icon.svg +0 -1
  159. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/Contents.json +0 -1
  160. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/icon.svg +0 -1
  161. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/Contents.json +0 -1
  162. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/icon.svg +0 -1
  163. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/Contents.json +0 -1
  164. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/icon.svg +0 -1
  165. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/Contents.json +0 -1
  166. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/icon.svg +0 -1
  167. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/Contents.json +0 -1
  168. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/icon.svg +0 -1
  169. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/Contents.json +0 -1
  170. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/icon.svg +0 -1
  171. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/Contents.json +0 -1
  172. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/icon.svg +0 -1
  173. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/Contents.json +0 -1
  174. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/icon.svg +0 -1
  175. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/Contents.json +0 -1
  176. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/icon.svg +0 -1
  177. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/Contents.json +0 -1
  178. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/icon.svg +0 -1
  179. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/Contents.json +0 -1
  180. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/icon.svg +0 -1
  181. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/Contents.json +0 -1
  182. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/icon.svg +0 -1
  183. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/Contents.json +0 -1
  184. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/icon.svg +0 -1
  185. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/Contents.json +0 -1
  186. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/icon.svg +0 -1
  187. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/Contents.json +0 -1
  188. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/icon.svg +0 -1
  189. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/Contents.json +0 -15
  190. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/icon.svg +0 -14
  191. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/Contents.json +0 -15
  192. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/icon.svg +0 -12
  193. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/Contents.json +0 -15
  194. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/icon.svg +0 -6
  195. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/Contents.json +0 -15
  196. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/icon.svg +0 -15
  197. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/Contents.json +0 -15
  198. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/icon.svg +0 -3
  199. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/Contents.json +0 -15
  200. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/icon.svg +0 -7
  201. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/Contents.json +0 -15
  202. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/icon.svg +0 -18
  203. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/Contents.json +0 -15
  204. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/icon.svg +0 -7
  205. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/Contents.json +0 -1
  206. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/icon.svg +0 -1
  207. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/Contents.json +0 -1
  208. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/icon.svg +0 -1
  209. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/Contents.json +0 -1
  210. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/icon.svg +0 -1
  211. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/Contents.json +0 -1
  212. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/icon.svg +0 -1
  213. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/Contents.json +0 -1
  214. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/icon.svg +0 -1
@@ -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,9 @@ 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
49
+ import com.facebook.react.uimanager.events.NativeGestureUtil
42
50
  import com.margelo.nitro.nativelogger.OneKeyLog
43
51
  import org.json.JSONArray
44
52
  import org.json.JSONObject
@@ -62,13 +70,10 @@ private class NativeListGridLayoutManager(
62
70
  var onChildLaidOut: ((View, Int) -> Unit)? = null
63
71
  var onLayoutPassCompleted: (() -> Unit)? = null
64
72
  var onBeforeDataLayout: (() -> Unit)? = null
65
- var onDiagnosticLayout: ((String, RecyclerView.State) -> Unit)? = null
66
73
 
67
74
  override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
68
- onDiagnosticLayout?.invoke("layout-children-before", state)
69
75
  if (!state.isPreLayout) onBeforeDataLayout?.invoke()
70
76
  super.onLayoutChildren(recycler, state)
71
- onDiagnosticLayout?.invoke("layout-children-after", state)
72
77
  }
73
78
 
74
79
  // Scroll fills and layout passes both place children here, including rows that a
@@ -80,7 +85,6 @@ private class NativeListGridLayoutManager(
80
85
 
81
86
  override fun onLayoutCompleted(state: RecyclerView.State) {
82
87
  super.onLayoutCompleted(state)
83
- onDiagnosticLayout?.invoke("layout-completed", state)
84
88
  onLayoutPassCompleted?.invoke()
85
89
  }
86
90
 
@@ -105,6 +109,7 @@ class NativeListView(
105
109
 
106
110
  fun setFontFamiliesJson(json: String) {
107
111
  if (!fonts.configure(json)) return
112
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
108
113
  invalidateActionAnchor("layout")
109
114
  measuredRowExtentsPx.clear()
110
115
  measuredRowExtentSumPx = 0L
@@ -200,67 +205,251 @@ class NativeListView(
200
205
  var onReorder: ((String) -> Unit)? = null
201
206
  var onEndReached: ((String) -> Unit)? = null
202
207
  var onVisibleRangeChanged: ((String) -> Unit)? = null
208
+ var onStructuralTransitionSettled: ((String) -> Unit)? = null
203
209
  var keyboardDismissMode = NativeListKeyboardDismissMode.NONE
204
210
  var keyboardShouldPersistTaps = NativeListKeyboardShouldPersistTaps.NEVER
205
211
  private val density = resources.displayMetrics.density
206
- private val recyclerView = RecyclerView(context)
212
+ private val recyclerView = object : RecyclerView(context) {
213
+ override fun onMeasure(widthSpec: Int, heightSpec: Int) {
214
+ if (isLayoutSuppressed) {
215
+ setMeasuredDimension(measuredWidth, measuredHeight)
216
+ return
217
+ }
218
+ super.onMeasure(widthSpec, heightSpec)
219
+ }
220
+
221
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
222
+ if (isLayoutSuppressed) return
223
+ super.onLayout(changed, left, top, right, bottom)
224
+ }
225
+
226
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean {
227
+ val handled = super.dispatchTouchEvent(event)
228
+ if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) {
229
+ finishPagerNativeGesture(event)
230
+ }
231
+ return handled
232
+ }
233
+ }
207
234
  private var configuredTopPaddingPx = 0
208
235
  private var slotInsetPx = 0
236
+ private var slotRightInsetPx = 0
209
237
  private var configuredBottomPaddingPx = 0
238
+ private data class SidecarLayout(val width: Int, val gap: Int, val maxContentWidth: Int)
239
+ private var sidecarLayout: SidecarLayout? = null
240
+ private var sidecarSpacerHeightPx = 0
241
+ private var sidecarSpacerScheduled = false
242
+ private var consumedStructuralTransitionId: String? = null
243
+ private var structuralAnimator: ValueAnimator? = null
244
+ private var structuralSpacerHeightPx = 0
245
+ private var structuralTailSignedExtentPx = 0
246
+ private var structuralStartSpacerPx = 0
247
+ private var structuralFooterVisualStartTop: Int? = null
248
+ private var structuralFooterVisualEndTop: Int? = null
249
+ private var structuralFooterVisualProgress = 0f
250
+ private var structuralFooterCompensatedHeightPx: Int? = null
251
+ private var structuralFooterObservedNativeHeightPx: Int? = null
252
+ private var acceptedFooterNaturalHeightPx: Int? = null
253
+ private data class PendingPreparingFooterFrame(
254
+ val heights: IntArray,
255
+ val naturalHeight: Int,
256
+ val observedNativeHeight: Int?,
257
+ val ownerOffset: Int,
258
+ val epoch: Int,
259
+ val footer: View?,
260
+ val handoffOnly: Boolean,
261
+ )
262
+ private var pendingPreparingFooterFrame: PendingPreparingFooterFrame? = null
263
+ private var preparingFooterFrameScheduled = false
264
+ private var structuralScrollInterrupted = false
265
+ private var structuralFooterHoldTop: Int? = null
266
+ private var structuralTransitionEpoch = 0
267
+ private class StructuralTail(
268
+ var items: MutableList<NativeListItem>,
269
+ val heights: IntArray,
270
+ spacings: IntArray,
271
+ val prefixCount: Int,
272
+ val finalExtent: Int,
273
+ ) {
274
+ val starts = IntArray(items.size)
275
+ val indexByKey = items.withIndex().associate { it.value.key to it.index }
276
+ val hosts = mutableMapOf<Int, NativeListRowHost>()
277
+ var peakHosts = 0
278
+ val extent: Int
279
+ init {
280
+ var edge = 0
281
+ for (index in items.indices) {
282
+ starts[index] = edge
283
+ edge += heights[index] + spacings[index]
284
+ }
285
+ extent = edge
286
+ }
287
+ }
288
+ private val structuralTailLayer = object : FrameLayout(reactContext), ReactPointerEventsView {
289
+ override val pointerEvents: PointerEvents = PointerEvents.NONE
290
+ override fun dispatchTouchEvent(event: MotionEvent) = false
291
+ }.apply {
292
+ clipChildren = true
293
+ clipToPadding = true
294
+ isClickable = false
295
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
296
+ visibility = GONE
297
+ }
298
+ private var structuralTail: StructuralTail? = null
299
+ private var structuralTailRowsInAdapterPx = 0
300
+ private var structuralTailStartExtentPx = 0
301
+ private var structuralTailStartProgress = 0f
302
+ private var structuralTailStartContentY = 0
303
+ private var structuralTailStartOffset = 0
304
+ private var structuralTailTargetOffset = 0
305
+ private var disclosureFraction = 0f
306
+ private var disclosureStartFraction = 0f
307
+ private var disclosurePresentedContentPx = 0
308
+ private var disclosurePresentedInsetPx = 0
309
+ private var disclosureContentStartPx = 0
310
+ private var disclosureContentStartProgress = 0f
311
+ private var disclosureTransitioning = false
312
+ private var activeDisclosureTransitionId: String? = null
313
+ private var settledDisclosureTransitionId: String? = null
314
+ private var directDisclosureStatus = "interrupted"
315
+ private var directDisclosureTogglePositionPending = false
316
+ private var batchedDisclosureGeometryInvalid = false
317
+ private var structuralTailCommandActive = false
318
+ private var structuralTailFinalizing = false
319
+ private var structuralTailPreparing = false
320
+ private data class PendingStructuralTransition(
321
+ val transition: NativeListConfig.StructuralTransition,
322
+ val epoch: Int,
323
+ val anchorKey: String?,
324
+ val anchorTop: Int?,
325
+ val footerStartTop: Int?,
326
+ val heldHeightPx: Int,
327
+ val collapsing: Boolean,
328
+ val spacerInserted: Boolean = false,
329
+ val footerAnchorAppliedTop: Int? = null,
330
+ val rowAnchorAppliedTop: Int? = null,
331
+ )
332
+ private var pendingStructuralTransition: PendingStructuralTransition? = null
333
+ private var pendingStructuralStartScheduled = false
210
334
  private val refreshLayout = SwipeRefreshLayout(context)
211
335
  private val refreshIndicatorTravelPx = refreshLayout.progressViewEndOffset
212
336
  private val defaultRefreshTriggerDistancePx = (64 * resources.displayMetrics.density).roundToInt()
213
337
  private var refreshIndicatorOffsetPx = 0
214
338
  private val contentContainer = FrameLayout(context)
339
+ private val sidecarHost = object : FrameLayout(context) {
340
+ private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
341
+ private var down: MotionEvent? = null
342
+ private var routing = false
343
+
344
+ private fun route(event: MotionEvent) {
345
+ val copy = MotionEvent.obtain(event)
346
+ copy.offsetLocation(x - refreshLayout.x, y - refreshLayout.y)
347
+ refreshLayout.dispatchTouchEvent(copy)
348
+ copy.recycle()
349
+ }
350
+
351
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean {
352
+ when (event.actionMasked) {
353
+ MotionEvent.ACTION_DOWN -> {
354
+ down?.recycle()
355
+ down = MotionEvent.obtain(event)
356
+ routing = false
357
+ }
358
+ MotionEvent.ACTION_MOVE -> {
359
+ if (routing) {
360
+ route(event)
361
+ return true
362
+ }
363
+ val start = down
364
+ if (start != null && abs(event.y - start.y) > touchSlop &&
365
+ abs(event.y - start.y) > abs(event.x - start.x)) {
366
+ val cancel = MotionEvent.obtain(event)
367
+ cancel.action = MotionEvent.ACTION_CANCEL
368
+ super.dispatchTouchEvent(cancel)
369
+ cancel.recycle()
370
+ route(start)
371
+ route(event)
372
+ routing = true
373
+ return true
374
+ }
375
+ }
376
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
377
+ if (routing) route(event)
378
+ down?.recycle()
379
+ down = null
380
+ if (routing) {
381
+ routing = false
382
+ return true
383
+ }
384
+ }
385
+ else -> if (routing) {
386
+ route(event)
387
+ return true
388
+ }
389
+ }
390
+ return super.dispatchTouchEvent(event)
391
+ }
392
+ }
215
393
  private val adapter = NativeListAdapter(reactContext, fonts)
216
394
  private val containerSlots = mutableListOf<View>()
217
- private val slotHeights = IntArray(3)
395
+ private val slotHeights = IntArray(6)
396
+ private val expandedContentHost = object : FrameLayout(context), ReactPointerEventsView {
397
+ var naturalHeightPx = 0
398
+ override val pointerEvents: PointerEvents
399
+ get() = if (config?.disclosure?.expanded == true &&
400
+ !disclosureTransitioning && disclosureFraction >= 1f) PointerEvents.AUTO
401
+ else PointerEvents.NONE
402
+
403
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
404
+ setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
405
+ MeasureSpec.getSize(heightMeasureSpec))
406
+ }
407
+
408
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
409
+ getChildAt(0)?.layout(0, 0, right - left, naturalHeightPx)
410
+ }
411
+ }.apply {
412
+ clipChildren = true
413
+ clipToPadding = true
414
+ isClickable = false
415
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
416
+ }
417
+ private val footerPresentationHost = object : FrameLayout(context) {
418
+ var naturalHeightPx = 0
419
+ var hiddenTopPx = 0
420
+
421
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
422
+ setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
423
+ MeasureSpec.getSize(heightMeasureSpec))
424
+ }
425
+
426
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
427
+ val child = getChildAt(0) ?: return
428
+ child.layout(0, -hiddenTopPx, right - left, naturalHeightPx - hiddenTopPx)
429
+ }
430
+ }.apply {
431
+ clipChildren = true
432
+ clipToPadding = true
433
+ }
434
+ private var initialHeaderInsertionHandled = false
218
435
  private var containerSlotRelayoutPending = false
219
436
  private var containerSlotRelayoutScheduled = false
220
437
  private val headerSlotAdapter = NativeListContainerSlotAdapter()
221
438
  private val emptySlotAdapter = NativeListContainerSlotAdapter()
439
+ private val structuralSpacerView = View(context)
440
+ private val structuralSpacerAdapter = NativeListContainerSlotAdapter()
441
+ private val expandedContentAdapter = NativeListContainerSlotAdapter()
442
+ private val structureToggleAdapter = NativeListContainerSlotAdapter()
443
+ private val disclosureInsetView = View(context)
444
+ private val disclosureInsetAdapter = NativeListContainerSlotAdapter()
222
445
  private val footerSlotAdapter = NativeListContainerSlotAdapter()
223
- private val scrollContentAdapter = ConcatAdapter(headerSlotAdapter, adapter, emptySlotAdapter, footerSlotAdapter)
224
-
225
- private val homeOffsetDiagnosticEnabled =
226
- context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0
227
- private var homeOffsetDiagnosticSequence = 0L
228
-
229
- private fun homeOffsetDiagnostic(phase: String, state: RecyclerView.State? = null) {
230
- if (!homeOffsetDiagnosticEnabled) return
231
- try {
232
- val first = layoutManager.findFirstVisibleItemPosition()
233
- val firstView = layoutManager.findViewByPosition(first)
234
- val holder = firstView?.let { recyclerView.getChildViewHolder(it) }
235
- val lastView = layoutManager.findViewByPosition(layoutManager.findLastVisibleItemPosition())
236
- val lastHolder = lastView?.let { recyclerView.getChildViewHolder(it) }
237
- fun adapterOrdinal(value: RecyclerView.Adapter<*>?): Int = when (value) {
238
- headerSlotAdapter -> 0
239
- adapter -> 1
240
- emptySlotAdapter -> 2
241
- footerSlotAdapter -> 3
242
- else -> -1
243
- }
244
- val focused = recyclerView.findFocus()
245
- val focusChild = focused?.let { recyclerView.findContainingItemView(it) }
246
- val focusHolder = focusChild?.let { recyclerView.getChildViewHolder(it) }
247
- OneKeyLog.debug("NativeList", "[HOME-OFFSET-DIAG] listPhase=$phase " +
248
- "seq=${++homeOffsetDiagnosticSequence} wallMs=${System.currentTimeMillis()} monoMs=${SystemClock.uptimeMillis()} " +
249
- "list=${System.identityHashCode(this)} view=${System.identityHashCode(recyclerView)} tag=$id " +
250
- "generation=${config?.generation} configuredCount=${config?.items?.size} " +
251
- "counts=${headerSlotAdapter.itemCount},${adapter.itemCount},${emptySlotAdapter.itemCount},${footerSlotAdapter.itemCount} " +
252
- "total=${scrollContentAdapter.itemCount} pendingCommand=${pendingScrollRequest?.javaClass?.simpleName ?: "none"} " +
253
- "stateCount=${state?.itemCount} preLayout=${state?.isPreLayout} structureChanged=${state?.didStructureChange()} predictive=${state?.willRunPredictiveAnimations()} " +
254
- "first=$first last=${layoutManager.findLastVisibleItemPosition()} " +
255
- "adapterOrdinal=${adapterOrdinal(holder?.bindingAdapter)} layout=${holder?.layoutPosition} absolute=${holder?.absoluteAdapterPosition} binding=${holder?.bindingAdapterPosition} lastAdapterOrdinal=${adapterOrdinal(lastHolder?.bindingAdapter)} lastLayout=${lastHolder?.layoutPosition} lastAbsolute=${lastHolder?.absoluteAdapterPosition} lastBinding=${lastHolder?.bindingAdapterPosition} " +
256
- "anchorTop=${firstView?.let(layoutManager::getDecoratedTop)} paddingTop=${recyclerView.paddingTop} " +
257
- "childHeight=${firstView?.height} height=${recyclerView.height} range=${recyclerView.computeVerticalScrollRange()} extent=${recyclerView.computeVerticalScrollExtent()} " +
258
- "canUp=${recyclerView.canScrollVertically(-1)} canDown=${recyclerView.canScrollVertically(1)} " +
259
- "focusClass=${focused?.javaClass?.simpleName ?: "none"} focusId=${focused?.id} focusAdapterOrdinal=${adapterOrdinal(focusHolder?.bindingAdapter)} focusLayout=${focusHolder?.layoutPosition} focusPosition=${focusHolder?.absoluteAdapterPosition} focusBinding=${focusHolder?.bindingAdapterPosition}")
260
- } catch (_: Exception) {
261
- // Diagnostic reads must not affect layout or command delivery.
262
- }
263
- }
446
+ private val sidecarSpacerView = View(context)
447
+ private val sidecarSpacerAdapter = NativeListContainerSlotAdapter()
448
+ private val scrollContentAdapter = ConcatAdapter(
449
+ headerSlotAdapter, adapter, emptySlotAdapter, structuralSpacerAdapter,
450
+ expandedContentAdapter, structureToggleAdapter, disclosureInsetAdapter,
451
+ footerSlotAdapter, sidecarSpacerAdapter,
452
+ )
264
453
 
265
454
  fun mountContainerSlot(view: View, index: Int) {
266
455
  containerSlots.add(index.coerceIn(0, containerSlots.size), view)
@@ -277,23 +466,283 @@ class NativeListView(
277
466
  scheduleContainerSlotRelayout()
278
467
  }
279
468
 
280
- fun setContainerSlotHeightsJson(json: String) {
469
+ fun setContainerSlotHeightsJson(json: String, upcomingSnapshotJson: String? = null) {
281
470
  val values = runCatching { JSONArray(json) }.getOrNull() ?: return
282
- if (values.length() != 3) return
283
- for (index in 0..2) {
471
+ if (values.length() != 4 && values.length() != 6) return
472
+ val nextHeights = IntArray(6)
473
+ for (index in 0 until values.length()) {
284
474
  val value = values.optDouble(index)
285
475
  if (!value.isFinite() || value < 0) return
476
+ nextHeights[index] = (value * density).roundToInt()
477
+ }
478
+ val disclosureTail = structuralTail != null && config?.disclosure != null &&
479
+ !structuralTailFinalizing
480
+ if (disclosureTail && upcomingSnapshotJson != null &&
481
+ (nextHeights[2] != slotHeights[2] || nextHeights[5] != slotHeights[5] ||
482
+ nextHeights[4] < disclosurePresentedContentPx)) {
483
+ // Nitro delivers both setters in this UI turn. Let the complete new snapshot
484
+ // replace the old command before deciding whether its geometry is supported.
485
+ batchedDisclosureGeometryInvalid = true
486
+ for (index in 0..5) slotHeights[index] = nextHeights[index]
487
+ acceptedFooterNaturalHeightPx = nextHeights[2]
488
+ return
489
+ }
490
+ val unsupportedDisclosureGeometry = disclosureTail &&
491
+ (nextHeights[2] != slotHeights[2] || nextHeights[5] != slotHeights[5] ||
492
+ nextHeights[4] < disclosurePresentedContentPx)
493
+ if (unsupportedDisclosureGeometry) {
494
+ // A changing fixed footer/toggle or a shrinking mounted C cannot be represented
495
+ // by the current visual segment. Commit the accepted endpoint before ACK.
496
+ structuralFooterCompensatedHeightPx = null
497
+ acceptedFooterNaturalHeightPx = nextHeights[2]
498
+ for (index in 0..5) slotHeights[index] = nextHeights[index]
499
+ updateContainerSlots()
500
+ finishStructuralTail(interrupted = true)
501
+ return
502
+ }
503
+ if (disclosureTail && nextHeights[4] != slotHeights[4]) {
504
+ disclosureContentStartPx = disclosurePresentedContentPx
505
+ disclosureContentStartProgress =
506
+ (structuralAnimator?.animatedValue as? Float) ?: 0f
507
+ }
508
+ if (structuralTail != null && structuralTailRowsInAdapterPx > 0 &&
509
+ listOf(0, 1, 3).all { slotHeights[it] == nextHeights[it] } &&
510
+ (pendingPreparingFooterFrame != null ||
511
+ (!structuralTailFinalizing && slotHeights[2] != nextHeights[2]))) {
512
+ enqueuePreparingFooterFrame(nextHeights, nextHeights[2])
513
+ return
514
+ }
515
+ pendingPreparingFooterFrame?.takeIf {
516
+ structuralTailRowsInAdapterPx > 0 && it.footer === containerSlots.getOrNull(2)
517
+ }?.let { pending ->
518
+ val preservesNewerHeight = nextHeights[2] == slotHeights[2] &&
519
+ pending.naturalHeight != nextHeights[2]
520
+ pendingPreparingFooterFrame = pending.copy(
521
+ heights = nextHeights.copyOf(),
522
+ naturalHeight = if (preservesNewerHeight) pending.naturalHeight else nextHeights[2],
523
+ observedNativeHeight = pending.observedNativeHeight.takeIf {
524
+ preservesNewerHeight || pending.naturalHeight == nextHeights[2]
525
+ },
526
+ )
286
527
  }
528
+ if (structuralTailPreparing && (0..3).any { index ->
529
+ slotHeights[index] != nextHeights[index]
530
+ }) invalidateTailForContainerGeometry()
531
+ if (structuralTail != null && listOf(0, 1, 3).any { index ->
532
+ slotHeights[index] != nextHeights[index]
533
+ }) finishStructuralTail(interrupted = true)
534
+ val footerHeightPx = nextHeights[2]
535
+ if (footerHeightPx != slotHeights[2]) {
536
+ containerSlots.getOrNull(2)?.measuredHeight?.takeIf { it > 0 && it != footerHeightPx }
537
+ ?.let { structuralFooterObservedNativeHeightPx = it }
538
+ reconcileStructuralFooterHeight(footerHeightPx)
539
+ acceptedFooterNaturalHeightPx = footerHeightPx
540
+ } else if (acceptedFooterNaturalHeightPx == null) {
541
+ acceptedFooterNaturalHeightPx = footerHeightPx
542
+ }
543
+ val hiddenDisclosureContentOnlyChange = config?.disclosure?.expanded == false &&
544
+ !disclosureTransitioning && structuralTail == null &&
545
+ !structuralTailPreparing && !structuralTailFinalizing &&
546
+ disclosurePresentedContentPx == 0 && disclosurePresentedInsetPx == 0 &&
547
+ expandedContentAdapter.itemCount == 0 &&
548
+ slotHeights[4] != nextHeights[4] &&
549
+ (0..5).all { index -> index == 4 || slotHeights[index] == nextHeights[index] }
287
550
  var changed = false
288
- for (index in 0..2) {
289
- val height = (values.getDouble(index) * density).roundToInt()
551
+ for (index in 0..5) {
552
+ val height = nextHeights[index]
290
553
  if (slotHeights[index] != height) changed = true
291
554
  slotHeights[index] = height
292
555
  }
556
+ if (hiddenDisclosureContentOnlyChange) {
557
+ expandedContentHost.naturalHeightPx = slotHeights[4]
558
+ layoutExpandedContentHostNow()
559
+ return
560
+ }
293
561
  updateContainerSlots()
562
+ if (structuralTail != null) updateStructuralTailTarget()
563
+ updateSidecarGeometry()
564
+ scheduleSidecarSpacer()
294
565
  if (changed) scheduleContainerSlotRelayout()
295
566
  }
296
567
 
568
+ private fun enqueuePreparingFooterFrame(
569
+ heights: IntArray,
570
+ naturalHeight: Int,
571
+ observedNativeHeight: Int? = null,
572
+ ) {
573
+ val footer = containerSlots.getOrNull(2)
574
+ val existing = pendingPreparingFooterFrame?.takeIf { it.footer === footer }
575
+ val preservesNewerHeight = existing != null && observedNativeHeight == null &&
576
+ naturalHeight == slotHeights[2] && existing.naturalHeight != naturalHeight
577
+ val acceptedHeight = if (preservesNewerHeight) existing.naturalHeight else naturalHeight
578
+ val observedHeight = observedNativeHeight ?:
579
+ existing?.observedNativeHeight?.takeIf { preservesNewerHeight || it == acceptedHeight }
580
+ pendingPreparingFooterFrame = PendingPreparingFooterFrame(
581
+ heights.copyOf(), acceptedHeight, observedHeight,
582
+ existing?.ownerOffset ?: structuralTailStartOffset,
583
+ structuralTransitionEpoch, footer, existing?.handoffOnly == true,
584
+ )
585
+ if (!commitPreparingFooterFrame() && pendingPreparingFooterFrame?.handoffOnly != true) {
586
+ schedulePreparingFooterFrame()
587
+ }
588
+ }
589
+
590
+ private fun schedulePreparingFooterFrame() {
591
+ if (preparingFooterFrameScheduled) return
592
+ preparingFooterFrameScheduled = true
593
+ recyclerView.post {
594
+ preparingFooterFrameScheduled = false
595
+ if (!commitPreparingFooterFrame()) recyclerView.postInvalidateOnAnimation()
596
+ }
597
+ recyclerView.postInvalidateOnAnimation()
598
+ }
599
+
600
+ private fun reconcileStructuralFooterHeight(nextHeightPx: Int) {
601
+ if (structuralTail != null) {
602
+ if (!structuralTailFinalizing) {
603
+ val delta = (structuralFooterCompensatedHeightPx ?:
604
+ acceptedFooterNaturalHeightPx ?: slotHeights[2]) - nextHeightPx
605
+ if (delta != 0) {
606
+ if (structuralTailPreparing) {
607
+ invalidateTailForContainerGeometry()
608
+ return
609
+ }
610
+ structuralFooterCompensatedHeightPx = nextHeightPx
611
+ val compensated = structuralTailSignedExtentPx + delta
612
+ structuralTailStartProgress = (structuralAnimator?.animatedValue as? Float) ?: 0f
613
+ structuralTailStartExtentPx = compensated
614
+ if (structuralTailRowsInAdapterPx == 0) structuralTailStartOffset = tailScrollExtentPx()
615
+ setStructuralTailExtent(compensated)
616
+ if (structuralTailRowsInAdapterPx == 0) updateStructuralTailWindow()
617
+ }
618
+ }
619
+ return
620
+ }
621
+ val previousHeightPx = structuralFooterCompensatedHeightPx ?:
622
+ acceptedFooterNaturalHeightPx ?: slotHeights[2]
623
+ val footerDelta = previousHeightPx - nextHeightPx
624
+ if (footerDelta == 0) return
625
+ if (pendingStructuralTransition != null || structuralAnimator != null || structuralFooterHoldTop != null) {
626
+ structuralFooterCompensatedHeightPx = nextHeightPx
627
+ }
628
+ if (pendingStructuralTransition != null) {
629
+ pendingStructuralTransition = pendingStructuralTransition?.let {
630
+ val updated = it.copy(
631
+ footerStartTop = it.footerStartTop?.plus(footerDelta),
632
+ heldHeightPx = (it.heldHeightPx + footerDelta).coerceAtLeast(0),
633
+ )
634
+ if (updated.spacerInserted) setStructuralSpacerHeight(updated.heldHeightPx)
635
+ updated
636
+ }
637
+ structuralFooterHoldTop = structuralFooterHoldTop?.plus(footerDelta)
638
+ updateStructuralFooterHoldPosition()
639
+ } else if (structuralFooterHoldTop != null && structuralAnimator == null) {
640
+ setStructuralSpacerHeight(structuralSpacerHeightPx + footerDelta)
641
+ structuralFooterHoldTop = structuralFooterHoldTop?.plus(footerDelta)
642
+ updateStructuralFooterHoldPosition()
643
+ } else if (structuralAnimator != null) {
644
+ structuralStartSpacerPx = (structuralStartSpacerPx + footerDelta).coerceAtLeast(0)
645
+ structuralFooterVisualStartTop = structuralFooterVisualStartTop?.plus(footerDelta)
646
+ val fraction = (structuralAnimator?.animatedValue as? Float) ?: 0f
647
+ setStructuralSpacerHeight((structuralStartSpacerPx * (1f - fraction)).roundToInt())
648
+ updateStructuralFooterVisualPosition()
649
+ }
650
+ }
651
+
652
+ fun setSidecarLayoutJson(json: String) {
653
+ val next = if (json.isEmpty()) null else {
654
+ val value = runCatching { JSONObject(json) }.getOrNull() ?: return
655
+ val width = value.optDouble("width")
656
+ val gap = value.optDouble("gap")
657
+ val maxWidth = value.optDouble("maxContentWidth")
658
+ if (!width.isFinite() || width <= 0 || !gap.isFinite() || gap < 0 ||
659
+ !maxWidth.isFinite() || maxWidth <= width + gap) return
660
+ SidecarLayout((width * density).roundToInt(), (gap * density).roundToInt(),
661
+ (maxWidth * density).roundToInt())
662
+ }
663
+ if (next == sidecarLayout) return
664
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
665
+ sidecarLayout = next
666
+ config?.let(::updateLayout)
667
+ updateSidecarGeometry()
668
+ scheduleSidecarSpacer()
669
+ }
670
+
671
+ private fun sidecarBaseInsetPx(): Int {
672
+ val layout = sidecarLayout ?: return 0
673
+ val width = recyclerView.width
674
+ return max(0, (width - minOf(width, layout.maxContentWidth)) / 2)
675
+ }
676
+
677
+ private fun updateSidecarGeometry() {
678
+ val layout = sidecarLayout
679
+ val root = containerSlots.getOrNull(3)
680
+ if (root !== sidecarHost.getChildAt(0)) {
681
+ sidecarHost.removeAllViews()
682
+ (root?.parent as? ViewGroup)?.removeView(root)
683
+ if (root != null) sidecarHost.addView(root)
684
+ }
685
+ val params = sidecarHost.layoutParams as? FrameLayout.LayoutParams
686
+ ?: FrameLayout.LayoutParams(0, 0, Gravity.TOP or Gravity.RIGHT)
687
+ val nextWidth = layout?.width ?: 0
688
+ val nextHeight = if (layout != null) slotHeights[3] else 0
689
+ val isRtl = layoutDirection == LAYOUT_DIRECTION_RTL
690
+ val nextGravity = Gravity.TOP or (if (isRtl) Gravity.LEFT else Gravity.RIGHT)
691
+ val nextSideMargin = sidecarBaseInsetPx()
692
+ if (params.width != nextWidth || params.height != nextHeight ||
693
+ params.gravity != nextGravity ||
694
+ params.leftMargin != (if (isRtl) nextSideMargin else 0) ||
695
+ params.rightMargin != (if (isRtl) 0 else nextSideMargin)) {
696
+ params.width = nextWidth
697
+ params.height = nextHeight
698
+ params.gravity = nextGravity
699
+ params.leftMargin = if (isRtl) nextSideMargin else 0
700
+ params.rightMargin = if (isRtl) 0 else nextSideMargin
701
+ sidecarHost.layoutParams = params
702
+ }
703
+ sidecarHost.visibility = if (layout != null && root != null && slotHeights[3] > 0) VISIBLE else GONE
704
+ updateSidecarPosition()
705
+ }
706
+
707
+ private fun updateSidecarPosition(resync: Boolean = false) {
708
+ if (sidecarLayout == null) return
709
+ if (resync) (if (structuralTail == null) measuredScrollDistancePx()
710
+ else structuralTailMeasuredScrollDistancePx())?.let { logicalScrollDistancePx = it }
711
+ sidecarHost.translationY = (recyclerView.paddingTop - logicalScrollDistancePx).toFloat()
712
+ }
713
+
714
+ private fun sidecarLeftExtentPx(): Int =
715
+ (nativeListScrollPrefixPx(
716
+ scrollContentAdapter.itemCount - sidecarSpacerAdapter.itemCount,
717
+ layoutManager.spanCount,
718
+ layoutManager.spanSizeLookup::getSpanSize,
719
+ if (structuralTail == null) ::estimatedScrollExtentPx else ::structuralTailRowOrSlotExtentPx,
720
+ ) + recyclerView.paddingTop + recyclerView.paddingBottom)
721
+ .coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
722
+
723
+ private fun scheduleSidecarSpacer() {
724
+ if (sidecarLayout == null && sidecarSpacerHeightPx == 0) return
725
+ if (disposed || sidecarSpacerScheduled) return
726
+ sidecarSpacerScheduled = true
727
+ recyclerView.post {
728
+ sidecarSpacerScheduled = false
729
+ updateSidecarSpacerNow()
730
+ }
731
+ }
732
+
733
+ private fun updateSidecarSpacerNow() {
734
+ if (disposed || recyclerView.width <= 0 || recyclerView.height <= 0) return
735
+ val desired = if (sidecarLayout != null) {
736
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
737
+ } else 0
738
+ val leftExtent = sidecarLeftExtentPx()
739
+ val next = (desired - leftExtent).coerceAtLeast(0)
740
+ if (abs(next - sidecarSpacerHeightPx) <= 1) return
741
+ sidecarSpacerHeightPx = next
742
+ sidecarSpacerAdapter.update(sidecarSpacerView, next, next > 0)
743
+ recyclerView.requestLayout()
744
+ }
745
+
297
746
  private fun scheduleContainerSlotRelayout() {
298
747
  if (disposed) return
299
748
  containerSlotRelayoutPending = true
@@ -313,15 +762,185 @@ class NativeListView(
313
762
  }
314
763
 
315
764
  private fun updateContainerSlots() {
316
- homeOffsetDiagnostic("slots-before")
765
+ val headerWasAbsent = headerSlotAdapter.itemCount == 0
766
+ val firstVisible = layoutManager.findFirstVisibleItemPosition()
767
+ val firstView = layoutManager.findViewByPosition(firstVisible)
768
+ val restoreInitialHeaderTop = !initialHeaderInsertionHandled && headerWasAbsent &&
769
+ layoutManager.orientation == RecyclerView.VERTICAL &&
770
+ adapter.itemCount > 0 && readingIntentEpoch == 0L && pendingScrollRequest == null &&
771
+ acceptedScrollRequest == null && !executingScrollCommand &&
772
+ recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE && firstVisible == 0 &&
773
+ firstView != null && abs(layoutManager.getDecoratedTop(firstView) - recyclerView.paddingTop) <= 1 &&
774
+ !recyclerView.canScrollVertically(-1)
317
775
  headerSlotAdapter.update(containerSlots.getOrNull(0), slotHeights[0], true)
318
776
  emptySlotAdapter.update(containerSlots.getOrNull(1), slotHeights[1], config?.items?.isEmpty() != false)
319
- footerSlotAdapter.update(containerSlots.getOrNull(2), slotHeights[2], true)
320
- homeOffsetDiagnostic("slots-after")
777
+ syncDisclosurePresentation()
778
+ syncFooterPresentation()
779
+ updateSidecarGeometry()
780
+ if (headerWasAbsent && headerSlotAdapter.itemCount > 0) {
781
+ initialHeaderInsertionHandled = true
782
+ if (restoreInitialHeaderTop) {
783
+ // RecyclerView otherwise keeps the first body row at the top when this slot arrives late.
784
+ layoutManager.scrollToPositionWithOffset(0, 0)
785
+ }
786
+ }
321
787
  layoutManager.spanSizeLookup.invalidateSpanIndexCache()
322
788
  recyclerView.requestLayout()
323
789
  }
324
790
 
791
+ private fun disclosureInsetExtentPx(): Int =
792
+ ((config?.disclosure?.expandedTrailingInset ?: 0.0) * density)
793
+ .coerceIn(0.0, Int.MAX_VALUE.toDouble()).roundToInt()
794
+
795
+ private fun settleDisclosureCommand(status: String) {
796
+ val id = activeDisclosureTransitionId ?: return
797
+ if (disposed || id == settledDisclosureTransitionId ||
798
+ consumedStructuralTransitionId != id || structuralTail != null) return
799
+ settledDisclosureTransitionId = id
800
+ activeDisclosureTransitionId = null
801
+ directDisclosureTogglePositionPending = false
802
+ onStructuralTransitionSettled?.invoke(JSONObject().apply {
803
+ put("transitionId", id)
804
+ put("status", status)
805
+ put("settledExpanded", config?.disclosure?.expanded == true)
806
+ }.toString())
807
+ }
808
+
809
+ private fun settleCommittedDirectDisclosure(
810
+ next: NativeListConfig,
811
+ id: String?,
812
+ positionToggle: Boolean,
813
+ ) {
814
+ if (id == null || disposed || config !== next ||
815
+ activeDisclosureTransitionId != id || consumedStructuralTransitionId != id ||
816
+ structuralTail != null || next.disclosure == null) return
817
+ relayoutRecyclerViewImmediately()
818
+ if (positionToggle && directDisclosureTogglePositionPending)
819
+ positionSettledDisclosureToggle()
820
+ settleDisclosureCommand(directDisclosureStatus)
821
+ }
822
+
823
+ private fun presentAcceptedDisclosureEndpoint(next: NativeListConfig) {
824
+ val disclosure = next.disclosure ?: return
825
+ disclosureFraction = if (disclosure.expanded) 1f else 0f
826
+ disclosurePresentedContentPx = if (disclosure.expanded) slotHeights[4] else 0
827
+ syncDisclosurePresentation()
828
+ }
829
+
830
+ private fun syncDisclosurePresentation() {
831
+ val disclosure = config?.disclosure
832
+ if (disclosure == null) {
833
+ disclosurePresentedContentPx = 0
834
+ disclosurePresentedInsetPx = 0
835
+ expandedContentAdapter.update(null, 0, false)
836
+ structureToggleAdapter.update(null, 0, false)
837
+ disclosureInsetAdapter.update(null, 0, false)
838
+ return
839
+ }
840
+ val content = containerSlots.getOrNull(4)
841
+ if (expandedContentHost.getChildAt(0) !== content) {
842
+ expandedContentHost.removeAllViews()
843
+ if (content != null) {
844
+ (content.parent as? ViewGroup)?.removeView(content)
845
+ expandedContentHost.addView(content, FrameLayout.LayoutParams(
846
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
847
+ }
848
+ }
849
+ expandedContentHost.naturalHeightPx = slotHeights[4]
850
+ val fraction = disclosureFraction.coerceIn(0f, 1f)
851
+ val contentHeight = if (disclosureTransitioning) disclosurePresentedContentPx else
852
+ if (disclosure.expanded) slotHeights[4] else 0
853
+ disclosurePresentedContentPx = contentHeight
854
+ disclosurePresentedInsetPx = (disclosureInsetExtentPx() * fraction).roundToInt()
855
+ val interactive = disclosure.expanded && !disclosureTransitioning && fraction >= 1f
856
+ expandedContentHost.importantForAccessibility = if (interactive)
857
+ View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
858
+ else View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
859
+ expandedContentAdapter.update(if (content == null) null else expandedContentHost,
860
+ contentHeight, true)
861
+ structureToggleAdapter.update(containerSlots.getOrNull(5), slotHeights[5], true)
862
+ disclosureInsetAdapter.update(disclosureInsetView,
863
+ disclosurePresentedInsetPx, true)
864
+ if (content != null) layoutExpandedContentHostNow()
865
+ }
866
+
867
+ private fun layoutExpandedContentHostNow() {
868
+ val wrapper = expandedContentHost
869
+ val child = wrapper.getChildAt(0) ?: return
870
+ val width = wrapper.width.takeIf { it > 0 } ?: wrapper.measuredWidth.takeIf { it > 0 } ?: return
871
+ val height = disclosurePresentedContentPx
872
+ if (!wrapper.isLayoutRequested && wrapper.measuredWidth == width &&
873
+ wrapper.measuredHeight == height && wrapper.height == height &&
874
+ child.left == 0 && child.top == 0 && child.right == width &&
875
+ child.bottom == wrapper.naturalHeightPx) return
876
+ wrapper.forceLayout()
877
+ wrapper.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
878
+ View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY))
879
+ wrapper.layout(wrapper.left, wrapper.top, wrapper.left + width, wrapper.top + height)
880
+ }
881
+
882
+ private fun syncFooterPresentation() {
883
+ val footer = containerSlots.getOrNull(2)
884
+ if (footerPresentationHost.getChildAt(0) !== footer) {
885
+ invalidateTailForContainerGeometry()
886
+ structuralFooterCompensatedHeightPx = null
887
+ structuralFooterObservedNativeHeightPx = null
888
+ acceptedFooterNaturalHeightPx = null
889
+ footerPresentationHost.removeAllViews()
890
+ if (footer != null) {
891
+ (footer.parent as? ViewGroup)?.removeView(footer)
892
+ footerPresentationHost.addView(footer, FrameLayout.LayoutParams(
893
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
894
+ }
895
+ }
896
+ val naturalHeight = footerNaturalHeightPx()
897
+ val hiddenTop = footerHiddenTopPx()
898
+ if (footerPresentationHost.naturalHeightPx != naturalHeight ||
899
+ footerPresentationHost.hiddenTopPx != hiddenTop) {
900
+ footerPresentationHost.naturalHeightPx = naturalHeight
901
+ footerPresentationHost.hiddenTopPx = hiddenTop
902
+ footerPresentationHost.requestLayout()
903
+ }
904
+ footerSlotAdapter.update(if (footer == null) null else footerPresentationHost,
905
+ naturalHeight - hiddenTop, true)
906
+ if (footer != null) layoutFooterPresentationHostNow()
907
+ }
908
+
909
+ private fun layoutFooterPresentationHostNow() {
910
+ val wrapper = footerPresentationHost
911
+ val child = wrapper.getChildAt(0) ?: return
912
+ val width = wrapper.width.takeIf { it > 0 } ?: wrapper.measuredWidth.takeIf { it > 0 } ?: return
913
+ val height = footerPresentedHeightPx()
914
+ val childTop = -wrapper.hiddenTopPx
915
+ val childBottom = wrapper.naturalHeightPx - wrapper.hiddenTopPx
916
+ if (!wrapper.isLayoutRequested && wrapper.measuredWidth == width &&
917
+ wrapper.measuredHeight == height && wrapper.height == height &&
918
+ child.left == 0 && child.top == childTop && child.right == width &&
919
+ child.bottom == childBottom) return
920
+ wrapper.forceLayout()
921
+ wrapper.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
922
+ View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY))
923
+ wrapper.layout(wrapper.left, wrapper.top, wrapper.left + width, wrapper.top + height)
924
+ }
925
+
926
+ private fun invalidateTailForContainerGeometry() {
927
+ pendingPreparingFooterFrame = null
928
+ if (structuralTail == null) return
929
+ if (!structuralTailFinalizing) finishStructuralTail(interrupted = true)
930
+ structuralFooterCompensatedHeightPx = null
931
+ structuralTailSignedExtentPx = structuralTailRowsInAdapterPx + structuralSpacerHeightPx
932
+ }
933
+
934
+ private fun footerNaturalHeightPx(): Int = if (structuralTail == null)
935
+ acceptedFooterNaturalHeightPx ?: slotHeights[2] else
936
+ structuralFooterCompensatedHeightPx ?: acceptedFooterNaturalHeightPx ?: slotHeights[2]
937
+
938
+ private fun footerHiddenTopPx(): Int = if (structuralTail == null) 0 else
939
+ (structuralTailRowsInAdapterPx - structuralTailSignedExtentPx)
940
+ .coerceIn(0, footerNaturalHeightPx())
941
+
942
+ private fun footerPresentedHeightPx(): Int = footerNaturalHeightPx() - footerHiddenTopPx()
943
+
325
944
  private fun scrollPositionForRow(index: Int): Int = index + headerSlotAdapter.itemCount
326
945
 
327
946
  private fun recordLaidOutRowExtent(child: View, extentPx: Int) {
@@ -345,7 +964,23 @@ class NativeListView(
345
964
  if (position < headerCount) return slotHeights[0]
346
965
  val row = position - headerCount
347
966
  if (row >= adapter.itemCount) {
348
- return if (row - adapter.itemCount < emptySlotAdapter.itemCount) slotHeights[1] else slotHeights[2]
967
+ val slot = row - adapter.itemCount
968
+ return when {
969
+ slot < emptySlotAdapter.itemCount -> slotHeights[1]
970
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount -> structuralSpacerHeightPx
971
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
972
+ expandedContentAdapter.itemCount -> disclosurePresentedContentPx
973
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
974
+ expandedContentAdapter.itemCount + structureToggleAdapter.itemCount -> slotHeights[5]
975
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
976
+ expandedContentAdapter.itemCount + structureToggleAdapter.itemCount +
977
+ disclosureInsetAdapter.itemCount ->
978
+ disclosurePresentedInsetPx
979
+ slot < emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
980
+ expandedContentAdapter.itemCount + structureToggleAdapter.itemCount +
981
+ disclosureInsetAdapter.itemCount + footerSlotAdapter.itemCount -> footerPresentedHeightPx()
982
+ else -> sidecarSpacerHeightPx
983
+ }
349
984
  }
350
985
  val item = adapter.itemAt(row)
351
986
  item?.key?.let(measuredRowExtentsPx::get)?.let { return it }
@@ -354,6 +989,847 @@ class NativeListView(
354
989
  return if (measuredRowExtentsPx.isEmpty()) 0 else (measuredRowExtentSumPx / measuredRowExtentsPx.size).toInt()
355
990
  }
356
991
 
992
+ private fun estimatedItemExtentPx(item: NativeListItem): Int {
993
+ measuredRowExtentsPx[item.key]?.let { return it }
994
+ val explicit = item.styledHeight ?: item.json.optDouble("height").takeIf { it.isFinite() }
995
+ if (explicit != null) return (explicit * density).roundToInt()
996
+ return if (measuredRowExtentsPx.isEmpty()) dp(56)
997
+ else (measuredRowExtentSumPx / measuredRowExtentsPx.size).toInt()
998
+ }
999
+
1000
+ private fun setStructuralSpacerHeight(heightPx: Int) {
1001
+ val next = heightPx.coerceAtLeast(0)
1002
+ if (next == structuralSpacerHeightPx) return
1003
+ structuralSpacerHeightPx = next
1004
+ structuralSpacerAdapter.update(structuralSpacerView, next, true)
1005
+ layoutManager.spanSizeLookup.invalidateSpanIndexCache()
1006
+ }
1007
+
1008
+ private fun setStructuralTailExtent(extentPx: Int) {
1009
+ structuralTailSignedExtentPx = extentPx
1010
+ setStructuralSpacerHeight((extentPx - structuralTailRowsInAdapterPx).coerceAtLeast(0))
1011
+ syncFooterPresentation()
1012
+ }
1013
+
1014
+ private fun prefixTailCount(old: NativeListConfig, next: NativeListConfig): Int? {
1015
+ if (old.orientation != "vertical" || next.orientation != "vertical" ||
1016
+ old.layout != next.layout || next.layout !in setOf("linear", "table") ||
1017
+ old.itemSpacing != next.itemSpacing ||
1018
+ old.contentPadding != next.contentPadding ||
1019
+ old.contentPaddingTop != next.contentPaddingTop ||
1020
+ old.contentPaddingBottom != next.contentPaddingBottom ||
1021
+ old.contentPaddingHorizontal != next.contentPaddingHorizontal ||
1022
+ old.theme?.toString() != next.theme?.toString() ||
1023
+ old.listStyle?.toString() != next.listStyle?.toString() ||
1024
+ old.items.size == next.items.size ||
1025
+ old.reorderable || next.reorderable ||
1026
+ structuralTailFinalizing || structuralTailRowsInAdapterPx > 0 ||
1027
+ old.items.any { it.usesSelectorSourceScale } !=
1028
+ next.items.any { it.usesSelectorSourceScale } ||
1029
+ (structuralAnimator != null && structuralTail == null) ||
1030
+ old.items.any { !it.hasExplicitHeight } ||
1031
+ next.items.any { !it.hasExplicitHeight } ||
1032
+ old.items.any { it.type !in setOf("identity", "dataRow") } ||
1033
+ next.items.any { it.type !in setOf("identity", "dataRow") } ||
1034
+ old.items.any { it.type == "sectionHeader" } ||
1035
+ next.items.any { it.type == "sectionHeader" }) return null
1036
+ val prefix = minOf(old.items.size, next.items.size)
1037
+ if (prefix == 0) return null
1038
+ if (structuralTail != null && prefix != structuralTail?.prefixCount) return null
1039
+ for (index in 0 until prefix) {
1040
+ val before = old.items[index]
1041
+ val after = next.items[index]
1042
+ if (before.key != after.key || before.rendererKey != after.rendererKey ||
1043
+ explicitTailRowHeight(before) != explicitTailRowHeight(after) ||
1044
+ explicitTailRowSpacingPx(before, old.itemSpacing) !=
1045
+ explicitTailRowSpacingPx(after, next.itemSpacing)) return null
1046
+ }
1047
+ return prefix
1048
+ }
1049
+
1050
+ private fun explicitTailRowHeight(item: NativeListItem): Int =
1051
+ item.styledHeight?.let { (it * density).roundToInt() } ?: run {
1052
+ val value = item.json.optDouble("height")
1053
+ when (item.json.optString("heightRounding")) {
1054
+ "floor" -> (value * density).toInt()
1055
+ "nearest" -> (value * density).roundToInt()
1056
+ else -> if (usesSelectorSourceScale || item.usesSelectorSourceScale)
1057
+ (item.json.optInt("height") * density).roundToInt()
1058
+ else NativeListScale.dp(resources, item.json.optInt("height"))
1059
+ }
1060
+ }
1061
+
1062
+ private fun explicitTailRowSpacingPx(item: NativeListItem, spacing: Int): Int {
1063
+ if (item.type == "identity" &&
1064
+ item.json.optString("presentation") == "walletSidebar") {
1065
+ val height = item.styledHeight ?: item.json.optDouble("height")
1066
+ return ((height + spacing) * density).roundToInt() -
1067
+ (height * density).roundToInt()
1068
+ }
1069
+ return dp(spacing)
1070
+ }
1071
+
1072
+ private fun exceedsStructuralTailHostLimit(
1073
+ old: NativeListConfig,
1074
+ next: NativeListConfig,
1075
+ prefixCount: Int,
1076
+ ): Boolean {
1077
+ val items = (if (old.items.size > next.items.size) old.items else next.items)
1078
+ .drop(prefixCount)
1079
+ if (items.size <= 128) return false
1080
+ val starts = LongArray(items.size)
1081
+ val heights = IntArray(items.size)
1082
+ var cursor = 0L
1083
+ items.forEachIndexed { index, item ->
1084
+ starts[index] = cursor
1085
+ heights[index] = explicitTailRowHeight(item)
1086
+ cursor += heights[index] + explicitTailRowSpacingPx(item, next.itemSpacing)
1087
+ }
1088
+ val window = 3L * recyclerView.height
1089
+ return (0..(items.size - 129)).any { first ->
1090
+ starts[first + 128] - (starts[first] + heights[first]) <= window
1091
+ }
1092
+ }
1093
+
1094
+ private fun clearStructuralTail() {
1095
+ pendingPreparingFooterFrame = null
1096
+ structuralTail?.hosts?.values?.forEach { host ->
1097
+ structuralTailLayer.removeView(host)
1098
+ host.recycle()
1099
+ host.dispose()
1100
+ }
1101
+ structuralTail = null
1102
+ structuralTailFinalizing = false
1103
+ structuralTailPreparing = false
1104
+ structuralFooterCompensatedHeightPx = null
1105
+ structuralTailRowsInAdapterPx = 0
1106
+ setStructuralTailExtent(0)
1107
+ structuralTailLayer.removeAllViews()
1108
+ structuralTailLayer.visibility = GONE
1109
+ structuralTailLayer.layoutParams?.let { params ->
1110
+ params.width = 0
1111
+ params.height = 0
1112
+ structuralTailLayer.layoutParams = params
1113
+ }
1114
+ structuralTailLayer.forceLayout()
1115
+ structuralTailLayer.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY),
1116
+ View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY))
1117
+ structuralTailLayer.layout(0, 0, 0, 0)
1118
+ }
1119
+
1120
+ private fun structuralTailRowOrSlotExtentPx(position: Int): Int {
1121
+ val row = position - headerSlotAdapter.itemCount
1122
+ val item = adapter.itemAt(row)
1123
+ if (row < 0 || item == null || !item.hasExplicitHeight) return estimatedScrollExtentPx(position)
1124
+ return explicitTailRowHeight(item) +
1125
+ explicitTailRowSpacingPx(item, config?.itemSpacing ?: 0)
1126
+ }
1127
+
1128
+ private fun structuralTailMeasuredScrollDistancePx(): Int? {
1129
+ if (layoutManager.orientation != RecyclerView.VERTICAL) return null
1130
+ val first = layoutManager.findFirstVisibleItemPosition()
1131
+ if (first == RecyclerView.NO_POSITION) return null
1132
+ val view = layoutManager.findViewByPosition(first) ?: return null
1133
+ val prefix = nativeListScrollPrefixPx(first, layoutManager.spanCount,
1134
+ layoutManager.spanSizeLookup::getSpanSize, ::structuralTailRowOrSlotExtentPx)
1135
+ val topMargin = (view.layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin ?: 0
1136
+ val top = layoutManager.getDecoratedTop(view) - topMargin
1137
+ return (prefix + recyclerView.paddingTop - top).coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
1138
+ }
1139
+
1140
+ private fun tailScrollExtentPx(): Int =
1141
+ (if (structuralTail != null) structuralTailMeasuredScrollDistancePx()
1142
+ else measuredScrollDistancePx()) ?: logicalScrollDistancePx
1143
+
1144
+ private fun updateStructuralTailWindow() {
1145
+ val tail = structuralTail ?: return
1146
+ if (structuralTailFinalizing || structuralTailRowsInAdapterPx > 0) return
1147
+ val scroll = tailScrollExtentPx()
1148
+ val viewport = recyclerView.height
1149
+ if (viewport <= 0) return
1150
+ val y = recyclerView.top + recyclerView.paddingTop + structuralTailStartContentY - scroll
1151
+ val width = (recyclerView.width - recyclerView.paddingLeft - recyclerView.paddingRight).coerceAtLeast(0)
1152
+ val params = structuralTailLayer.layoutParams as FrameLayout.LayoutParams
1153
+ val left = recyclerView.left + recyclerView.paddingLeft
1154
+ if (params.width != width || params.height != structuralSpacerHeightPx ||
1155
+ params.leftMargin != left || params.topMargin != y) {
1156
+ params.width = width
1157
+ params.height = structuralSpacerHeightPx
1158
+ params.leftMargin = left
1159
+ params.topMargin = y
1160
+ structuralTailLayer.layoutParams = params
1161
+ }
1162
+ structuralTailLayer.visibility = VISIBLE
1163
+ val low = (-y - viewport).coerceAtLeast(0)
1164
+ val high = minOf(structuralSpacerHeightPx, -y + 2 * viewport)
1165
+ var first = 0
1166
+ var end = tail.items.size
1167
+ while (first < end) {
1168
+ val middle = (first + end) / 2
1169
+ if (tail.starts[middle] + tail.heights[middle] < low) first = middle + 1
1170
+ else end = middle
1171
+ }
1172
+ var last = first
1173
+ end = tail.items.size
1174
+ while (last < end) {
1175
+ val middle = (last + end) / 2
1176
+ if (tail.starts[middle] <= high) last = middle + 1
1177
+ else end = middle
1178
+ }
1179
+ if (last - first > 128) {
1180
+ finishStructuralTail(interrupted = false)
1181
+ return
1182
+ }
1183
+ tail.hosts.keys.filter { it < first || it >= last }.forEach { index ->
1184
+ val host = tail.hosts.remove(index) ?: return@forEach
1185
+ structuralTailLayer.removeView(host)
1186
+ host.recycle()
1187
+ host.dispose()
1188
+ }
1189
+ for (index in first until last) {
1190
+ if (tail.hosts.containsKey(index)) continue
1191
+ val item = tail.items[index]
1192
+ val host = NativeListRendererRegistry.create(reactContext, item.rendererKey.ordinal, fonts)
1193
+ host.listStyle = config?.listStyle
1194
+ host.bind(item, config?.theme, config?.layout ?: "linear", "vertical",
1195
+ tail.prefixCount + index, item.json.optBoolean("selected") ||
1196
+ (config?.selectedKeys?.contains(item.key) == true), adapter.checkboxState,
1197
+ useSourceScale = usesSelectorSourceScale)
1198
+ host.isClickable = false
1199
+ host.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
1200
+ structuralTailLayer.addView(host, FrameLayout.LayoutParams(width, tail.heights[index],
1201
+ Gravity.TOP or Gravity.LEFT).apply { topMargin = tail.starts[index] })
1202
+ tail.hosts[index] = host
1203
+ tail.peakHosts = maxOf(tail.peakHosts, tail.hosts.size)
1204
+ }
1205
+ val height = structuralSpacerHeightPx
1206
+ val needsMeasure = structuralTailLayer.isLayoutRequested ||
1207
+ structuralTailLayer.measuredWidth != width ||
1208
+ structuralTailLayer.measuredHeight != height ||
1209
+ tail.hosts.values.any { it.isLayoutRequested }
1210
+ if (needsMeasure) {
1211
+ structuralTailLayer.measure(
1212
+ MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
1213
+ MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
1214
+ )
1215
+ }
1216
+ if (needsMeasure || structuralTailLayer.left != left || structuralTailLayer.top != y ||
1217
+ structuralTailLayer.right != left + width || structuralTailLayer.bottom != y + height) {
1218
+ structuralTailLayer.layout(left, y, left + width, y + height)
1219
+ }
1220
+ }
1221
+
1222
+ private fun updateStructuralTailTarget() {
1223
+ val tail = structuralTail ?: return
1224
+ val disclosure = config?.disclosure
1225
+ val finalChrome = if (disclosure == null) 0 else
1226
+ slotHeights[5] + if (disclosure.expanded) slotHeights[4] + disclosureInsetExtentPx() else 0
1227
+ val leftHeight = recyclerView.paddingTop + structuralTailStartContentY + tail.finalExtent +
1228
+ finalChrome + footerNaturalHeightPx() + recyclerView.paddingBottom
1229
+ val sidecarHeight = if (sidecarLayout == null) 0 else
1230
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1231
+ val maximum = (maxOf(leftHeight, sidecarHeight) - recyclerView.height).coerceAtLeast(0)
1232
+ var target = structuralTailStartOffset.coerceIn(0, maximum)
1233
+ if (tail.finalExtent == 0 && disclosure != null && slotHeights[5] > 0) {
1234
+ val toggleTop = recyclerView.paddingTop + structuralTailStartContentY
1235
+ val toggleBottom = toggleTop + slotHeights[5]
1236
+ val sticky = stickyHeaderHost.height
1237
+ val lower = toggleBottom - recyclerView.height + recyclerView.paddingBottom
1238
+ val upper = toggleTop - recyclerView.paddingTop - sticky
1239
+ target = if (lower <= upper) target.coerceIn(lower, upper) else upper
1240
+ } else if (tail.finalExtent == 0 && footerNaturalHeightPx() > 0) {
1241
+ val footerTop = recyclerView.paddingTop + structuralTailStartContentY
1242
+ val footerBottom = footerTop + footerNaturalHeightPx()
1243
+ val sticky = stickyHeaderHost.height
1244
+ val lower = footerBottom - recyclerView.height + recyclerView.paddingBottom
1245
+ val upper = footerTop - recyclerView.paddingTop - sticky
1246
+ target = if (lower <= upper) target.coerceIn(lower, upper) else upper
1247
+ }
1248
+ structuralTailTargetOffset = target.coerceIn(0, maximum)
1249
+ }
1250
+
1251
+ private fun positionSettledDisclosureToggle() {
1252
+ if (recyclerView.width <= 0 || recyclerView.height <= 0 ||
1253
+ structureToggleAdapter.itemCount == 0 || slotHeights[5] <= 0 ||
1254
+ recyclerView.scrollState != RecyclerView.SCROLL_STATE_IDLE ||
1255
+ pendingScrollRequest != null || acceptedScrollRequest != null ||
1256
+ executingScrollCommand) return
1257
+ val togglePosition = headerSlotAdapter.itemCount + adapter.itemCount +
1258
+ emptySlotAdapter.itemCount + structuralSpacerAdapter.itemCount +
1259
+ expandedContentAdapter.itemCount
1260
+ val toggleTop = (recyclerView.paddingTop.toLong() +
1261
+ nativeListScrollPrefixPx(togglePosition, layoutManager.spanCount,
1262
+ layoutManager.spanSizeLookup::getSpanSize, ::structuralTailRowOrSlotExtentPx))
1263
+ .coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
1264
+ val stickyTop = recyclerView.paddingTop + stickyHeaderHost.height
1265
+ val lower = toggleTop + slotHeights[5] - recyclerView.height + recyclerView.paddingBottom
1266
+ val upper = toggleTop - stickyTop
1267
+ val sidecarBottom = if (sidecarLayout == null) 0 else
1268
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1269
+ val leftExtent = (nativeListScrollPrefixPx(
1270
+ scrollContentAdapter.itemCount - sidecarSpacerAdapter.itemCount,
1271
+ layoutManager.spanCount, layoutManager.spanSizeLookup::getSpanSize,
1272
+ ::structuralTailRowOrSlotExtentPx) +
1273
+ recyclerView.paddingTop + recyclerView.paddingBottom)
1274
+ .coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
1275
+ val maximum = (maxOf(leftExtent, sidecarBottom) - recyclerView.height).coerceAtLeast(0)
1276
+ val current = structuralTailMeasuredScrollDistancePx() ?: tailScrollExtentPx()
1277
+ val target = (if (lower <= upper) current.coerceIn(lower, upper) else upper)
1278
+ .coerceIn(0, maximum)
1279
+ val ownsCommand = !structuralTailCommandActive
1280
+ if (ownsCommand) {
1281
+ notifyScrollCommand(false, 0)
1282
+ notifyScrollCommand(false, 1)
1283
+ }
1284
+ try {
1285
+ recyclerView.scrollBy(0, target - current)
1286
+ relayoutRecyclerViewImmediately()
1287
+ } finally {
1288
+ if (ownsCommand) notifyScrollCommand(false, 2)
1289
+ }
1290
+ }
1291
+
1292
+ private fun finishStructuralTail(interrupted: Boolean) {
1293
+ val next = config ?: return
1294
+ if (structuralTail == null || structuralTailFinalizing) return
1295
+ structuralTailFinalizing = true
1296
+ val epoch = ++structuralTransitionEpoch
1297
+ pendingPreparingFooterFrame = pendingPreparingFooterFrame?.takeIf {
1298
+ it.footer === containerSlots.getOrNull(2)
1299
+ }?.copy(epoch = epoch, handoffOnly = true)
1300
+ structuralAnimator?.cancel()
1301
+ structuralAnimator = null
1302
+ recyclerView.itemAnimator = null
1303
+ structuralFooterHoldTop = null
1304
+ structuralFooterVisualStartTop = null
1305
+ structuralFooterVisualEndTop = null
1306
+ footerSlotAdapter.setVisualTranslationY(0f)
1307
+ if (interrupted && structuralTailCommandActive) {
1308
+ structuralTailCommandActive = false
1309
+ notifyScrollCommand(false, 2)
1310
+ }
1311
+ adapter.submitList(next.items) {
1312
+ if (epoch != structuralTransitionEpoch || disposed) return@submitList
1313
+ fun handoff() {
1314
+ if (epoch != structuralTransitionEpoch || disposed) return
1315
+ if (recyclerView.isComputingLayout) {
1316
+ recyclerView.post { handoff() }
1317
+ return
1318
+ }
1319
+ val acceptedPendingFooter = acceptPendingFooterValues(adjustTailStart = false)
1320
+ presentAcceptedDisclosureEndpoint(next)
1321
+ if (recyclerView.width <= 0 || recyclerView.height <= 0) {
1322
+ clearStructuralTail()
1323
+ if (acceptedPendingFooter) updateContainerSlots()
1324
+ if (structuralTailCommandActive) {
1325
+ structuralTailCommandActive = false
1326
+ notifyScrollCommand(false, 2)
1327
+ }
1328
+ if (next.disclosure != null) {
1329
+ disclosureTransitioning = false
1330
+ syncDisclosurePresentation()
1331
+ settleDisclosureCommand(if (interrupted) "interrupted" else "completed")
1332
+ }
1333
+ scheduleVisibleEvent()
1334
+ checkEndReached()
1335
+ return
1336
+ }
1337
+ structuralTailRowsInAdapterPx = 0
1338
+ setStructuralTailExtent(0)
1339
+ updateSidecarSpacerNow()
1340
+ relayoutRecyclerViewImmediately()
1341
+ if (epoch != structuralTransitionEpoch || disposed) return
1342
+ if (!interrupted && recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE) {
1343
+ val sidecarBottom = if (sidecarLayout == null) 0 else
1344
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1345
+ val maximum = (maxOf(sidecarLeftExtentPx(), sidecarBottom) -
1346
+ recyclerView.height).coerceAtLeast(0)
1347
+ val target = structuralTailTargetOffset.coerceIn(0, maximum)
1348
+ recyclerView.scrollBy(0, target - tailScrollExtentPx())
1349
+ }
1350
+ if (epoch != structuralTransitionEpoch || disposed) return
1351
+ clearStructuralTail()
1352
+ if (acceptedPendingFooter) updateContainerSlots()
1353
+ performPendingScrollIfNeeded()
1354
+ if (structuralTailCommandActive) {
1355
+ structuralTailCommandActive = false
1356
+ notifyScrollCommand(false, 2)
1357
+ }
1358
+ if (next.disclosure != null) {
1359
+ disclosureTransitioning = false
1360
+ syncDisclosurePresentation()
1361
+ settleDisclosureCommand(if (interrupted) "interrupted" else "completed")
1362
+ }
1363
+ scheduleVisibleEvent()
1364
+ checkEndReached()
1365
+ }
1366
+ handoff()
1367
+ }
1368
+ }
1369
+
1370
+ private fun discardStructuralTail() {
1371
+ if (structuralTail == null) return
1372
+ structuralTransitionEpoch += 1
1373
+ structuralAnimator?.cancel()
1374
+ structuralAnimator = null
1375
+ if (structuralTailCommandActive) {
1376
+ structuralTailCommandActive = false
1377
+ notifyScrollCommand(false, 2)
1378
+ }
1379
+ clearStructuralTail()
1380
+ setStructuralSpacerHeight(0)
1381
+ }
1382
+
1383
+ private fun holdStructuralTailUntilListCommit(): Int {
1384
+ val epoch = ++structuralTransitionEpoch
1385
+ pendingPreparingFooterFrame = pendingPreparingFooterFrame?.takeIf {
1386
+ it.footer === containerSlots.getOrNull(2)
1387
+ }?.copy(epoch = epoch, handoffOnly = true)
1388
+ structuralAnimator?.cancel()
1389
+ structuralAnimator = null
1390
+ structuralTailFinalizing = true
1391
+ if (structuralTailCommandActive) {
1392
+ structuralTailCommandActive = false
1393
+ notifyScrollCommand(false, 2)
1394
+ }
1395
+ return epoch
1396
+ }
1397
+
1398
+ private fun completeHeldTailCommit(
1399
+ next: NativeListConfig,
1400
+ epoch: Int,
1401
+ completion: () -> Unit,
1402
+ positionToggle: Boolean,
1403
+ ) {
1404
+ if (epoch != structuralTransitionEpoch || disposed) return
1405
+ if (recyclerView.isComputingLayout) {
1406
+ recyclerView.post { completeHeldTailCommit(next, epoch, completion, positionToggle) }
1407
+ return
1408
+ }
1409
+ val acceptedPendingFooter = acceptPendingFooterValues(adjustTailStart = false)
1410
+ presentAcceptedDisclosureEndpoint(next)
1411
+ structuralTailRowsInAdapterPx = 0
1412
+ setStructuralTailExtent(0)
1413
+ if (acceptedPendingFooter) updateContainerSlots()
1414
+ updateSidecarSpacerNow()
1415
+ relayoutRecyclerViewImmediately()
1416
+ if (positionToggle) positionSettledDisclosureToggle()
1417
+ if (epoch != structuralTransitionEpoch || disposed) return
1418
+ clearStructuralTail()
1419
+ disclosureTransitioning = false
1420
+ syncDisclosurePresentation()
1421
+ completion()
1422
+ }
1423
+
1424
+ private fun applyStructuralTailFrame(tail: StructuralTail, epoch: Int, progress: Float): Boolean {
1425
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail ||
1426
+ structuralTailFinalizing) return true
1427
+ if (recyclerView.isComputingLayout) return false
1428
+ val segmentProgress = if (structuralTailStartProgress >= 1f) 1f else
1429
+ ((progress - structuralTailStartProgress) /
1430
+ (1f - structuralTailStartProgress)).coerceIn(0f, 1f)
1431
+ config?.disclosure?.let { disclosure ->
1432
+ val target = if (disclosure.expanded) 1f else 0f
1433
+ disclosureFraction = disclosureStartFraction +
1434
+ (target - disclosureStartFraction) * segmentProgress
1435
+ val contentProgress = if (disclosureContentStartProgress >= 1f) 1f else
1436
+ ((progress - disclosureContentStartProgress) /
1437
+ (1f - disclosureContentStartProgress)).coerceIn(0f, 1f)
1438
+ val contentTarget = if (disclosure.expanded) slotHeights[4] else 0
1439
+ disclosurePresentedContentPx = (disclosureContentStartPx +
1440
+ (contentTarget - disclosureContentStartPx) * contentProgress).roundToInt()
1441
+ syncDisclosurePresentation()
1442
+ }
1443
+ setStructuralTailExtent((structuralTailStartExtentPx +
1444
+ (tail.finalExtent - structuralTailStartExtentPx) * segmentProgress).roundToInt())
1445
+ updateSidecarSpacerNow()
1446
+ relayoutRecyclerViewImmediately()
1447
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail) return true
1448
+ if (!structuralScrollInterrupted && recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE) {
1449
+ val sidecarBottom = if (sidecarLayout == null) 0 else
1450
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1451
+ val maximum = (maxOf(sidecarLeftExtentPx(), sidecarBottom) -
1452
+ recyclerView.height).coerceAtLeast(0)
1453
+ val desired = (structuralTailStartOffset +
1454
+ (structuralTailTargetOffset - structuralTailStartOffset) * segmentProgress)
1455
+ .roundToInt().coerceIn(0, maximum)
1456
+ val requestedScroll = desired - tailScrollExtentPx()
1457
+ recyclerView.scrollBy(0, requestedScroll)
1458
+ }
1459
+ updateStructuralTailWindow()
1460
+ return true
1461
+ }
1462
+
1463
+ private fun commitPreparingFooterFrame(): Boolean {
1464
+ val pending = pendingPreparingFooterFrame ?: return true
1465
+ if (structuralTail == null || structuralTailRowsInAdapterPx <= 0 ||
1466
+ pending.epoch != structuralTransitionEpoch || disposed ||
1467
+ pending.footer !== containerSlots.getOrNull(2)) {
1468
+ if (pendingPreparingFooterFrame === pending) pendingPreparingFooterFrame = null
1469
+ return true
1470
+ }
1471
+ if (pending.handoffOnly || recyclerView.isComputingLayout) return false
1472
+ pendingPreparingFooterFrame = null
1473
+ if (pending.observedNativeHeight != null) {
1474
+ structuralFooterObservedNativeHeightPx = pending.observedNativeHeight
1475
+ } else {
1476
+ containerSlots.getOrNull(2)?.measuredHeight
1477
+ ?.takeIf { it > 0 && it != pending.naturalHeight }
1478
+ ?.let { structuralFooterObservedNativeHeightPx = it }
1479
+ }
1480
+ reconcileStructuralFooterHeight(pending.naturalHeight)
1481
+ acceptedFooterNaturalHeightPx = pending.naturalHeight
1482
+ for (index in 0..5) slotHeights[index] = pending.heights[index]
1483
+ updateContainerSlots()
1484
+ updateStructuralTailTarget()
1485
+ updateSidecarGeometry()
1486
+ updateSidecarSpacerNow()
1487
+ relayoutRecyclerViewImmediately()
1488
+ if (pending.epoch != structuralTransitionEpoch || disposed ||
1489
+ pending.footer !== containerSlots.getOrNull(2)) {
1490
+ return pendingPreparingFooterFrame == null
1491
+ }
1492
+ val sidecarBottom = if (sidecarLayout == null) 0 else
1493
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom
1494
+ val maximum = (maxOf(sidecarLeftExtentPx(), sidecarBottom) -
1495
+ recyclerView.height).coerceAtLeast(0)
1496
+ val desired = pending.ownerOffset.coerceIn(0, maximum)
1497
+ recyclerView.scrollBy(0, desired - tailScrollExtentPx())
1498
+ relayoutRecyclerViewImmediately()
1499
+ updateStructuralTailWindow()
1500
+ return pendingPreparingFooterFrame == null
1501
+ }
1502
+
1503
+ private fun acceptPendingFooterValues(adjustTailStart: Boolean): Boolean {
1504
+ val pending = pendingPreparingFooterFrame ?: return false
1505
+ if (pending.footer !== containerSlots.getOrNull(2) || disposed ||
1506
+ pending.epoch != structuralTransitionEpoch) {
1507
+ pendingPreparingFooterFrame = null
1508
+ return false
1509
+ }
1510
+ val latestNativeHeight = if (pending.observedNativeHeight != null)
1511
+ pending.footer?.measuredHeight?.takeIf { it > 0 } else null
1512
+ val naturalHeight = if (latestNativeHeight != null &&
1513
+ latestNativeHeight != pending.observedNativeHeight) {
1514
+ (ceil(latestNativeHeight / density.toDouble()) * density).roundToInt()
1515
+ } else pending.naturalHeight
1516
+ if (adjustTailStart) {
1517
+ val previousHeight = structuralFooterCompensatedHeightPx ?:
1518
+ acceptedFooterNaturalHeightPx ?: slotHeights[2]
1519
+ val delta = previousHeight - naturalHeight
1520
+ structuralTailSignedExtentPx += delta
1521
+ structuralTailStartExtentPx += delta
1522
+ }
1523
+ structuralFooterObservedNativeHeightPx = latestNativeHeight ?:
1524
+ containerSlots.getOrNull(2)?.measuredHeight?.takeIf {
1525
+ it > 0 && it != naturalHeight
1526
+ }
1527
+ acceptedFooterNaturalHeightPx = naturalHeight
1528
+ structuralFooterCompensatedHeightPx = naturalHeight
1529
+ for (index in 0..5) slotHeights[index] = pending.heights[index]
1530
+ pendingPreparingFooterFrame = null
1531
+ return true
1532
+ }
1533
+
1534
+ private fun startPrefixTailTransition(
1535
+ previous: NativeListConfig,
1536
+ next: NativeListConfig,
1537
+ transition: NativeListConfig.StructuralTransition,
1538
+ prefixCount: Int,
1539
+ ) {
1540
+ val previousTail = structuralTail
1541
+ val carriedExtent = previousTail?.let { structuralTailSignedExtentPx }
1542
+ val startOffset = structuralTailMeasuredScrollDistancePx() ?: tailScrollExtentPx()
1543
+ if (previousTail == null) {
1544
+ cancelStructuralTransition()
1545
+ } else {
1546
+ structuralTransitionEpoch += 1
1547
+ structuralAnimator?.cancel()
1548
+ structuralAnimator = null
1549
+ if (structuralTailCommandActive) {
1550
+ structuralTailCommandActive = false
1551
+ notifyScrollCommand(false, 2)
1552
+ }
1553
+ // The old presentation remains visible until the new prefix and spacer commit together.
1554
+ structuralTailPreparing = true
1555
+ }
1556
+ val epoch = structuralTransitionEpoch
1557
+ val collapsing = previous.items.size > next.items.size
1558
+ val items = (if (collapsing) previous.items else next.items)
1559
+ .drop(prefixCount).toMutableList()
1560
+ val heights = IntArray(items.size) { explicitTailRowHeight(items[it]) }
1561
+ val spacings = IntArray(items.size) {
1562
+ explicitTailRowSpacingPx(items[it], next.itemSpacing)
1563
+ }
1564
+ val tail = StructuralTail(items, heights, spacings, prefixCount,
1565
+ if (collapsing) 0 else heights.sum() + spacings.sum())
1566
+ val startExtent = carriedExtent ?: if (collapsing) tail.extent else 0
1567
+ disclosureStartFraction = disclosureFraction
1568
+ if (next.disclosure != null) {
1569
+ disclosureContentStartPx = disclosurePresentedContentPx
1570
+ disclosureContentStartProgress = 0f
1571
+ disclosureTransitioning = true
1572
+ }
1573
+ val startContentY = (if (headerSlotAdapter.itemCount > 0) slotHeights[0] else 0) +
1574
+ next.items.take(prefixCount).sumOf {
1575
+ explicitTailRowHeight(it) + explicitTailRowSpacingPx(it, next.itemSpacing)
1576
+ }
1577
+ if (previousTail == null) {
1578
+ structuralTail = tail
1579
+ structuralTailRowsInAdapterPx = if (collapsing) tail.extent else 0
1580
+ structuralTailStartExtentPx = startExtent
1581
+ structuralTailStartProgress = 0f
1582
+ structuralTailStartContentY = startContentY
1583
+ structuralTailStartOffset = startOffset
1584
+ structuralTailTargetOffset = startOffset
1585
+ setStructuralTailExtent(startExtent)
1586
+ }
1587
+ structuralScrollInterrupted = false
1588
+ structuralFooterCompensatedHeightPx = null
1589
+ recyclerView.itemAnimator = null
1590
+ acceptRowIndex(next, previous)
1591
+ config = next
1592
+ pruneMeasuredRowExtents(next.items)
1593
+ updateContainerSlots()
1594
+ usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
1595
+ adapter.usesSelectorSourceScale = usesSelectorSourceScale
1596
+ adapter.theme = next.theme
1597
+ adapter.listStyle = next.listStyle
1598
+ adapter.layout = next.layout
1599
+ adapter.orientation = next.orientation
1600
+ adapter.selectedKeys = next.selectedKeys
1601
+ if (previous.generation != next.generation) endReachedGeneration = null
1602
+ configureSectionIndex(next)
1603
+ updateLayout(next)
1604
+ bindFooter(next)
1605
+ updateReordering(next)
1606
+ refreshLayout.isEnabled = next.pullToRefresh
1607
+ refreshLayout.setDistanceToTriggerSync(
1608
+ next.refreshTriggerDistance?.let { (it * density).roundToInt() }
1609
+ ?: defaultRefreshTriggerDistancePx,
1610
+ )
1611
+ refreshLayout.isRefreshing = next.refreshing
1612
+ structuralTailCommandActive = true
1613
+ notifyScrollCommand(false, 0)
1614
+ notifyScrollCommand(false, 1)
1615
+ adapter.submitList(next.items.take(prefixCount)) {
1616
+ fun commitPrefix() {
1617
+ if (epoch != structuralTransitionEpoch || disposed ||
1618
+ structuralTail !== (previousTail ?: tail) || structuralTailFinalizing) return
1619
+ if (recyclerView.isComputingLayout) {
1620
+ recyclerView.post { commitPrefix() }
1621
+ return
1622
+ }
1623
+ if (previousTail != null) {
1624
+ clearStructuralTail()
1625
+ structuralTail = tail
1626
+ structuralTailStartExtentPx = startExtent
1627
+ structuralTailStartProgress = 0f
1628
+ structuralTailStartContentY = startContentY
1629
+ structuralTailStartOffset = startOffset
1630
+ structuralTailTargetOffset = startOffset
1631
+ }
1632
+ acceptPendingFooterValues(adjustTailStart = true)
1633
+ structuralTailPreparing = false
1634
+ structuralTailRowsInAdapterPx = 0
1635
+ setStructuralTailExtent(structuralTailStartExtentPx)
1636
+ updateStructuralTailTarget()
1637
+ if (recyclerView.width <= 0 || recyclerView.height <= 0) {
1638
+ finishStructuralTail(interrupted = false)
1639
+ return
1640
+ }
1641
+ applyStructuralTailFrame(tail, epoch, 0f)
1642
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail ||
1643
+ structuralTailFinalizing) return
1644
+ var lastAppliedProgress = 0f
1645
+ var frameScheduled = false
1646
+ fun applyProgress(progress: Float) {
1647
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail ||
1648
+ structuralTailFinalizing) return
1649
+ val nextProgress = maxOf(progress, lastAppliedProgress)
1650
+ if (!applyStructuralTailFrame(tail, epoch, nextProgress)) {
1651
+ if (!frameScheduled) {
1652
+ frameScheduled = true
1653
+ recyclerView.post {
1654
+ frameScheduled = false
1655
+ val current = structuralAnimator?.animatedValue as? Float ?: nextProgress
1656
+ applyProgress(current)
1657
+ }
1658
+ }
1659
+ return
1660
+ }
1661
+ lastAppliedProgress = nextProgress
1662
+ }
1663
+ structuralAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
1664
+ duration = transition.durationMs
1665
+ interpolator = android.view.animation.AccelerateDecelerateInterpolator()
1666
+ addUpdateListener { animation ->
1667
+ if (epoch != structuralTransitionEpoch || disposed || structuralTail !== tail) return@addUpdateListener
1668
+ if (Build.VERSION.SDK_INT >= 26 && !ValueAnimator.areAnimatorsEnabled()) {
1669
+ finishStructuralTail(interrupted = false)
1670
+ return@addUpdateListener
1671
+ }
1672
+ applyProgress(animation.animatedValue as Float)
1673
+ }
1674
+ addListener(object : AnimatorListenerAdapter() {
1675
+ override fun onAnimationEnd(animation: Animator) {
1676
+ if (epoch == structuralTransitionEpoch && structuralTail === tail)
1677
+ finishStructuralTail(interrupted = structuralScrollInterrupted)
1678
+ }
1679
+ })
1680
+ start()
1681
+ }
1682
+ }
1683
+ commitPrefix()
1684
+ }
1685
+ }
1686
+
1687
+ private fun updatePrefixTailSnapshot(
1688
+ previous: NativeListConfig,
1689
+ next: NativeListConfig,
1690
+ acceptIndex: Boolean = false,
1691
+ ): Boolean {
1692
+ val tail = structuralTail ?: return false
1693
+ if (structuralTailPreparing || structuralTailFinalizing ||
1694
+ structuralTailRowsInAdapterPx > 0 ||
1695
+ previous.items.size != next.items.size ||
1696
+ previous.disclosure != next.disclosure ||
1697
+ previous.layout != next.layout || previous.orientation != next.orientation ||
1698
+ previous.theme?.toString() != next.theme?.toString() ||
1699
+ previous.listStyle?.toString() != next.listStyle?.toString() ||
1700
+ previous.itemSpacing != next.itemSpacing ||
1701
+ previous.contentPadding != next.contentPadding ||
1702
+ previous.contentPaddingTop != next.contentPaddingTop ||
1703
+ previous.contentPaddingBottom != next.contentPaddingBottom ||
1704
+ previous.contentPaddingHorizontal != next.contentPaddingHorizontal) return false
1705
+ for (index in next.items.indices) {
1706
+ val before = previous.items[index]
1707
+ val after = next.items[index]
1708
+ if (before.key != after.key || before.rendererKey != after.rendererKey ||
1709
+ !after.hasExplicitHeight || explicitTailRowHeight(before) != explicitTailRowHeight(after) ||
1710
+ explicitTailRowSpacingPx(before, previous.itemSpacing) !=
1711
+ explicitTailRowSpacingPx(after, next.itemSpacing))
1712
+ return false
1713
+ }
1714
+ if (acceptIndex) acceptRowIndex(next, previous)
1715
+ config = next
1716
+ adapter.selectedKeys = next.selectedKeys
1717
+ adapter.submitList(next.items.take(tail.prefixCount)) {
1718
+ if (structuralTail !== tail || disposed) return@submitList
1719
+ scheduleVisibleEvent()
1720
+ }
1721
+ if (tail.finalExtent > 0) {
1722
+ for (index in tail.items.indices) {
1723
+ val item = next.items[tail.prefixCount + index]
1724
+ if (tail.items[index].content == item.content) continue
1725
+ tail.items[index] = item
1726
+ tail.hosts[index]?.let { host ->
1727
+ host.bind(item, next.theme, next.layout, "vertical", tail.prefixCount + index,
1728
+ item.json.optBoolean("selected") || next.selectedKeys.contains(item.key),
1729
+ adapter.checkboxState, useSourceScale = usesSelectorSourceScale)
1730
+ host.isClickable = false
1731
+ }
1732
+ }
1733
+ }
1734
+ bindFooter(next)
1735
+ updateStructuralTailTarget()
1736
+ return true
1737
+ }
1738
+
1739
+ private fun updateStructuralFooterHoldPosition() {
1740
+ val targetTop = structuralFooterHoldTop ?: return
1741
+ if (footerSlotAdapter.itemCount == 0) return
1742
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1743
+ layoutManager.findViewByPosition(footerPosition)?.let { footer ->
1744
+ footerSlotAdapter.setVisualTranslationY((targetTop - layoutManager.getDecoratedTop(footer)).toFloat())
1745
+ }
1746
+ }
1747
+
1748
+ private fun updateStructuralFooterVisualPosition() {
1749
+ val startTop = structuralFooterVisualStartTop ?: return
1750
+ val endTop = structuralFooterVisualEndTop ?: return
1751
+ if (footerSlotAdapter.itemCount == 0) return
1752
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1753
+ layoutManager.findViewByPosition(footerPosition)?.let { footer ->
1754
+ val desiredTop = startTop + (endTop - startTop) * structuralFooterVisualProgress
1755
+ footerSlotAdapter.setVisualTranslationY(desiredTop - layoutManager.getDecoratedTop(footer))
1756
+ }
1757
+ }
1758
+
1759
+ private fun cancelStructuralTransition() {
1760
+ if (structuralTail != null) discardStructuralTail()
1761
+ structuralTransitionEpoch += 1
1762
+ pendingStructuralTransition = null
1763
+ pendingStructuralStartScheduled = false
1764
+ structuralAnimator?.cancel()
1765
+ structuralAnimator = null
1766
+ recyclerView.itemAnimator = null
1767
+ setStructuralSpacerHeight(0)
1768
+ footerSlotAdapter.setVisualTranslationY(0f)
1769
+ structuralFooterHoldTop = null
1770
+ structuralFooterVisualStartTop = null
1771
+ structuralFooterVisualEndTop = null
1772
+ structuralFooterVisualProgress = 0f
1773
+ structuralFooterCompensatedHeightPx = null
1774
+ structuralStartSpacerPx = 0
1775
+ }
1776
+
1777
+ private fun startPendingStructuralTransition() {
1778
+ val pending = pendingStructuralTransition ?: return
1779
+ if (pending.epoch != structuralTransitionEpoch || disposed || pendingStructuralStartScheduled) return
1780
+ val expected = config?.items?.map { it.key } ?: return
1781
+ if (adapter.currentList.map { it.key } != expected) return
1782
+ pendingStructuralStartScheduled = true
1783
+ recyclerView.postOnAnimation {
1784
+ if (pending.epoch != structuralTransitionEpoch) return@postOnAnimation
1785
+ pendingStructuralStartScheduled = false
1786
+ val latest = pendingStructuralTransition
1787
+ if (latest?.epoch == pending.epoch && !disposed) {
1788
+ if (recyclerView.isComputingLayout) {
1789
+ startPendingStructuralTransition()
1790
+ return@postOnAnimation
1791
+ }
1792
+ alignPendingStructuralAnchor(latest)
1793
+ if (latest.anchorTop != null || (latest.collapsing && latest.footerStartTop != null)) {
1794
+ relayoutRecyclerViewImmediately()
1795
+ }
1796
+ pendingStructuralTransition = null
1797
+ startStructuralTransition(
1798
+ latest.transition, latest.epoch, latest.anchorKey, latest.anchorTop,
1799
+ latest.footerStartTop,
1800
+ )
1801
+ }
1802
+ }
1803
+ }
1804
+
1805
+ private fun alignPendingStructuralFooter(pending: PendingStructuralTransition): Boolean {
1806
+ val top = pending.footerStartTop ?: return false
1807
+ if (!pending.collapsing || !pending.spacerInserted || footerSlotAdapter.itemCount == 0 || structuralScrollInterrupted) return false
1808
+ if (pending.footerAnchorAppliedTop == top) return false
1809
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
1810
+ layoutManager.scrollToPositionWithOffset(footerPosition, top - recyclerView.paddingTop)
1811
+ pendingStructuralTransition = pending.copy(footerAnchorAppliedTop = top)
1812
+ return true
1813
+ }
1814
+
1815
+ private fun alignPendingStructuralRow(pending: PendingStructuralTransition): Boolean {
1816
+ val key = pending.anchorKey ?: return false
1817
+ val top = pending.anchorTop ?: return false
1818
+ if (structuralScrollInterrupted || pending.rowAnchorAppliedTop == top) return false
1819
+ val desiredItems = config?.items ?: return false
1820
+ val rowIndex = desiredItems.indexOfFirst { it.key == key }
1821
+ if (rowIndex < 0 || adapter.itemCount != desiredItems.size ||
1822
+ adapter.currentList.getOrNull(rowIndex)?.key != key) return false
1823
+ layoutManager.scrollToPositionWithOffset(scrollPositionForRow(rowIndex), top - recyclerView.paddingTop)
1824
+ pendingStructuralTransition = pending.copy(rowAnchorAppliedTop = top)
1825
+ return true
1826
+ }
1827
+
1828
+ private fun alignPendingStructuralAnchor(pending: PendingStructuralTransition) {
1829
+ if (pending.anchorTop != null) alignPendingStructuralRow(pending)
1830
+ else alignPendingStructuralFooter(pending)
1831
+ }
1832
+
357
1833
  private fun measuredScrollDistancePx(): Int? {
358
1834
  if (layoutManager.orientation != RecyclerView.VERTICAL) return null
359
1835
  val first = layoutManager.findFirstVisibleItemPosition()
@@ -376,6 +1852,7 @@ class NativeListView(
376
1852
  // OneKey patch: vertical lists retain vertical drags and leave horizontal drags to a parent pager.
377
1853
  private val pagerGestureTouchSlop = ViewConfiguration.get(context).scaledTouchSlop
378
1854
  private var pagerGestureIsVertical = false
1855
+ private var pagerNativeGestureStarted = false
379
1856
  private val pagerGestureTouchListener = object : RecyclerView.SimpleOnItemTouchListener() {
380
1857
  private var downX = 0f
381
1858
  private var downY = 0f
@@ -389,30 +1866,43 @@ class NativeListView(
389
1866
  downY = event.y
390
1867
  directionResolved = false
391
1868
  pagerGestureIsVertical = false
1869
+ pagerNativeGestureStarted = false
392
1870
  }
393
- MotionEvent.ACTION_MOVE -> if (!directionResolved) {
1871
+ MotionEvent.ACTION_MOVE -> {
394
1872
  val deltaX = abs(event.x - downX)
395
1873
  val deltaY = abs(event.y - downY)
396
- if (max(deltaX, deltaY) > pagerGestureTouchSlop) {
1874
+ if (!directionResolved && max(deltaX, deltaY) > pagerGestureTouchSlop) {
397
1875
  directionResolved = true
398
1876
  pagerGestureIsVertical = deltaY >= deltaX
399
1877
  recyclerView.parent?.requestDisallowInterceptTouchEvent(pagerGestureIsVertical)
400
- if (
401
- pagerGestureIsVertical &&
402
- keyboardDismissMode == NativeListKeyboardDismissMode.ON_DRAG
403
- ) {
1878
+ } else if (!pagerGestureIsVertical && deltaY > pagerGestureTouchSlop && deltaY >= deltaX) {
1879
+ pagerGestureIsVertical = true
1880
+ recyclerView.parent?.requestDisallowInterceptTouchEvent(true)
1881
+ }
1882
+ if (pagerGestureIsVertical && !pagerNativeGestureStarted) {
1883
+ NativeGestureUtil.notifyNativeGestureStarted(this@NativeListView, event)
1884
+ pagerNativeGestureStarted = true
1885
+ if (keyboardDismissMode == NativeListKeyboardDismissMode.ON_DRAG) {
404
1886
  dismissKeyboard()
405
1887
  }
406
1888
  }
407
1889
  }
408
1890
  MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
409
- recyclerView.parent?.requestDisallowInterceptTouchEvent(false)
410
- pagerGestureIsVertical = false
1891
+ finishPagerNativeGesture(event)
411
1892
  }
412
1893
  }
413
1894
  return false
414
1895
  }
415
1896
  }
1897
+
1898
+ private fun finishPagerNativeGesture(event: MotionEvent) {
1899
+ if (pagerNativeGestureStarted) {
1900
+ NativeGestureUtil.notifyNativeGestureEnded(this, event)
1901
+ pagerNativeGestureStarted = false
1902
+ }
1903
+ recyclerView.parent?.requestDisallowInterceptTouchEvent(false)
1904
+ pagerGestureIsVertical = false
1905
+ }
416
1906
  // Intercept only a completed tap so RecyclerView keeps drag and reorder ownership.
417
1907
  private val keyboardTapTouchListener = object : RecyclerView.SimpleOnItemTouchListener() {
418
1908
  private var downX = 0f
@@ -473,7 +1963,10 @@ class NativeListView(
473
1963
  private var footerView: NativeListRowHost = NativeListRendererRegistry.create(reactContext, NativeListRendererKey.ACTION.ordinal, fonts)
474
1964
  private var footerRendererKey = NativeListRendererKey.ACTION
475
1965
  private val sectionIndexView = NativeListSectionIndexView(context, fonts)
476
- private val sectionIndexPreview = TextView(context)
1966
+ // RN touch targeting still visits invisible native children with retained bounds.
1967
+ private val sectionIndexPreview = object : TextView(context), ReactPointerEventsView {
1968
+ override val pointerEvents: PointerEvents = PointerEvents.NONE
1969
+ }
477
1970
  private var config: NativeListConfig? = null
478
1971
  private var usesSelectorSourceScale = false
479
1972
  private val stickyHeaderView = NativeListRendererRegistry.create(reactContext, NativeListRendererKey.SECTION_HEADER.ordinal, fonts)
@@ -527,6 +2020,39 @@ class NativeListView(
527
2020
  override fun onDetachedFromWindow() { down?.recycle(); down = null; super.onDetachedFromWindow() }
528
2021
  }
529
2022
  private val stickyPreDraw = android.view.ViewTreeObserver.OnPreDrawListener {
2023
+ if (!commitPreparingFooterFrame()) {
2024
+ if (pendingPreparingFooterFrame?.handoffOnly != true) schedulePreparingFooterFrame()
2025
+ return@OnPreDrawListener false
2026
+ }
2027
+ if (pendingStructuralTransition != null || structuralAnimator != null || structuralTail != null) {
2028
+ val measuredHeightPx = containerSlots.getOrNull(2)?.measuredHeight ?: 0
2029
+ if (measuredHeightPx > 0 && measuredHeightPx != structuralFooterObservedNativeHeightPx) {
2030
+ // React layout can change the footer's contents before its onLayout height reaches JS.
2031
+ val roundedDip = ceil(measuredHeightPx / density.toDouble())
2032
+ val naturalHeight = (roundedDip * density).roundToInt()
2033
+ if (structuralTail != null && config?.disclosure != null &&
2034
+ naturalHeight != footerNaturalHeightPx()) {
2035
+ structuralFooterObservedNativeHeightPx = measuredHeightPx
2036
+ acceptedFooterNaturalHeightPx = naturalHeight
2037
+ structuralFooterCompensatedHeightPx = null
2038
+ finishStructuralTail(interrupted = true)
2039
+ return@OnPreDrawListener false
2040
+ }
2041
+ if (structuralTail != null && structuralTailRowsInAdapterPx > 0 &&
2042
+ !structuralTailFinalizing) {
2043
+ enqueuePreparingFooterFrame(slotHeights.copyOf(), naturalHeight,
2044
+ observedNativeHeight = measuredHeightPx)
2045
+ if (pendingPreparingFooterFrame != null) return@OnPreDrawListener false
2046
+ } else {
2047
+ structuralFooterObservedNativeHeightPx = measuredHeightPx
2048
+ reconcileStructuralFooterHeight(naturalHeight)
2049
+ acceptedFooterNaturalHeightPx = naturalHeight
2050
+ if (structuralTail == null || structuralTailFinalizing) syncFooterPresentation()
2051
+ }
2052
+ }
2053
+ }
2054
+ if (structuralTail != null && !structuralTailFinalizing) layoutFooterPresentationHostNow()
2055
+ if (config?.disclosure != null) layoutExpandedContentHostNow()
530
2056
  updateStickyHeader()
531
2057
  finishScrollCommandIfSettled()
532
2058
  true
@@ -572,7 +2098,6 @@ class NativeListView(
572
2098
  private var dispatchingScrollRequest: ScrollRequest? = null
573
2099
  private var commandLayoutRequest: ScrollRequest? = null
574
2100
  private var commandAlignmentRequest: ScrollRequest? = null
575
- private var commandFinishDiagnosticReason: String? = null
576
2101
  private var readingIntentEpoch = 0L
577
2102
  private var pendingBodyStartEpoch: Long? = null
578
2103
  private val actionAnchorInstanceId = UUID.randomUUID().toString()
@@ -584,6 +2109,17 @@ class NativeListView(
584
2109
  private var lastMarketPaginationAnchorLogAtMs = 0L
585
2110
  private var disposed = false
586
2111
  private var resourcesDisposed = false
2112
+ private var acceptedKeyIndex: Map<String, Int>? = null
2113
+
2114
+ private fun acceptRowIndex(next: NativeListConfig, previous: NativeListConfig?) {
2115
+ if (previous != null && acceptedKeyIndex != null &&
2116
+ previous.generation == next.generation && previous.items.size == next.items.size &&
2117
+ previous.items.indices.all { index ->
2118
+ previous.items[index].key == next.items[index].key &&
2119
+ previous.items[index].type == next.items[index].type
2120
+ }) return
2121
+ acceptedKeyIndex = next.items.withIndex().associate { it.value.key to it.index }
2122
+ }
587
2123
 
588
2124
  init {
589
2125
  orientation = VERTICAL
@@ -595,18 +2131,20 @@ class NativeListView(
595
2131
  recyclerView.addItemDecoration(reorderPlaceholderDecoration)
596
2132
  // OneKey patch: full-width selector header backgrounds do not change row content insets.
597
2133
  recyclerView.addItemDecoration(SelectorBackgroundDecoration(adapter))
598
- recyclerView.addItemDecoration(ContainerSlotInsetDecoration { slotInsetPx })
599
- if (homeOffsetDiagnosticEnabled) layoutManager.onDiagnosticLayout = ::homeOffsetDiagnostic
2134
+ recyclerView.addItemDecoration(ContainerSlotInsetDecoration { slotInsetPx to slotRightInsetPx })
600
2135
  layoutManager.onBeforeDataLayout = {
601
2136
  if (pendingBodyStartEpoch == readingIntentEpoch && adapter.itemCount > 0 && pendingScrollRequest == null) {
602
2137
  layoutManager.scrollToPositionWithOffset(0, 0)
603
2138
  pendingBodyStartEpoch = null
604
- homeOffsetDiagnostic("first-fill-body-start")
605
2139
  }
2140
+ pendingStructuralTransition?.let(::alignPendingStructuralAnchor)
606
2141
  }
607
2142
  layoutManager.onChildLaidOut = ::recordLaidOutRowExtent
608
2143
  layoutManager.onLayoutPassCompleted = {
2144
+ if (structuralFooterHoldTop != null) updateStructuralFooterHoldPosition()
2145
+ else if (structuralAnimator != null) updateStructuralFooterVisualPosition()
609
2146
  emitScrollPositionThresholdIfNeeded(resync = true)
2147
+ updateSidecarPosition(resync = true)
610
2148
  if (containerSlotRelayoutPending) scheduleContainerSlotRelayout()
611
2149
  if (commandLayoutRequest === acceptedScrollRequest) commandLayoutRequest = null
612
2150
  finishScrollCommandIfSettled()
@@ -618,7 +2156,7 @@ class NativeListView(
618
2156
  val rowPosition = rowPositionForScroll(position)
619
2157
  if (rowPosition !in 0 until adapter.itemCount) return layoutManager.spanCount
620
2158
  val type = adapter.itemAt(rowPosition)?.type
621
- return if (type == "sectionHeader" || type == "system" || type == "action") {
2159
+ return if (type == "sectionHeader" || type == "system" || type == "action" || type == "buttonGroup") {
622
2160
  layoutManager.spanCount
623
2161
  } else {
624
2162
  1
@@ -636,17 +2174,12 @@ class NativeListView(
636
2174
  FrameLayout.LayoutParams.MATCH_PARENT,
637
2175
  ),
638
2176
  )
2177
+ contentContainer.addView(structuralTailLayer, FrameLayout.LayoutParams(0, 0, Gravity.TOP or Gravity.LEFT))
2178
+ contentContainer.addView(sidecarHost,
2179
+ FrameLayout.LayoutParams(0, 0, Gravity.TOP or Gravity.RIGHT))
639
2180
  stickyHeaderHost.visibility = GONE
640
2181
  stickyHeaderHost.addView(stickyHeaderView, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT))
641
2182
  contentContainer.addView(stickyHeaderHost, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.TOP))
642
- contentContainer.addView(
643
- sectionIndexView,
644
- FrameLayout.LayoutParams(
645
- sectionIndexDp(SECTION_INDEX_RAIL_WIDTH_DP),
646
- FrameLayout.LayoutParams.MATCH_PARENT,
647
- Gravity.END,
648
- ),
649
- )
650
2183
  sectionIndexPreview.apply {
651
2184
  gravity = Gravity.CENTER
652
2185
  textSize = 30f
@@ -656,16 +2189,13 @@ class NativeListView(
656
2189
  alpha = 0f
657
2190
  importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
658
2191
  }
659
- contentContainer.addView(
660
- sectionIndexPreview,
661
- FrameLayout.LayoutParams(
662
- sectionIndexDp(SECTION_INDEX_PREVIEW_WIDTH_DP),
663
- sectionIndexDp(SECTION_INDEX_PREVIEW_HEIGHT_DP),
664
- Gravity.CENTER_VERTICAL or Gravity.END,
665
- ).apply {
666
- marginEnd = sectionIndexDp(SECTION_INDEX_PREVIEW_END_MARGIN_DP)
667
- },
668
- )
2192
+ sectionIndexPreview.layoutParams = FrameLayout.LayoutParams(
2193
+ sectionIndexDp(SECTION_INDEX_PREVIEW_WIDTH_DP),
2194
+ sectionIndexDp(SECTION_INDEX_PREVIEW_HEIGHT_DP),
2195
+ Gravity.CENTER_VERTICAL or Gravity.END,
2196
+ ).apply {
2197
+ marginEnd = sectionIndexDp(SECTION_INDEX_PREVIEW_END_MARGIN_DP)
2198
+ }
669
2199
  addView(contentContainer, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
670
2200
  footerView.visibility = GONE
671
2201
  addView(footerView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
@@ -700,6 +2230,9 @@ class NativeListView(
700
2230
  recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
701
2231
  override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
702
2232
  if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
2233
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
2234
+ if (structuralAnimator != null || pendingStructuralTransition != null)
2235
+ structuralScrollInterrupted = true
703
2236
  cancelExecutingScrollCommand()
704
2237
  readingIntentEpoch++
705
2238
  pendingBodyStartEpoch = null
@@ -724,6 +2257,21 @@ class NativeListView(
724
2257
 
725
2258
  override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
726
2259
  logicalScrollDistancePx = (logicalScrollDistancePx + dy).coerceAtLeast(0)
2260
+ if (structuralScrollInterrupted && dy != 0) {
2261
+ if (pendingStructuralTransition != null) {
2262
+ pendingStructuralTransition = pendingStructuralTransition?.let {
2263
+ it.copy(footerStartTop = it.footerStartTop?.minus(dy))
2264
+ }
2265
+ structuralFooterHoldTop = structuralFooterHoldTop?.minus(dy)
2266
+ updateStructuralFooterHoldPosition()
2267
+ } else if (structuralAnimator != null) {
2268
+ structuralFooterVisualStartTop = structuralFooterVisualStartTop?.minus(dy)
2269
+ structuralFooterVisualEndTop = structuralFooterVisualEndTop?.minus(dy)
2270
+ updateStructuralFooterVisualPosition()
2271
+ }
2272
+ }
2273
+ updateSidecarPosition()
2274
+ if (structuralTail != null) updateStructuralTailWindow()
727
2275
  emitScrollPositionThresholdIfNeeded(resync = dx == 0 && dy == 0)
728
2276
  if (dx != 0 || dy != 0) invalidateActionAnchor("scroll")
729
2277
  syncSectionIndexToVisibleRows()
@@ -781,6 +2329,11 @@ class NativeListView(
781
2329
  }
782
2330
  val nextWidth = right - left
783
2331
  val nextHeight = bottom - top
2332
+ val widthChanged = lastLayoutWidth != nextWidth
2333
+ val directionChanged = layoutDirection != lastLayoutDirection
2334
+ if (structuralTail != null && lastLayoutWidth >= 0 &&
2335
+ (widthChanged || lastLayoutHeight != nextHeight || directionChanged))
2336
+ finishStructuralTail(interrupted = true)
784
2337
  if (
785
2338
  lastLayoutWidth >= 0 &&
786
2339
  (nextWidth != lastLayoutWidth || nextHeight != lastLayoutHeight || layoutDirection != lastLayoutDirection)
@@ -790,6 +2343,9 @@ class NativeListView(
790
2343
  lastLayoutWidth = nextWidth
791
2344
  lastLayoutHeight = nextHeight
792
2345
  lastLayoutDirection = layoutDirection
2346
+ if ((widthChanged || directionChanged) && sidecarLayout != null) config?.let(::updateLayout)
2347
+ updateSidecarGeometry()
2348
+ scheduleSidecarSpacer()
793
2349
  updateSectionIndexAttachment()
794
2350
  performPendingScrollIfNeeded()
795
2351
  }
@@ -821,6 +2377,27 @@ class NativeListView(
821
2377
  }
822
2378
 
823
2379
  override fun onDetachedFromWindow() {
2380
+ val disclosureId = activeDisclosureTransitionId
2381
+ if (structuralTail != null) {
2382
+ discardStructuralTail()
2383
+ val epoch = structuralTransitionEpoch
2384
+ config?.let { accepted ->
2385
+ adapter.submitList(accepted.items) {
2386
+ if (!disposed && epoch == structuralTransitionEpoch &&
2387
+ activeDisclosureTransitionId == disclosureId && disclosureId != null) {
2388
+ disclosureFraction = if (accepted.disclosure?.expanded == true) 1f else 0f
2389
+ disclosureTransitioning = false
2390
+ syncDisclosurePresentation()
2391
+ settleDisclosureCommand("interrupted")
2392
+ }
2393
+ }
2394
+ }
2395
+ } else if (disclosureId != null && !disposed) {
2396
+ disclosureFraction = if (config?.disclosure?.expanded == true) 1f else 0f
2397
+ disclosureTransitioning = false
2398
+ syncDisclosurePresentation()
2399
+ settleDisclosureCommand("interrupted")
2400
+ }
824
2401
  val cancelTag = R.id.onekey_native_scroll_coordinator_command_cancel_listener
825
2402
  if (recyclerView.getTag(cancelTag) === coordinatorCommandCancelListener) recyclerView.setTag(cancelTag, null)
826
2403
  cancelExecutingScrollCommand()
@@ -841,9 +2418,94 @@ class NativeListView(
841
2418
  } catch (_: Exception) {
842
2419
  return
843
2420
  }
844
- homeOffsetDiagnostic("snapshot-before-nextCount=${next.items.size}")
845
2421
  invalidateActionAnchor("snapshot")
846
2422
  val previous = config
2423
+ val transition = next.structuralTransition
2424
+ val isNewTransition = transition != null && transition.id != consumedStructuralTransitionId
2425
+ if (transition != null) consumedStructuralTransitionId = transition.id
2426
+ val disclosureGeometryInvalid = batchedDisclosureGeometryInvalid ||
2427
+ (!isNewTransition && structuralTail != null &&
2428
+ previous?.disclosure != next.disclosure)
2429
+ batchedDisclosureGeometryInvalid = false
2430
+ if (!isNewTransition &&
2431
+ (next.disclosure == null || previous?.disclosure?.expanded != next.disclosure.expanded)) {
2432
+ activeDisclosureTransitionId = null
2433
+ directDisclosureTogglePositionPending = false
2434
+ }
2435
+ val oldKeys = previous?.items?.map { it.key } ?: emptyList()
2436
+ val nextKeys = next.items.map { it.key }
2437
+ if (next.disclosure != null && isNewTransition && previous != null) {
2438
+ activeDisclosureTransitionId = transition?.id
2439
+ directDisclosureStatus = if (oldKeys == nextKeys || nextKeys.isEmpty() ||
2440
+ transition?.durationMs == 0L ||
2441
+ (Build.VERSION.SDK_INT >= 26 && !ValueAnimator.areAnimatorsEnabled()))
2442
+ "completed" else "interrupted"
2443
+ directDisclosureTogglePositionPending = !next.disclosure.expanded &&
2444
+ !disclosureGeometryInvalid && directDisclosureStatus == "completed"
2445
+ } else if (next.disclosure == null) {
2446
+ activeDisclosureTransitionId = null
2447
+ directDisclosureTogglePositionPending = false
2448
+ }
2449
+ if (disclosureGeometryInvalid && activeDisclosureTransitionId != null) {
2450
+ directDisclosureStatus = "interrupted"
2451
+ directDisclosureTogglePositionPending = false
2452
+ }
2453
+ val positionDirectCollapse = directDisclosureTogglePositionPending
2454
+ var animateStructure = !disclosureGeometryInvalid && previous != null &&
2455
+ isNewTransition && oldKeys != nextKeys &&
2456
+ previous.orientation == "vertical" &&
2457
+ (previous.layout == "linear" || previous.layout == "table") &&
2458
+ next.orientation == "vertical" && (next.layout == "linear" || next.layout == "table") &&
2459
+ (transition?.durationMs ?: 0) > 0 &&
2460
+ (if (Build.VERSION.SDK_INT >= 26) ValueAnimator.areAnimatorsEnabled() else
2461
+ android.provider.Settings.Global.getFloat(context.contentResolver, "animator_duration_scale", 1f) > 0f)
2462
+ val prefixCount = if (animateStructure && previous != null && recyclerView.width > 0 &&
2463
+ recyclerView.height > 0) prefixTailCount(previous, next) else null
2464
+ val exceedsTailHostLimit = prefixCount != null && previous != null &&
2465
+ exceedsStructuralTailHostLimit(previous, next, prefixCount)
2466
+ if (exceedsTailHostLimit) animateStructure = false
2467
+ if (next.disclosure != null && prefixCount == null) animateStructure = false
2468
+ if (prefixCount != null && !exceedsTailHostLimit && previous != null && transition != null) {
2469
+ startPrefixTailTransition(previous, next, transition, prefixCount)
2470
+ return
2471
+ }
2472
+ var heldTailEpoch: Int? = null
2473
+ if (structuralTail != null) {
2474
+ if (!disclosureGeometryInvalid && !animateStructure && oldKeys == nextKeys &&
2475
+ (Build.VERSION.SDK_INT < 26 || ValueAnimator.areAnimatorsEnabled()) &&
2476
+ previous != null && updatePrefixTailSnapshot(previous, next, acceptIndex = true)) {
2477
+ return
2478
+ }
2479
+ heldTailEpoch = holdStructuralTailUntilListCommit()
2480
+ // Keep the accepted presentation until the full adapter list has committed.
2481
+ animateStructure = false
2482
+ }
2483
+ val nextKeySet = nextKeys.toHashSet()
2484
+ val visibleAnchor = if (animateStructure) {
2485
+ val first = layoutManager.findFirstVisibleItemPosition()
2486
+ val last = layoutManager.findLastVisibleItemPosition()
2487
+ (first..last).firstNotNullOfOrNull { position ->
2488
+ val rowIndex = rowPositionForScroll(position)
2489
+ oldKeys.getOrNull(rowIndex)?.takeIf(nextKeySet::contains)?.let { key ->
2490
+ layoutManager.findViewByPosition(position)?.let { key to layoutManager.getDecoratedTop(it) }
2491
+ }
2492
+ }
2493
+ } else null
2494
+ val anchorKey = visibleAnchor?.first ?: transition?.anchorKey?.takeIf(nextKeySet::contains)
2495
+ val anchorTop = visibleAnchor?.second
2496
+ val footerStartTop = if (animateStructure && footerSlotAdapter.itemCount > 0) {
2497
+ layoutManager.findViewByPosition(scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount)?.let {
2498
+ layoutManager.getDecoratedTop(it) + it.translationY.roundToInt()
2499
+ }
2500
+ } else null
2501
+ val oldKeySet = oldKeys.toHashSet()
2502
+ val removedExtent = if (animateStructure) previous?.items?.sumOf { item ->
2503
+ if (nextKeySet.contains(item.key)) 0 else estimatedItemExtentPx(item)
2504
+ } ?: 0 else 0
2505
+ val addedExtent = if (animateStructure) next.items.sumOf { item ->
2506
+ if (oldKeySet.contains(item.key)) 0 else estimatedItemExtentPx(item)
2507
+ } else 0
2508
+ if (!animateStructure && oldKeys != nextKeys && heldTailEpoch == null) cancelStructuralTransition()
847
2509
  if (previous?.items?.isEmpty() == true && next.items.isNotEmpty() && adapter.itemCount == 0 &&
848
2510
  pendingScrollRequest == null && recyclerView.scrollState != RecyclerView.SCROLL_STATE_DRAGGING &&
849
2511
  !recyclerView.canScrollVertically(-1) && layoutManager.findFirstVisibleItemPosition() == 0) {
@@ -866,7 +2528,12 @@ class NativeListView(
866
2528
  previous.items[index].content != next.items[index].content
867
2529
  }
868
2530
  }.toSet()
2531
+ acceptRowIndex(next, previous)
869
2532
  config = next
2533
+ if (heldTailEpoch == null) {
2534
+ disclosureFraction = if (next.disclosure?.expanded == true) 1f else 0f
2535
+ disclosureTransitioning = false
2536
+ }
870
2537
  updateContainerSlots()
871
2538
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
872
2539
  adapter.usesSelectorSourceScale = usesSelectorSourceScale
@@ -878,15 +2545,23 @@ class NativeListView(
878
2545
  // Rows rebind through the adapter's listStyle invalidation; the fixed footer is bound
879
2546
  // outside the adapter, so a listStyle-only snapshot must rebind it here.
880
2547
  if (previous.listStyle?.toString() != next.listStyle?.toString()) bindFooter(next)
2548
+ val directDisclosureId = activeDisclosureTransitionId
881
2549
  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()
2550
+ val committed: () -> Unit = {
2551
+ // OneKey patch: DiffUtil has dispatched its payloads; release the old serialized rows.
2552
+ next.items.forEach { it.selectionUpdateFromContent = null }
2553
+ recyclerView.post {
2554
+ scheduleSidecarSpacer()
2555
+ startPendingStructuralTransition()
2556
+ bindVisibleSelection(changedSummaryKeys)
2557
+ bindFooterSelection()
2558
+ performPendingScrollIfNeeded()
2559
+ settleCommittedDirectDisclosure(next, directDisclosureId, heldTailEpoch == null)
2560
+ }
889
2561
  }
2562
+ if (heldTailEpoch != null) completeHeldTailCommit(next, heldTailEpoch, committed,
2563
+ positionDirectCollapse)
2564
+ else committed()
890
2565
  }
891
2566
  return
892
2567
  }
@@ -905,7 +2580,12 @@ class NativeListView(
905
2580
  layoutManager.getDecoratedTop(it) - recyclerView.paddingTop
906
2581
  }
907
2582
  } else null
2583
+ acceptRowIndex(next, previous)
908
2584
  config = next
2585
+ if (heldTailEpoch == null) {
2586
+ disclosureFraction = if (next.disclosure?.expanded == true) 1f else 0f
2587
+ disclosureTransitioning = false
2588
+ }
909
2589
  pruneMeasuredRowExtents(next.items)
910
2590
  updateContainerSlots()
911
2591
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
@@ -919,16 +2599,52 @@ class NativeListView(
919
2599
  adapter.selectedKeys = next.selectedKeys
920
2600
  configureSectionIndex(next)
921
2601
  updateLayout(next)
2602
+ if (animateStructure && transition != null) {
2603
+ structuralTransitionEpoch += 1
2604
+ pendingStructuralStartScheduled = false
2605
+ structuralAnimator?.cancel()
2606
+ structuralAnimator = null
2607
+ structuralScrollInterrupted = false
2608
+ structuralFooterHoldTop = footerStartTop
2609
+ structuralFooterCompensatedHeightPx = slotHeights[2]
2610
+ val held = (structuralSpacerHeightPx + removedExtent - addedExtent).coerceAtLeast(0)
2611
+ pendingStructuralTransition = PendingStructuralTransition(
2612
+ transition, structuralTransitionEpoch, anchorKey, anchorTop, footerStartTop, held,
2613
+ removedExtent > addedExtent,
2614
+ )
2615
+ recyclerView.itemAnimator = DefaultItemAnimator().apply {
2616
+ addDuration = transition.durationMs
2617
+ removeDuration = transition.durationMs
2618
+ moveDuration = 0
2619
+ changeDuration = 0
2620
+ supportsChangeAnimations = false
2621
+ }
2622
+ }
2623
+ val directDisclosureId = activeDisclosureTransitionId
922
2624
  adapter.submitList(next.items) {
923
- homeOffsetDiagnostic("snapshot-submit-commit-marketAnchor=${marketStartOffset != null}")
924
- if (marketStartOffset != null) {
925
- layoutManager.scrollToPositionWithOffset(scrollPositionForRow(0), marketStartOffset)
2625
+ val committed: () -> Unit = {
2626
+ pendingStructuralTransition?.takeIf { it.epoch == structuralTransitionEpoch }?.let {
2627
+ setStructuralSpacerHeight(it.heldHeightPx)
2628
+ pendingStructuralTransition = it.copy(spacerInserted = true)
2629
+ pendingStructuralTransition?.let(::alignPendingStructuralAnchor)
2630
+ }
2631
+ if (marketStartOffset != null) {
2632
+ layoutManager.scrollToPositionWithOffset(scrollPositionForRow(0), marketStartOffset)
2633
+ }
2634
+ relayoutContents(preserveMarketPaginationAnchor)
2635
+ scheduleSidecarSpacer()
2636
+ startPendingStructuralTransition()
2637
+ performPendingScrollIfNeeded()
2638
+ syncSectionIndexToVisibleRows()
2639
+ scheduleVisibleEvent()
2640
+ if (next.items.isNotEmpty()) checkEndReached()
2641
+ if (directDisclosureId != null) recyclerView.post {
2642
+ settleCommittedDirectDisclosure(next, directDisclosureId, heldTailEpoch == null)
2643
+ }
926
2644
  }
927
- relayoutContents(preserveMarketPaginationAnchor)
928
- performPendingScrollIfNeeded()
929
- syncSectionIndexToVisibleRows()
930
- scheduleVisibleEvent()
931
- if (next.items.isNotEmpty()) checkEndReached()
2645
+ if (heldTailEpoch != null) completeHeldTailCommit(next, heldTailEpoch, committed,
2646
+ positionDirectCollapse)
2647
+ else committed()
932
2648
  }
933
2649
  refreshLayout.isEnabled = next.pullToRefresh
934
2650
  refreshLayout.setDistanceToTriggerSync(next.refreshTriggerDistance?.let { (it * density).roundToInt() } ?: defaultRefreshTriggerDistancePx)
@@ -937,6 +2653,85 @@ class NativeListView(
937
2653
  updateReordering(next)
938
2654
  }
939
2655
 
2656
+ private fun startStructuralTransition(
2657
+ transition: NativeListConfig.StructuralTransition,
2658
+ epoch: Int,
2659
+ anchorKey: String?,
2660
+ anchorTop: Int?,
2661
+ footerStartTop: Int?,
2662
+ ) {
2663
+ structuralFooterHoldTop = null
2664
+ val startSpacer = structuralSpacerHeightPx
2665
+ structuralStartSpacerPx = startSpacer
2666
+ structuralFooterVisualStartTop = footerStartTop
2667
+ structuralFooterVisualProgress = 0f
2668
+ val startOffset = measuredScrollDistancePx()?.also { logicalScrollDistancePx = it }
2669
+ ?: logicalScrollDistancePx
2670
+ val anchorIndex = anchorKey?.let { key -> adapter.currentList.indexOfFirst { it.key == key } }
2671
+ val currentAnchorTop = anchorIndex?.takeIf { it >= 0 }?.let { index ->
2672
+ layoutManager.findViewByPosition(scrollPositionForRow(index))?.let(layoutManager::getDecoratedTop)
2673
+ }
2674
+ val anchorDelta = if (anchorTop != null && currentAnchorTop != null) currentAnchorTop - anchorTop else 0
2675
+ val leftFinal = (sidecarLeftExtentPx() - startSpacer).coerceAtLeast(0)
2676
+ val sidecarBottom = if (sidecarLayout != null)
2677
+ recyclerView.paddingTop + slotHeights[3] + recyclerView.paddingBottom else 0
2678
+ val finalMax = (max(leftFinal, sidecarBottom) - recyclerView.height).coerceAtLeast(0)
2679
+ var targetOffset = (startOffset + anchorDelta).coerceIn(0, finalMax)
2680
+ if (anchorTop == null && anchorIndex != null && anchorIndex >= 0) {
2681
+ val fallbackTop = nativeListScrollPrefixPx(
2682
+ scrollPositionForRow(anchorIndex),
2683
+ layoutManager.spanCount,
2684
+ layoutManager.spanSizeLookup::getSpanSize,
2685
+ ::estimatedScrollExtentPx,
2686
+ ).coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
2687
+ targetOffset = minOf(targetOffset, fallbackTop)
2688
+ }
2689
+ structuralFooterVisualEndTop = if (footerStartTop != null && footerSlotAdapter.itemCount > 0) {
2690
+ val footerPosition = scrollContentAdapter.itemCount - 1 - sidecarSpacerAdapter.itemCount
2691
+ val finalPrefix = nativeListScrollPrefixPx(
2692
+ footerPosition,
2693
+ layoutManager.spanCount,
2694
+ layoutManager.spanSizeLookup::getSpanSize,
2695
+ ::estimatedScrollExtentPx,
2696
+ ) - startSpacer
2697
+ (finalPrefix + recyclerView.paddingTop - targetOffset)
2698
+ .coerceIn(Int.MIN_VALUE.toLong(), Int.MAX_VALUE.toLong()).toInt()
2699
+ } else null
2700
+ structuralAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
2701
+ duration = transition.durationMs
2702
+ interpolator = android.view.animation.AccelerateDecelerateInterpolator()
2703
+ addUpdateListener { animation ->
2704
+ if (epoch != structuralTransitionEpoch || disposed) return@addUpdateListener
2705
+ val fraction = animation.animatedValue as Float
2706
+ structuralFooterVisualProgress = fraction
2707
+ setStructuralSpacerHeight((structuralStartSpacerPx * (1f - fraction)).roundToInt())
2708
+ measuredScrollDistancePx()?.let { logicalScrollDistancePx = it }
2709
+ val finalLeftExtent = (sidecarLeftExtentPx() - structuralSpacerHeightPx).coerceAtLeast(0)
2710
+ val finalMaximum = (max(finalLeftExtent, sidecarBottom) - recyclerView.height).coerceAtLeast(0)
2711
+ val desired = (startOffset + (minOf(targetOffset, finalMaximum) - startOffset) * fraction).roundToInt()
2712
+ if (!structuralScrollInterrupted && recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE)
2713
+ recyclerView.scrollBy(0, desired - logicalScrollDistancePx)
2714
+ updateStructuralFooterVisualPosition()
2715
+ }
2716
+ addListener(object : AnimatorListenerAdapter() {
2717
+ override fun onAnimationEnd(animation: Animator) {
2718
+ if (epoch != structuralTransitionEpoch) return
2719
+ structuralAnimator = null
2720
+ recyclerView.itemAnimator = null
2721
+ setStructuralSpacerHeight(0)
2722
+ scheduleSidecarSpacer()
2723
+ footerSlotAdapter.setVisualTranslationY(0f)
2724
+ structuralFooterVisualStartTop = null
2725
+ structuralFooterVisualEndTop = null
2726
+ structuralFooterVisualProgress = 0f
2727
+ structuralFooterCompensatedHeightPx = null
2728
+ structuralStartSpacerPx = 0
2729
+ }
2730
+ })
2731
+ start()
2732
+ }
2733
+ }
2734
+
940
2735
  private fun captureVisibleMarketAnchor(): VisibleMarketAnchor? {
941
2736
  val position = rowPositionForScroll(layoutManager.findFirstVisibleItemPosition()).coerceAtLeast(0)
942
2737
  if (position == RecyclerView.NO_POSITION) return null
@@ -1111,20 +2906,22 @@ class NativeListView(
1111
2906
 
1112
2907
  fun applyPatches(patchesJson: String) {
1113
2908
  val current = config ?: return
2909
+ val indexByKey = acceptedKeyIndex ?: return
1114
2910
  val patches = try {
1115
2911
  JSONArray(patchesJson)
1116
2912
  } catch (_: Exception) {
1117
2913
  return
1118
2914
  }
1119
- val indexByKey = current.items.withIndex().associate { it.value.key to it.index }
1120
2915
  val pending = ArrayList<Pair<Int, JSONObject>>(patches.length())
1121
2916
  val seen = HashSet<String>()
1122
2917
  for (index in 0 until patches.length()) {
1123
2918
  val patch = patches.optJSONObject(index) ?: return
1124
2919
  val key = patch.optString("key")
1125
2920
  val itemIndex = indexByKey[key] ?: return
2921
+ val item = current.items.getOrNull(itemIndex) ?: return
2922
+ if (item.key != key) return
1126
2923
  if (!seen.add(key)) return
1127
- if (patch.optString("type") != current.items[itemIndex].type) return
2924
+ if (patch.optString("type") != item.type) return
1128
2925
  val changes = patch.optJSONObject("changes") ?: return
1129
2926
  pending.add(itemIndex to changes)
1130
2927
  }
@@ -1138,6 +2935,7 @@ class NativeListView(
1138
2935
  previous.type == "market" &&
1139
2936
  changes.keys().asSequence().all(MARKET_QUOTE_FIELDS::contains)
1140
2937
  val merged = NativeListItem.parse(mergeRow(previous.json, changes))
2938
+ marketQuoteOnly = marketQuoteOnly && hasSameMarketMetricStructure(previous, merged)
1141
2939
  nextItems[index] = merged
1142
2940
  if (changes.has("selected")) {
1143
2941
  if (changes.optBoolean("selected")) selected.add(merged.key) else selected.remove(merged.key)
@@ -1148,12 +2946,27 @@ class NativeListView(
1148
2946
  }
1149
2947
  if (!marketQuoteOnly) invalidateActionAnchor("snapshot")
1150
2948
  val next = current.copy(items = nextItems, selectedKeys = selected)
2949
+ if (structuralTail != null && updatePrefixTailSnapshot(current, next)) return
2950
+ val heldTailEpoch = if (structuralTail != null) holdStructuralTailUntilListCommit() else null
1151
2951
  config = next
1152
2952
  updateContainerSlots()
1153
2953
  usesSelectorSourceScale = next.items.any { it.usesSelectorSourceScale }
1154
2954
  adapter.usesSelectorSourceScale = usesSelectorSourceScale
1155
2955
  adapter.selectedKeys = selected
1156
- adapter.submitList(nextItems) { relayoutContents() }
2956
+ val directDisclosureId = activeDisclosureTransitionId
2957
+ adapter.submitList(nextItems) {
2958
+ if (heldTailEpoch != null) {
2959
+ if (heldTailEpoch != structuralTransitionEpoch || disposed) return@submitList
2960
+ val acceptedPendingFooter = acceptPendingFooterValues(adjustTailStart = false)
2961
+ clearStructuralTail()
2962
+ if (acceptedPendingFooter) updateContainerSlots()
2963
+ setStructuralSpacerHeight(0)
2964
+ }
2965
+ relayoutContents()
2966
+ if (directDisclosureId != null) recyclerView.post {
2967
+ settleCommittedDirectDisclosure(next, directDisclosureId, heldTailEpoch == null)
2968
+ }
2969
+ }
1157
2970
  bindFooter(next)
1158
2971
  }
1159
2972
 
@@ -1215,12 +3028,12 @@ class NativeListView(
1215
3028
  is ScrollRequest.End -> true
1216
3029
  }
1217
3030
  if (!valid) return
3031
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
1218
3032
  executingScrollCommand = false
1219
3033
  dispatchingScrollRequest = null
1220
3034
  commandLayoutRequest = null
1221
3035
  commandAlignmentRequest = null
1222
3036
  acceptedScrollRequest = request
1223
- commandFinishDiagnosticReason = null
1224
3037
  readingIntentEpoch++
1225
3038
  pendingBodyStartEpoch = null
1226
3039
  val explicitTop = when (request) {
@@ -1240,6 +3053,7 @@ class NativeListView(
1240
3053
 
1241
3054
  private val coordinatorCommandCancelListener = Runnable {
1242
3055
  if (disposed) return@Runnable
3056
+ if (structuralTail != null) finishStructuralTail(interrupted = true)
1243
3057
  pendingScrollRequest = null
1244
3058
  readingIntentEpoch++
1245
3059
  pendingBodyStartEpoch = null
@@ -1261,15 +3075,6 @@ class NativeListView(
1261
3075
 
1262
3076
  private fun finishScrollCommandIfSettled() {
1263
3077
  val request = acceptedScrollRequest ?: return
1264
- if (homeOffsetDiagnosticEnabled && executingScrollCommand) {
1265
- val reason = "pendingOwn=${pendingScrollRequest === request}-dispatchOwn=${dispatchingScrollRequest === request}" +
1266
- "-layoutOwn=${commandLayoutRequest === request}-alignOwn=${commandAlignmentRequest === request}" +
1267
- "-computing=${recyclerView.isComputingLayout}-scrollState=${recyclerView.scrollState}-smooth=${layoutManager.isSmoothScrolling}"
1268
- if (commandFinishDiagnosticReason != reason) {
1269
- commandFinishDiagnosticReason = reason
1270
- homeOffsetDiagnostic("command-finish-gates-$reason")
1271
- }
1272
- }
1273
3078
  if (
1274
3079
  !executingScrollCommand || pendingScrollRequest === request ||
1275
3080
  dispatchingScrollRequest === request || commandLayoutRequest === request ||
@@ -1285,7 +3090,6 @@ class NativeListView(
1285
3090
  private fun requestScroll(request: ScrollRequest) {
1286
3091
  acceptScrollRequest(request)
1287
3092
  if (config != null && acceptedScrollRequest !== request) return
1288
- homeOffsetDiagnostic("command-request-kind=${request.javaClass.simpleName}")
1289
3093
  if (performScroll(request)) {
1290
3094
  pendingScrollRequest = null
1291
3095
  finishScrollCommandIfSettled()
@@ -1301,7 +3105,6 @@ class NativeListView(
1301
3105
  if (pendingScrollRequest === request) pendingScrollRequest = null
1302
3106
  return
1303
3107
  }
1304
- homeOffsetDiagnostic("command-pending-kind=${request.javaClass.simpleName}")
1305
3108
  if (performScroll(request)) {
1306
3109
  pendingScrollRequest = null
1307
3110
  finishScrollCommandIfSettled()
@@ -1309,7 +3112,6 @@ class NativeListView(
1309
3112
  }
1310
3113
 
1311
3114
  private fun performScroll(request: ScrollRequest): Boolean {
1312
- homeOffsetDiagnostic("command-perform-kind=${request.javaClass.simpleName}")
1313
3115
  val current = config ?: return false
1314
3116
  if (adapter.itemCount != current.items.size) return false
1315
3117
  if (recyclerView.width <= 0 || recyclerView.height <= 0) return false
@@ -1353,7 +3155,8 @@ class NativeListView(
1353
3155
  }
1354
3156
  is ScrollRequest.End -> {
1355
3157
  val finalSlotHeight = when {
1356
- footerSlotAdapter.itemCount > 0 -> slotHeights[2]
3158
+ sidecarSpacerAdapter.itemCount > 0 -> sidecarSpacerHeightPx
3159
+ footerSlotAdapter.itemCount > 0 -> footerPresentedHeightPx()
1357
3160
  emptySlotAdapter.itemCount > 0 -> slotHeights[1]
1358
3161
  adapter.itemCount == 0 && headerSlotAdapter.itemCount > 0 -> slotHeights[0]
1359
3162
  else -> null
@@ -1489,13 +3292,11 @@ class NativeListView(
1489
3292
  val startView = manager.findViewByPosition(0)
1490
3293
  val paddingStart = if (manager.orientation == RecyclerView.VERTICAL) manager.paddingTop else manager.paddingLeft
1491
3294
  val relativeStart = startView?.let { decoratedStart(manager, it) - paddingStart }
1492
- homeOffsetDiagnostic("command-top-dispatch-first=${manager.findFirstVisibleItemPosition()}-relativeStart=$relativeStart-smooth=${manager.isSmoothScrolling}")
1493
3295
  if (
1494
3296
  startView != null && manager.findFirstVisibleItemPosition() == 0 && relativeStart == 0 &&
1495
3297
  recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE &&
1496
3298
  !recyclerView.isComputingLayout && !manager.isSmoothScrolling
1497
3299
  ) {
1498
- homeOffsetDiagnostic("command-top-noop")
1499
3300
  return
1500
3301
  }
1501
3302
  recyclerView.smoothScrollToPosition(0)
@@ -1648,6 +3449,8 @@ class NativeListView(
1648
3449
  fun dispose() {
1649
3450
  if (disposed) return
1650
3451
  disposed = true
3452
+ acceptedKeyIndex = null
3453
+ if (structuralTail != null) discardStructuralTail()
1651
3454
  val cancelTag = R.id.onekey_native_scroll_coordinator_command_cancel_listener
1652
3455
  if (recyclerView.getTag(cancelTag) === coordinatorCommandCancelListener) recyclerView.setTag(cancelTag, null)
1653
3456
  containerSlotRelayoutPending = false
@@ -1658,6 +3461,8 @@ class NativeListView(
1658
3461
  private fun disposeResources() {
1659
3462
  if (resourcesDisposed) return
1660
3463
  resourcesDisposed = true
3464
+ cancelStructuralTransition()
3465
+ recyclerView.itemAnimator = null
1661
3466
  stopSectionIndexAttachmentTracking()
1662
3467
  scheduleSectionIndexAttachmentToList()
1663
3468
  stopReorderRelayoutLoop()
@@ -1667,7 +3472,6 @@ class NativeListView(
1667
3472
  visibleEventScheduled = false
1668
3473
  layoutManager.onChildLaidOut = null
1669
3474
  layoutManager.onLayoutPassCompleted = null
1670
- layoutManager.onDiagnosticLayout = null
1671
3475
  layoutManager.onBeforeDataLayout = null
1672
3476
  pendingBodyStartEpoch = null
1673
3477
  executingScrollCommand = false
@@ -1722,12 +3526,26 @@ class NativeListView(
1722
3526
  val coordinatorBottomPadding = (recyclerView.paddingBottom - configuredBottomPaddingPx).coerceAtLeast(0)
1723
3527
  // Slot roots are laid out by React at the unscaled JS inset, without the index gutter.
1724
3528
  slotInsetPx = (horizontalPadding * density).roundToInt()
3529
+ val sidecar = sidecarLayout
3530
+ val contentWidth = recyclerView.width
3531
+ if (sidecar != null && contentWidth > 0) {
3532
+ slotInsetPx = (contentWidth - minOf(contentWidth, sidecar.maxContentWidth)) / 2
3533
+ }
3534
+ val sidecarSpace = (sidecar?.width ?: 0) + (sidecar?.gap ?: 0)
3535
+ val baseSlotInset = slotInsetPx
3536
+ if (sidecar != null && layoutDirection == LAYOUT_DIRECTION_RTL) {
3537
+ slotInsetPx += sidecarSpace
3538
+ slotRightInsetPx = baseSlotInset
3539
+ } else {
3540
+ slotRightInsetPx = baseSlotInset + sidecarSpace
3541
+ }
1725
3542
  configuredTopPaddingPx = dp(topPadding)
1726
3543
  configuredBottomPaddingPx = dp(bottomPadding)
1727
3544
  recyclerView.setPaddingRelative(
1728
- dp(horizontalPadding),
3545
+ if (sidecar == null) dp(horizontalPadding) else baseSlotInset + dp(horizontalPadding),
1729
3546
  configuredTopPaddingPx + coordinatorTopPadding,
1730
- dp(horizontalPadding + indexGutter),
3547
+ if (sidecar == null) dp(horizontalPadding + indexGutter)
3548
+ else baseSlotInset + sidecarSpace + dp(horizontalPadding + indexGutter),
1731
3549
  configuredBottomPaddingPx + coordinatorBottomPadding,
1732
3550
  )
1733
3551
  recyclerView.clipToPadding = false
@@ -1878,6 +3696,18 @@ class NativeListView(
1878
3696
  }
1879
3697
 
1880
3698
  private fun updateSectionIndexAttachment() {
3699
+ if (sectionIndexEntries.isEmpty()) {
3700
+ stopSectionIndexAttachmentTracking()
3701
+ sectionIndexAttachmentHandler.removeCallbacks(sectionIndexListAttachmentRunnable)
3702
+ sectionIndexListAttachmentScheduled = false
3703
+ (sectionIndexView.parent as? ViewGroup)?.let { previous ->
3704
+ previous.removeView(sectionIndexView)
3705
+ previous.endViewTransition(sectionIndexView)
3706
+ }
3707
+ contentContainer.removeView(sectionIndexPreview)
3708
+ return
3709
+ }
3710
+ if (sectionIndexPreview.parent == null) contentContainer.addView(sectionIndexPreview)
1881
3711
  val windowHost = rootView as? FrameLayout
1882
3712
  val canUseWindowHost = config?.sectionIndexCenteredInWindow == true &&
1883
3713
  sectionIndexEntries.isNotEmpty() &&
@@ -1931,6 +3761,7 @@ class NativeListView(
1931
3761
  }
1932
3762
 
1933
3763
  private fun scheduleSectionIndexAttachmentToList() {
3764
+ if (sectionIndexEntries.isEmpty()) return
1934
3765
  if (sectionIndexView.parent === contentContainer) return
1935
3766
  if (sectionIndexListAttachmentScheduled) return
1936
3767
  sectionIndexListAttachmentScheduled = true
@@ -1938,8 +3769,12 @@ class NativeListView(
1938
3769
  }
1939
3770
 
1940
3771
  private fun attachSectionIndexToList() {
3772
+ if (sectionIndexEntries.isEmpty()) return
1941
3773
  if (sectionIndexView.parent === contentContainer) return
1942
- (sectionIndexView.parent as? ViewGroup)?.removeView(sectionIndexView)
3774
+ (sectionIndexView.parent as? ViewGroup)?.let { previous ->
3775
+ previous.removeView(sectionIndexView)
3776
+ previous.endViewTransition(sectionIndexView)
3777
+ }
1943
3778
  sectionIndexView.translationX = 0f
1944
3779
  contentContainer.addView(
1945
3780
  sectionIndexView,
@@ -1975,7 +3810,10 @@ class NativeListView(
1975
3810
  topMargin = (windowHost.height - railHeight) / 2
1976
3811
  }
1977
3812
  if (sectionIndexView.parent !== windowHost) {
1978
- (sectionIndexView.parent as? ViewGroup)?.removeView(sectionIndexView)
3813
+ (sectionIndexView.parent as? ViewGroup)?.let { previous ->
3814
+ previous.removeView(sectionIndexView)
3815
+ previous.endViewTransition(sectionIndexView)
3816
+ }
1979
3817
  windowHost.addView(sectionIndexView, layoutParams)
1980
3818
  sectionIndexView.bringToFront()
1981
3819
  } else if (!sectionIndexView.hasSameWindowLayout(layoutParams)) {
@@ -2111,15 +3949,16 @@ class NativeListView(
2111
3949
  actionAnchor = record
2112
3950
  // OneKey patch: selector menus anchor to the glyph slot, not its expanded press target.
2113
3951
  val anchorInset = origin.anchorInsetPixels
3952
+ val helpBounds = (origin.sourceView as? NativeListTextView)?.helpAnchorBounds
2114
3953
  return JSONObject()
2115
3954
  .put("token", token)
2116
3955
  .put(
2117
3956
  "windowRect",
2118
3957
  JSONObject()
2119
- .put("x", (location[0] + anchorInset) / density)
2120
- .put("y", (location[1] + anchorInset) / density)
2121
- .put("width", (origin.sourceView.width - anchorInset * 2) / density)
2122
- .put("height", (origin.sourceView.height - anchorInset * 2) / density),
3958
+ .put("x", (location[0] + (helpBounds?.left ?: anchorInset.toFloat())) / density)
3959
+ .put("y", (location[1] + (helpBounds?.top ?: anchorInset.toFloat())) / density)
3960
+ .put("width", (helpBounds?.width() ?: (origin.sourceView.width - anchorInset * 2).toFloat()) / density)
3961
+ .put("height", (helpBounds?.height() ?: (origin.sourceView.height - anchorInset * 2).toFloat()) / density),
2123
3962
  )
2124
3963
  .put("source", origin.source)
2125
3964
  .put("generation", generation)
@@ -2660,6 +4499,7 @@ class NativeListView(
2660
4499
  if (from != RecyclerView.NO_POSITION && to != RecyclerView.NO_POSITION && from != to && reordered != null) {
2661
4500
  val moved = reordered.getOrNull(to)
2662
4501
  if (moved != null) {
4502
+ acceptedKeyIndex = reordered.withIndex().associate { it.value.key to it.index }
2663
4503
  config = config?.copy(items = reordered)
2664
4504
  val payload = JSONObject()
2665
4505
  .put("key", moved.key)
@@ -2843,6 +4683,7 @@ class NativeListView(
2843
4683
  }
2844
4684
 
2845
4685
  private fun checkEndReached() {
4686
+ if (structuralTail != null) return
2846
4687
  val current = config ?: return
2847
4688
  if (!current.loadMore || current.generation == endReachedGeneration || adapter.itemCount == 0) return
2848
4689
  val manager = recyclerView.layoutManager as? LinearLayoutManager ?: return
@@ -3004,6 +4845,7 @@ class NativeListView(
3004
4845
  "priceSegments",
3005
4846
  "change",
3006
4847
  "accessibilityLabel",
4848
+ "metrics",
3007
4849
  )
3008
4850
  private const val SECTION_INDEX_CONTENT_INSET_DP = 16
3009
4851
  private const val SECTION_INDEX_RAIL_WIDTH_DP = 32
@@ -3348,7 +5190,7 @@ private class ItemSpacingDecoration(
3348
5190
  * from each edge. Row padding may be scaled or widened by the section-index gutter, so slot
3349
5191
  * holders offset themselves (possibly negatively) back to the JavaScript inset.
3350
5192
  */
3351
- private class ContainerSlotInsetDecoration(private val insetPx: () -> Int) : RecyclerView.ItemDecoration() {
5193
+ private class ContainerSlotInsetDecoration(private val insetsPx: () -> Pair<Int, Int>) : RecyclerView.ItemDecoration() {
3352
5194
  override fun getItemOffsets(
3353
5195
  outRect: android.graphics.Rect,
3354
5196
  view: View,
@@ -3356,9 +5198,9 @@ private class ContainerSlotInsetDecoration(private val insetPx: () -> Int) : Rec
3356
5198
  state: RecyclerView.State,
3357
5199
  ) {
3358
5200
  if (parent.getChildViewHolder(view) !is NativeListContainerSlotAdapter.Holder) return
3359
- val inset = insetPx()
3360
- outRect.left = inset - parent.paddingLeft
3361
- outRect.right = inset - parent.paddingRight
5201
+ val (leftInset, rightInset) = insetsPx()
5202
+ outRect.left = leftInset - parent.paddingLeft
5203
+ outRect.right = rightInset - parent.paddingRight
3362
5204
  }
3363
5205
  }
3364
5206