@onekeyfe/react-native-native-list 6.7.0-6 → 6.7.0-61

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 (216) 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 +50 -13
  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 +209 -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 +8 -3
  23. package/android/src/main/java/com/onekey/nativelist/NativeListSectionHeaderRenderer.kt +69 -0
  24. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +130 -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/NativeListDescriptionTouchPolicyTest.kt +153 -0
  28. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListIdentityTrailingAxisTest.kt +36 -0
  29. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingSlotFrameTest.kt +68 -0
  30. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingVisualClipPolicyTest.kt +44 -0
  31. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +10 -0
  32. package/docs/ROW_TEMPLATES.md +78 -14
  33. package/docs/SPEC.md +1318 -16
  34. package/docs/STYLE_SPEC.md +18 -0
  35. package/ios/HybridNativeList.swift +21 -2
  36. package/ios/NativeListAccessoryStack.swift +237 -51
  37. package/ios/NativeListActivityDetailsView.swift +43 -16
  38. package/ios/NativeListActivityRenderer.swift +8 -2
  39. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  40. package/ios/NativeListDataRowRenderer.swift +167 -30
  41. package/ios/NativeListDesignAssets.swift +13 -75
  42. package/ios/NativeListGeneratedIcons.swift +55 -0
  43. package/ios/NativeListIconBinding.swift +171 -0
  44. package/ios/NativeListIdentityRenderer.swift +256 -39
  45. package/ios/NativeListLeadingVisual.swift +127 -28
  46. package/ios/NativeListMarketRenderer.swift +120 -31
  47. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  48. package/ios/NativeListMediaPreviewSlot.swift +122 -61
  49. package/ios/NativeListMediaTileRenderer.swift +15 -11
  50. package/ios/NativeListMessageRenderer.swift +34 -1
  51. package/ios/NativeListMetricCardRenderer.swift +4 -2
  52. package/ios/NativeListModels.swift +42 -2
  53. package/ios/NativeListRendererRegistry.swift +1 -0
  54. package/ios/NativeListResolvedText.swift +17 -5
  55. package/ios/NativeListRowHost.swift +14 -0
  56. package/ios/NativeListSectionHeaderRenderer.swift +100 -4
  57. package/ios/NativeListTextLabel.swift +106 -0
  58. package/ios/RNCNativeListView.swift +1097 -60
  59. package/ios/tests/NativeListAccessoryStackTests.swift +101 -0
  60. package/ios/tests/NativeListAccountSelectorLayoutTests.swift +96 -0
  61. package/ios/tests/NativeListActivityPresentationTests.swift +423 -0
  62. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +81 -0
  63. package/ios/tests/NativeListLeadingVisualPairBackdropTests.swift +50 -0
  64. package/ios/tests/NativeListLifecycleTests.swift +2959 -4
  65. package/ios/tests/NativeListMarketMetricsTests.swift +117 -0
  66. package/ios/tests/NativeListMediaVisibilityTests.swift +41 -7
  67. package/ios/tests/NativeListSharedIconTests.swift +236 -0
  68. package/lib/module/NativeList.js +236 -38
  69. package/lib/module/NativeList.web.js +163 -45
  70. package/lib/module/index.js +1 -1
  71. package/lib/module/models.js +3 -0
  72. package/lib/module/selection.js +1 -1
  73. package/lib/module/validation.js +1263 -48
  74. package/lib/module/web/NativeListGeneratedIcons.js +31 -0
  75. package/lib/module/web/NativeListWebEngine.js +513 -275
  76. package/lib/module/web/templates/ActivityRowRenderer.js +41 -54
  77. package/lib/module/web/templates/ButtonGroupRowRenderer.js +47 -0
  78. package/lib/module/web/templates/DataRowRenderer.js +56 -5
  79. package/lib/module/web/templates/IdentityRowRenderer.js +161 -7
  80. package/lib/module/web/templates/MarketTableRowRenderer.js +36 -19
  81. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -25
  82. package/lib/module/web/templates/MessageRowRenderer.js +18 -2
  83. package/lib/module/web/templates/RowContainerStyle.js +1 -0
  84. package/lib/module/web/templates/RowRendererRegistry.js +3 -0
  85. package/lib/module/web/templates/SectionHeaderRowRenderer.js +36 -2
  86. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  87. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  88. package/lib/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  89. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  90. package/lib/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  91. package/lib/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  92. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  93. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  94. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  95. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  96. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  97. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  98. package/lib/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  99. package/lib/typescript/src/NativeList.d.ts +3 -3
  100. package/lib/typescript/src/NativeList.nitro.d.ts +2 -0
  101. package/lib/typescript/src/NativeList.types.d.ts +20 -2
  102. package/lib/typescript/src/index.d.ts +2 -2
  103. package/lib/typescript/src/models.d.ts +134 -17
  104. package/lib/typescript/src/validation.d.ts +20 -0
  105. package/lib/typescript/src/web/NativeListGeneratedIcons.d.ts +2 -0
  106. package/lib/typescript/src/web/NativeListWebEngine.d.ts +32 -1
  107. package/lib/typescript/src/web/templates/ButtonGroupRowRenderer.d.ts +14 -0
  108. package/lib/typescript/src/web/templates/IdentityRowRenderer.d.ts +1 -1
  109. package/lib/typescript/src/web/templates/MessageRowRenderer.d.ts +9 -3
  110. package/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  111. package/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  112. package/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  113. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  114. package/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  115. package/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  116. package/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  117. package/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  118. package/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  119. package/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  120. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  121. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  122. package/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  123. package/package.json +16 -10
  124. package/react-native-native-list.podspec +2 -6
  125. package/scripts/generate-icons.mjs +150 -0
  126. package/scripts/generate-icons.test.mjs +288 -0
  127. package/scripts/native-list-icons.json +260 -0
  128. package/src/NativeList.nitro.ts +2 -0
  129. package/src/NativeList.tsx +439 -91
  130. package/src/NativeList.types.ts +24 -2
  131. package/src/NativeList.web.tsx +286 -88
  132. package/src/index.ts +2 -0
  133. package/src/models.ts +272 -144
  134. package/src/selection.ts +1 -0
  135. package/src/validation.ts +3041 -146
  136. package/src/web/NativeListGeneratedIcons.ts +28 -0
  137. package/src/web/NativeListWebEngine.ts +818 -343
  138. package/src/web/templates/ActivityRowRenderer.ts +71 -91
  139. package/src/web/templates/ButtonGroupRowRenderer.ts +58 -0
  140. package/src/web/templates/DataRowRenderer.ts +121 -20
  141. package/src/web/templates/IdentityRowRenderer.ts +234 -9
  142. package/src/web/templates/MarketTableRowRenderer.ts +53 -33
  143. package/src/web/templates/MediaTileRowRenderer.ts +90 -28
  144. package/src/web/templates/MessageRowRenderer.ts +23 -7
  145. package/src/web/templates/RowContainerStyle.ts +2 -0
  146. package/src/web/templates/RowRendererRegistry.ts +11 -1
  147. package/src/web/templates/SectionHeaderRowRenderer.ts +47 -4
  148. package/ios/Resources/NativeListIcons.xcassets/Contents.json +0 -1
  149. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/Contents.json +0 -1
  150. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/icon.svg +0 -1
  151. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/Contents.json +0 -1
  152. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/icon.svg +0 -1
  153. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/Contents.json +0 -1
  154. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/icon.svg +0 -1
  155. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/Contents.json +0 -1
  156. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/icon.svg +0 -1
  157. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/Contents.json +0 -1
  158. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/icon.svg +0 -1
  159. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/Contents.json +0 -1
  160. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/icon.svg +0 -1
  161. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/Contents.json +0 -1
  162. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/icon.svg +0 -1
  163. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/Contents.json +0 -1
  164. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/icon.svg +0 -1
  165. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/Contents.json +0 -1
  166. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/icon.svg +0 -1
  167. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/Contents.json +0 -1
  168. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/icon.svg +0 -1
  169. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/Contents.json +0 -1
  170. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/icon.svg +0 -1
  171. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/Contents.json +0 -1
  172. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/icon.svg +0 -1
  173. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/Contents.json +0 -1
  174. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/icon.svg +0 -1
  175. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/Contents.json +0 -1
  176. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/icon.svg +0 -1
  177. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/Contents.json +0 -1
  178. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/icon.svg +0 -1
  179. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/Contents.json +0 -1
  180. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/icon.svg +0 -1
  181. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/Contents.json +0 -1
  182. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/icon.svg +0 -1
  183. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/Contents.json +0 -1
  184. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/icon.svg +0 -1
  185. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/Contents.json +0 -1
  186. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/icon.svg +0 -1
  187. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/Contents.json +0 -1
  188. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/icon.svg +0 -1
  189. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/Contents.json +0 -1
  190. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/icon.svg +0 -1
  191. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/Contents.json +0 -15
  192. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/icon.svg +0 -14
  193. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/Contents.json +0 -15
  194. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/icon.svg +0 -12
  195. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/Contents.json +0 -15
  196. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/icon.svg +0 -6
  197. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/Contents.json +0 -15
  198. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/icon.svg +0 -15
  199. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/Contents.json +0 -15
  200. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/icon.svg +0 -3
  201. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/Contents.json +0 -15
  202. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/icon.svg +0 -7
  203. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/Contents.json +0 -15
  204. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/icon.svg +0 -18
  205. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/Contents.json +0 -15
  206. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/icon.svg +0 -7
  207. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/Contents.json +0 -1
  208. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/icon.svg +0 -1
  209. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/Contents.json +0 -1
  210. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/icon.svg +0 -1
  211. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/Contents.json +0 -1
  212. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/icon.svg +0 -1
  213. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/Contents.json +0 -1
  214. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/icon.svg +0 -1
  215. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/Contents.json +0 -1
  216. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/icon.svg +0 -1
@@ -4,6 +4,100 @@ import XCTest
4
4
 
5
5
  @MainActor
6
6
  final class NativeListLifecycleTests: XCTestCase {
7
+ func testCanonicalNullPatchRemovesStoredOptionalFields() throws {
8
+ let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
9
+ let row: [String: Any] = ["key": "token", "type": "identity", "title": "Token",
10
+ "leading": ["kind": "token"], "subtitle": "Old",
11
+ "titleImage": ["image": ["uri": "data:image/png;base64,AA==", "width": 14, "height": 14]]]
12
+ let snapshot: [String: Any] = ["schemaVersion": 1, "generation": 1,
13
+ "layout": ["kind": "linear"], "rows": [row]]
14
+ view.applySnapshotJson(String(decoding: try JSONSerialization.data(withJSONObject: snapshot), as: UTF8.self))
15
+ let patches: [[String: Any]] = [["key": "token", "type": "identity",
16
+ "changes": ["title": "New", "subtitle": NSNull(), "titleImage": NSNull()]]]
17
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patches), as: UTF8.self))
18
+ let items = try XCTUnwrap(Mirror(reflecting: view).descendant("itemsByKey") as? [String: NativeListItem])
19
+ let accepted = try XCTUnwrap(items["token"])
20
+ XCTAssertEqual(accepted.data.string("title"), "New")
21
+ XCTAssertNil(accepted.data["subtitle"])
22
+ XCTAssertNil(accepted.data["titleImage"])
23
+ XCTAssertEqual(accepted.key, "token")
24
+ }
25
+
26
+ func testAcceptedRowIndexReusesStableShapeAndRejectsLateInvalidPatch() throws {
27
+ let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
28
+ func snapshot(_ keys: [String], generation: Int, title: String = "Old") throws -> String {
29
+ let rows: [[String: Any]] = keys.map { key in
30
+ ["key": key, "type": "action", "title": title, "actionKey": "open"]
31
+ }
32
+ let value: [String: Any] = ["schemaVersion": 1, "generation": generation,
33
+ "layout": ["kind": "linear"], "rows": rows]
34
+ return String(decoding: try JSONSerialization.data(withJSONObject: value), as: UTF8.self)
35
+ }
36
+ func index() throws -> (ObjectIdentifier, [String: Int]) {
37
+ let optional = try XCTUnwrap(Mirror(reflecting: view).descendant("acceptedRowIndex"))
38
+ let value = try XCTUnwrap(Mirror(reflecting: optional).children.first?.value)
39
+ let byKey = try XCTUnwrap(Mirror(reflecting: value).descendant("byKey") as? [String: Int])
40
+ return (ObjectIdentifier(value as AnyObject), byKey)
41
+ }
42
+ func title(_ key: String) throws -> String {
43
+ let items = try XCTUnwrap(Mirror(reflecting: view).descendant("itemsByKey")
44
+ as? [String: NativeListItem])
45
+ return try XCTUnwrap(items[key]?.data["title"] as? String)
46
+ }
47
+ func patch(_ rows: [[String: Any]]) throws {
48
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: rows),
49
+ as: UTF8.self))
50
+ }
51
+
52
+ view.applySnapshotJson(try snapshot(["alpha", "beta"], generation: 1))
53
+ let initial = try index()
54
+ XCTAssertEqual(initial.1, ["alpha": 0, "beta": 1])
55
+ view.applySnapshotJson(try snapshot(["alpha", "beta"], generation: 1, title: "New"))
56
+ XCTAssertEqual(try index().0, initial.0)
57
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "Patched"]],
58
+ ["key": "missing", "type": "action", "changes": ["title": "Invalid"]]])
59
+ XCTAssertEqual(try title("alpha"), "New")
60
+ XCTAssertEqual(try title("beta"), "New")
61
+ XCTAssertEqual(try index().0, initial.0)
62
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "Patched"]]])
63
+ XCTAssertEqual(try title("alpha"), "Patched")
64
+ XCTAssertEqual(try index().0, initial.0)
65
+
66
+ view.applySnapshotJson(try snapshot(["beta", "alpha"], generation: 1))
67
+ let reordered = try index()
68
+ XCTAssertNotEqual(reordered.0, initial.0)
69
+ XCTAssertEqual(reordered.1, ["beta": 0, "alpha": 1])
70
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "After reorder"]]])
71
+ XCTAssertEqual(try title("alpha"), "After reorder")
72
+ view.applySnapshotJson(try snapshot(["beta", "gamma", "alpha"], generation: 1))
73
+ let inserted = try index()
74
+ XCTAssertNotEqual(inserted.0, reordered.0)
75
+ XCTAssertEqual(inserted.1, ["beta": 0, "gamma": 1, "alpha": 2])
76
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "After insert"]]])
77
+ XCTAssertEqual(try title("alpha"), "After insert")
78
+ view.applySnapshotJson(try snapshot(["beta", "alpha"], generation: 1))
79
+ let deleted = try index()
80
+ XCTAssertNotEqual(deleted.0, inserted.0)
81
+ XCTAssertEqual(deleted.1, ["beta": 0, "alpha": 1])
82
+ try patch([["key": "alpha", "type": "action", "changes": ["title": "After delete"]]])
83
+ XCTAssertEqual(try title("alpha"), "After delete")
84
+ view.applySnapshotJson(try snapshot(["beta", "alpha"], generation: 2))
85
+ XCTAssertNotEqual(try index().0, deleted.0)
86
+ let beforeTypeChange = try index().0
87
+ let typeChanged: [String: Any] = ["schemaVersion": 1, "generation": 2,
88
+ "layout": ["kind": "linear"], "rows": [
89
+ ["key": "beta", "type": "identity", "title": "Beta",
90
+ "leading": ["kind": "icon", "name": "coin"]],
91
+ ["key": "alpha", "type": "action", "title": "Alpha", "actionKey": "open"],
92
+ ]]
93
+ view.applySnapshotJson(String(decoding: try JSONSerialization.data(withJSONObject: typeChanged),
94
+ as: UTF8.self))
95
+ XCTAssertNotEqual(try index().0, beforeTypeChange)
96
+ view.dispose()
97
+ XCTAssertEqual(Mirror(reflecting: try XCTUnwrap(Mirror(reflecting: view)
98
+ .descendant("acceptedRowIndex"))).children.count, 0)
99
+ }
100
+
7
101
  func testScrollEdgeStylesPreserveOverlayGeometryAndRestoreOriginalStyle() throws {
8
102
  guard #available(iOS 26.0, *) else {
9
103
  throw XCTSkip("Scroll-edge styles require iOS 26 or newer")
@@ -15,7 +109,8 @@ final class NativeListLifecycleTests: XCTestCase {
15
109
  let originalStyle = list.topEdgeEffect.style
16
110
  let originalInset = list.contentInset.top
17
111
  let overlay = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 64))
18
- view.mountContainerSlot(overlay, atIndex: 3)
112
+ for index in 0..<6 { view.mountContainerSlot(UIView(), atIndex: index) }
113
+ view.mountContainerSlot(overlay, atIndex: 6)
19
114
  view.setTopScrollEdge(effect: .hard, overlayHeight: 64)
20
115
  XCTAssertEqual(list.topEdgeEffect.style, .hard)
21
116
  XCTAssertEqual(list.contentInset.top, originalInset + 64, accuracy: 0.01)
@@ -153,6 +248,764 @@ final class NativeListLifecycleTests: XCTestCase {
153
248
  XCTAssertNotEqual(cell.bindingEpoch, changedEpoch)
154
249
  }
155
250
 
251
+ func testIdentityTitleImageRetainsRequestAndClearsOnProductionCellReuse() throws {
252
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 320, height: 60))
253
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 200))
254
+ window.addSubview(cell)
255
+ func bind(_ descriptor: [String: Any]?, title: String = "STOCK") throws {
256
+ var data: [String: Any] = ["key": "stock", "type": "identity", "title": title,
257
+ "height": 60, "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]]]
258
+ if let descriptor { data["titleImage"] = descriptor }
259
+ cell.bind(item: try NativeListItem(data: data), theme: nil, layout: "linear", selected: false,
260
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
261
+ cell.layoutIfNeeded()
262
+ }
263
+ let descriptor: [String: Any] = ["image": ["uri": "data:image/png;base64,AA==", "width": 14, "height": 14],
264
+ "accessibilityLabel": "Issuer", "hoverActionKey": "issuer-info"]
265
+ try bind(descriptor)
266
+ let slot = try XCTUnwrap(Mirror(reflecting: cell).children.first {
267
+ $0.label == "titleImageSlot"
268
+ }?.value as? NativeListImageSlot)
269
+ XCTAssertFalse(slot.view.isHidden)
270
+ XCTAssertEqual(slot.view.bounds.width, 14, accuracy: 0.5)
271
+ XCTAssertEqual(slot.view.bounds.height, 14, accuracy: 0.5)
272
+ XCTAssertEqual(slot.view.layer.cornerRadius, 7, accuracy: 0.1)
273
+ XCTAssertEqual(slot.view.accessibilityLabel, "Issuer")
274
+ let identity = Mirror(reflecting: slot).children.first { $0.label == "identity" }?.value as? String
275
+ XCTAssertNotNil(identity)
276
+ try bind(descriptor, title: "Changed title")
277
+ XCTAssertEqual(Mirror(reflecting: slot).children.first { $0.label == "identity" }?.value as? String, identity)
278
+ try bind(["image": ["uri": "data:image/png;base64,AQ==", "width": 20, "height": 20]])
279
+ XCTAssertEqual(slot.view.bounds.width, 20, accuracy: 0.5)
280
+ XCTAssertEqual(slot.view.layer.cornerRadius, 10, accuracy: 0.1)
281
+ XCTAssertNil(slot.view.accessibilityLabel)
282
+ XCTAssertNotEqual(Mirror(reflecting: slot).children.first { $0.label == "identity" }?.value as? String, identity)
283
+ try bind(nil)
284
+ XCTAssertTrue(slot.view.isHidden)
285
+ XCTAssertNil(Mirror(reflecting: slot).children.first { $0.label == "identity" }?.value as? String)
286
+ try bind(descriptor)
287
+ cell.prepareForReuse()
288
+ XCTAssertTrue(slot.view.isHidden)
289
+ XCTAssertNil(slot.view.accessibilityLabel)
290
+ }
291
+
292
+ func testRiskIdentityTitleIconAndButtonResetOnProductionCellBind() throws {
293
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 320, height: 56))
294
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 200))
295
+ window.addSubview(cell)
296
+ let titleIcon = try XCTUnwrap(
297
+ Mirror(reflecting: cell).children.first { $0.label == "titleIconView" }?.value as? UIImageView)
298
+ let titleStack = try XCTUnwrap(
299
+ Mirror(reflecting: cell).children.first { $0.label == "titleRowStack" }?.value as? UIStackView)
300
+ let titleLabel = try XCTUnwrap(
301
+ Mirror(reflecting: cell).children.first { $0.label == "titleLabel" }?.value as? UILabel)
302
+ let trailing = try XCTUnwrap(
303
+ Mirror(reflecting: cell).children.first { $0.label == "trailingStack" }?.value
304
+ as? NativeListAccessoryStack)
305
+ func bind(_ data: [String: Any]) throws {
306
+ let item = try NativeListItem(data: data)
307
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
308
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
309
+ cell.layoutIfNeeded()
310
+ }
311
+ let base: [String: Any] = ["key": "risk", "type": "identity", "title": "Risk",
312
+ "height": 56, "leading": ["kind": "token",
313
+ "fallbackIcon": ["name": "CryptoCoinOutline"]]]
314
+ try bind(base)
315
+ XCTAssertTrue(titleIcon.isHidden)
316
+ XCTAssertLessThanOrEqual(titleIcon.bounds.width, 0.5)
317
+ try bind(base.merging(["titleIcon": ["name": "GasSolid"],
318
+ "trailing": [["kind": "button", "label": "Show", "actionKey": "show",
319
+ "backgroundColor": "#DDDDDD", "pressedBackgroundColor": "#AAAAAA"]]]) { _, newer in newer })
320
+ XCTAssertFalse(titleIcon.isHidden)
321
+ XCTAssertNotNil(titleIcon.image)
322
+ XCTAssertEqual(titleIcon.bounds.width, 20, accuracy: 0.5)
323
+ XCTAssertEqual(titleStack.customSpacing(after: titleLabel), 4, accuracy: 0.1)
324
+ let button = try XCTUnwrap(trailing.arrangedSubviews.compactMap { $0 as? NativeListAccessoryButton }
325
+ .first { !$0.isHidden })
326
+ XCTAssertEqual(button.intrinsicContentSize.height, 30, accuracy: 0.5)
327
+ let normal = button.backgroundColor
328
+ button.isHighlighted = true
329
+ XCTAssertNotEqual(button.backgroundColor, normal)
330
+ button.isHighlighted = false
331
+ XCTAssertEqual(button.backgroundColor, normal)
332
+ try bind(base)
333
+ XCTAssertTrue(titleIcon.isHidden)
334
+ XCTAssertLessThanOrEqual(titleIcon.bounds.width, 0.5)
335
+ XCTAssertTrue(trailing.arrangedSubviews.compactMap { $0 as? NativeListAccessoryButton }
336
+ .allSatisfy { $0.isHidden })
337
+ }
338
+
339
+ func testIdentityTitleSuffixesUsePlainLabelsAndClearOnRebind() throws {
340
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 320, height: 60))
341
+ let titleStack = try XCTUnwrap(
342
+ Mirror(reflecting: cell).children.first { $0.label == "titleRowStack" }?.value as? UIStackView)
343
+ func bind(_ suffixes: [[String: Any]]?) throws {
344
+ var data: [String: Any] = [
345
+ "key": "recent", "type": "identity", "title": "Alice",
346
+ "leading": ["kind": "account", "fallbackText": "A"],
347
+ ]
348
+ if let suffixes { data["titleSuffixes"] = suffixes }
349
+ let item = try NativeListItem(data: data)
350
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
351
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
352
+ cell.layoutIfNeeded()
353
+ }
354
+ try bind([
355
+ ["text": "EVM", "tone": "secondary", "maxWidth": 128],
356
+ ["text": "2 days ago", "tone": "disabled"],
357
+ ])
358
+ let suffixes = titleStack.arrangedSubviews.compactMap { $0 as? UILabel }
359
+ .filter { ["EVM", "2 days ago"].contains($0.text ?? "") }
360
+ XCTAssertEqual(suffixes.map(\.text), ["EVM", "2 days ago"])
361
+ XCTAssertTrue(suffixes.allSatisfy { $0.font.pointSize == 12 && $0.numberOfLines == 1 })
362
+ XCTAssertFalse(suffixes.contains { $0 is NativeListInsetLabel })
363
+ try bind(nil)
364
+ XCTAssertFalse(titleStack.arrangedSubviews.compactMap { $0 as? UILabel }
365
+ .contains { ["EVM", "2 days ago"].contains($0.text ?? "") })
366
+ }
367
+
368
+ func testDataRowTitleIconsClearWhenCellIsRebound() throws {
369
+ let cell = NativeListDataRowCell(frame: CGRect(x: 0, y: 0, width: 380, height: 60))
370
+ func bind(_ column: [String: Any]) throws {
371
+ let item = try NativeListItem(data: [
372
+ "key": "asset", "type": "dataRow", "columns": [column],
373
+ ])
374
+ cell.bind(item: item, theme: nil, layout: "table", selected: false,
375
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
376
+ cell.layoutIfNeeded()
377
+ }
378
+ func titleIcons(in view: UIView) -> [UIImageView] {
379
+ let current = (view as? UIImageView).map { [$0] } ?? []
380
+ return current + view.subviews.flatMap(titleIcons)
381
+ }
382
+ try bind([
383
+ "key": "asset", "text": "ETH",
384
+ "titleIcon": ["name": "GasSolid", "accessibilityLabel": "Gas help"],
385
+ "secondaryTitleIcon": ["name": "InfoCircleOutline", "accessibilityLabel": "Info help"],
386
+ ])
387
+ let visible = titleIcons(in: cell).filter { !$0.isHidden && $0.accessibilityLabel != nil }
388
+ XCTAssertEqual(visible.compactMap(\.accessibilityLabel), ["Gas help", "Info help"])
389
+ XCTAssertTrue(visible.allSatisfy { $0.image != nil })
390
+
391
+ try bind(["key": "asset", "text": "USDC"])
392
+ XCTAssertTrue(titleIcons(in: cell).allSatisfy {
393
+ $0.accessibilityLabel != "Gas help" && $0.accessibilityLabel != "Info help"
394
+ })
395
+ }
396
+
397
+ func testDataRowLinearRebindKeepsSizeConstraintsAndClearsOldContent() throws {
398
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 700, height: 100))
399
+ let cell = NativeListDataRowCell(frame: CGRect(x: 0, y: 0, width: 700, height: 60))
400
+ window.addSubview(cell)
401
+ window.isHidden = false
402
+ defer { window.isHidden = true }
403
+ func bind(_ title: String, secondary: String, layout: String = "linear",
404
+ visualWidth: Int, trailing: String?, icon: Bool = false, badge: Bool = false,
405
+ key: String = "asset") throws {
406
+ var column: [String: Any] = ["key": "asset", "text": title, "secondaryText": secondary]
407
+ if icon { column["titleIcon"] = ["name": "GasSolid", "accessibilityLabel": "Gas help"] }
408
+ let item = try NativeListItem(data: [
409
+ "key": key, "type": "dataRow", "height": 60,
410
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
411
+ "columns": [column], "badges": badge ? [["text": "Badge"]] : [],
412
+ "trailing": trailing.map { [["kind": "button", "label": $0, "actionKey": "swap"]] } ?? [],
413
+ "style": ["image": ["width": visualWidth, "height": visualWidth]],
414
+ ])
415
+ cell.bind(item: item, theme: nil, layout: layout, selected: false,
416
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
417
+ window.layoutIfNeeded()
418
+ cell.layoutIfNeeded()
419
+ }
420
+ func property<T>(_ name: String, in object: Any, as type: T.Type) throws -> T {
421
+ try XCTUnwrap(Mirror(reflecting: object).children.first { $0.label == name }?.value as? T)
422
+ }
423
+ let columns = try XCTUnwrap(cell.root.arrangedSubviews[3] as? UIStackView)
424
+ let firstColumn = columns.arrangedSubviews[0]
425
+ let primary: UILabel = try property("primaryLabel", in: firstColumn, as: UILabel.self)
426
+ let secondary: UILabel = try property("secondaryLabel", in: firstColumn, as: UILabel.self)
427
+ let secondaryLine: UIStackView = try property("secondaryLine", in: firstColumn,
428
+ as: UIStackView.self)
429
+ let titleIcon: UIImageView = try property("titleIconView", in: firstColumn,
430
+ as: UIImageView.self)
431
+ let badges: UIStackView = try property("badgesStack", in: firstColumn,
432
+ as: UIStackView.self)
433
+
434
+ try bind("ETH", secondary: "Ethereum", visualWidth: 32, trailing: "Swap",
435
+ icon: true, badge: true)
436
+ let sizeConstraints: [NSLayoutConstraint] = try property("rowConstraints", in: cell,
437
+ as: [NSLayoutConstraint].self)
438
+ XCTAssertEqual(sizeConstraints.count, 4)
439
+ let trailingStack = cell.root.arrangedSubviews[4]
440
+ let trailingWidth = try XCTUnwrap(trailingStack.constraints.first {
441
+ $0.firstAttribute == .width && ($0.firstItem as? UIView) === trailingStack
442
+ })
443
+ XCTAssertTrue(trailingWidth.isActive)
444
+ let shortTrailingWidth = trailingWidth.constant
445
+ XCTAssertEqual(sizeConstraints[2].constant, 32, accuracy: 0.1)
446
+ XCTAssertTrue(primary.attributedText?.string.contains("Badge") ?? false)
447
+ XCTAssertFalse(titleIcon.isHidden)
448
+ XCTAssertEqual(badges.arrangedSubviews.count, 0)
449
+
450
+ try bind("ETH", secondary: "Ethereum", visualWidth: 32, trailing: "Manage asset")
451
+ XCTAssertGreaterThan(trailingWidth.constant, shortTrailingWidth + 1)
452
+ let columnsFrame = columns.convert(columns.bounds, to: cell)
453
+ let trailingFrame = trailingStack.convert(trailingStack.bounds, to: cell)
454
+ XCTAssertGreaterThanOrEqual(trailingFrame.minX, columnsFrame.maxX - 0.5)
455
+ try bind("ETH", secondary: "Ethereum", visualWidth: 32, trailing: "Swap")
456
+ XCTAssertEqual(trailingWidth.constant, shortTrailingWidth, accuracy: 1)
457
+
458
+ try bind("", secondary: "", visualWidth: 48, trailing: nil)
459
+ let reboundConstraints: [NSLayoutConstraint] = try property("rowConstraints", in: cell,
460
+ as: [NSLayoutConstraint].self)
461
+ XCTAssertEqual(reboundConstraints.count, sizeConstraints.count)
462
+ XCTAssertTrue(zip(sizeConstraints, reboundConstraints).allSatisfy { $0 === $1 })
463
+ XCTAssertEqual(sizeConstraints[2].constant, 48, accuracy: 0.1)
464
+ XCTAssertFalse(trailingWidth.isActive)
465
+ XCTAssertEqual(primary.attributedText?.string, "")
466
+ XCTAssertNil(secondary.attributedText)
467
+ XCTAssertTrue(secondaryLine.isHidden)
468
+ XCTAssertTrue(titleIcon.isHidden)
469
+ XCTAssertNil(titleIcon.accessibilityLabel)
470
+ XCTAssertTrue(badges.arrangedSubviews.isEmpty)
471
+
472
+ try bind("Table", secondary: "New", layout: "table", visualWidth: 40, trailing: "Swap")
473
+ XCTAssertTrue(trailingWidth.isActive)
474
+ XCTAssertEqual(sizeConstraints[2].constant, 40, accuracy: 0.1)
475
+ XCTAssertEqual(primary.attributedText?.string, "Table")
476
+ XCTAssertEqual(secondary.attributedText?.string, "New")
477
+ try bind("Linear", secondary: "", visualWidth: 40, trailing: nil)
478
+ XCTAssertEqual(primary.attributedText?.string, "Linear")
479
+ XCTAssertNil(secondary.attributedText)
480
+ cell.prepareForReuse()
481
+ XCTAssertNil(primary.attributedText)
482
+ XCTAssertTrue(titleIcon.isHidden)
483
+ try bind("Replacement", secondary: "", visualWidth: 40, trailing: nil, key: "next")
484
+ XCTAssertEqual(primary.attributedText?.string, "Replacement")
485
+ }
486
+
487
+ func testIdentityTrailingActionUsesDescriptorSlotAfterCheckboxAndRebind() throws {
488
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 200))
489
+ let controller = UIViewController()
490
+ window.rootViewController = controller
491
+ window.isHidden = false
492
+ defer { window.isHidden = true }
493
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 56))
494
+ controller.view.addSubview(cell)
495
+ let trailing = try XCTUnwrap(
496
+ Mirror(reflecting: cell).children.first { $0.label == "trailingStack" }?.value
497
+ as? NativeListAccessoryStack)
498
+ var actions: [(rowKey: String, key: String, source: String, slot: Int?)] = []
499
+ cell.onAction = { item, key, _, origin in
500
+ actions.append((item.key, key, origin?.source ?? "", origin?.slot))
501
+ }
502
+ func bind(_ trailingData: [[String: Any]], key: String = "row") throws {
503
+ let item = try NativeListItem(data: [
504
+ "key": key, "type": "identity", "title": "Row", "trailing": trailingData,
505
+ ])
506
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
507
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
508
+ window.layoutIfNeeded()
509
+ cell.layoutIfNeeded()
510
+ }
511
+ func visibleButtons() -> [NativeListAccessoryButton] {
512
+ trailing.arrangedSubviews.compactMap { $0 as? NativeListAccessoryButton }
513
+ .filter { !$0.isHidden }
514
+ }
515
+ let checkbox: [String: Any] = [
516
+ "kind": "checkbox", "state": "unchecked", "actionKey": "selection",
517
+ ]
518
+ let first: [String: Any] = ["kind": "button", "label": "First", "actionKey": "first"]
519
+ let second: [String: Any] = ["kind": "button", "label": "Second", "actionKey": "second"]
520
+
521
+ try bind([checkbox, second])
522
+ XCTAssertEqual(visibleButtons().count, 1)
523
+ XCTAssertTrue(visibleButtons()[0].isEnabled)
524
+ XCTAssertTrue(visibleButtons()[0].isUserInteractionEnabled)
525
+ XCTAssertTrue(visibleButtons()[0].allTargets.contains(trailing))
526
+ XCTAssertNotNil(trailing.onAction)
527
+ try dispatchAccessoryTouchUpInside(visibleButtons()[0], on: trailing)
528
+ XCTAssertEqual(actions.last?.rowKey, "row")
529
+ XCTAssertEqual(actions.last?.key, "second")
530
+ XCTAssertEqual(actions.last?.source, "trailingAccessory")
531
+ XCTAssertEqual(actions.last?.slot, 1)
532
+ let selection = try XCTUnwrap(trailing.arrangedSubviews.compactMap { $0 as? UIButton }
533
+ .first { !($0 is NativeListAccessoryButton) && !$0.isHidden })
534
+ try dispatchAccessoryTouchUpInside(selection, on: trailing)
535
+ XCTAssertEqual(actions.last?.key, "selection")
536
+ XCTAssertNil(actions.last?.slot)
537
+
538
+ try bind([first, second])
539
+ XCTAssertEqual(visibleButtons().count, 2)
540
+ try dispatchAccessoryTouchUpInside(visibleButtons()[0], on: trailing)
541
+ XCTAssertEqual(actions.last?.key, "first")
542
+ XCTAssertEqual(actions.last?.slot, 0)
543
+ try dispatchAccessoryTouchUpInside(visibleButtons()[1], on: trailing)
544
+ XCTAssertEqual(actions.last?.key, "second")
545
+ XCTAssertEqual(actions.last?.slot, 1)
546
+
547
+ try bind([second], key: "replacement")
548
+ XCTAssertEqual(visibleButtons().count, 1)
549
+ try dispatchAccessoryTouchUpInside(visibleButtons()[0], on: trailing)
550
+ XCTAssertEqual(actions.last?.rowKey, "replacement")
551
+ XCTAssertEqual(actions.last?.key, "second")
552
+ XCTAssertEqual(actions.last?.slot, 0)
553
+ XCTAssertEqual(actions.count, 5)
554
+ }
555
+
556
+ func testIdentityTertiaryIconAnchorInsetSurvivesAccessoryRebind() throws {
557
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 200))
558
+ let controller = UIViewController()
559
+ window.rootViewController = controller
560
+ window.isHidden = false
561
+ defer { window.isHidden = true }
562
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 88))
563
+ controller.view.addSubview(cell)
564
+ let trailing = try XCTUnwrap(
565
+ Mirror(reflecting: cell).children.first { $0.label == "trailingStack" }?.value
566
+ as? NativeListAccessoryStack)
567
+ var actions: [(rowKey: String, source: String, slot: Int?, inset: CGFloat,
568
+ width: CGFloat)] = []
569
+ cell.onAction = { item, _, _, origin in
570
+ actions.append((item.key, origin?.source ?? "", origin?.slot, origin?.anchorInset ?? -1,
571
+ origin?.sourceView?.bounds.width ?? -1))
572
+ }
573
+ func bind(_ descriptors: [[String: Any]], key: String,
574
+ presentation: String? = nil) throws -> NativeListAccessoryButton {
575
+ var data: [String: Any] = [
576
+ "key": key, "type": "identity", "title": "Row", "height": 88,
577
+ "trailing": descriptors,
578
+ ]
579
+ if let presentation { data["presentation"] = presentation }
580
+ cell.bind(item: try NativeListItem(data: data), theme: nil, layout: "linear",
581
+ selected: false, checkboxState: { _, _, fallback in fallback },
582
+ fonts: NativeListFontFamilies())
583
+ window.layoutIfNeeded()
584
+ cell.layoutIfNeeded()
585
+ return try XCTUnwrap(trailing.firstVisibleControl as? NativeListAccessoryButton)
586
+ }
587
+ let tertiary: [String: Any] = [
588
+ "kind": "icon", "name": "CryptoCoinOutline", "buttonStyle": "tertiary",
589
+ "actionKey": "menu",
590
+ ]
591
+ let ordinary: [String: Any] = [
592
+ "kind": "icon", "name": "CryptoCoinOutline", "actionKey": "menu",
593
+ ]
594
+
595
+ let first = try bind([
596
+ ["kind": "checkbox", "state": "unchecked", "actionKey": "selection"], tertiary,
597
+ ], key: "tertiary-first")
598
+ XCTAssertEqual(first.bounds.width, 38, accuracy: 0.5)
599
+ try dispatchAccessoryTouchUpInside(first, on: trailing)
600
+ XCTAssertEqual(actions.last?.rowKey, "tertiary-first")
601
+ XCTAssertEqual(actions.last?.source, "trailingAccessory")
602
+ XCTAssertEqual(actions.last?.slot, 1)
603
+ XCTAssertEqual(actions.last?.inset, 7)
604
+ let firstOrigin = try XCTUnwrap(actions.last)
605
+ XCTAssertEqual(firstOrigin.width - 2 * firstOrigin.inset, 24, accuracy: 0.5)
606
+
607
+ let normal = try bind([ordinary], key: "ordinary")
608
+ XCTAssertEqual(normal.bounds.width, 36, accuracy: 0.5)
609
+ try dispatchAccessoryTouchUpInside(normal, on: trailing)
610
+ XCTAssertEqual(actions.last?.rowKey, "ordinary")
611
+ XCTAssertEqual(actions.last?.slot, 0)
612
+ XCTAssertEqual(actions.last?.inset, 0)
613
+ XCTAssertEqual(actions.last?.width, 36)
614
+
615
+ let value = try bind([["kind": "value", "text": "Value"]], key: "value")
616
+ value.bounds.size.width = 38
617
+ XCTAssertEqual(trailing.anchorInset(for: value), 0)
618
+
619
+ let rebound = try bind([tertiary], key: "tertiary-again")
620
+ try dispatchAccessoryTouchUpInside(rebound, on: trailing)
621
+ XCTAssertEqual(actions.last?.rowKey, "tertiary-again")
622
+ XCTAssertEqual(actions.last?.slot, 0)
623
+ XCTAssertEqual(actions.last?.inset, 7)
624
+ let reboundOrigin = try XCTUnwrap(actions.last)
625
+ XCTAssertEqual(reboundOrigin.width - 2 * reboundOrigin.inset, 24, accuracy: 0.5)
626
+
627
+ let account = try bind([ordinary], key: "account", presentation: "accountSelector")
628
+ XCTAssertEqual(account.bounds.width, 38, accuracy: 0.5)
629
+ try dispatchAccessoryTouchUpInside(account, on: trailing)
630
+ XCTAssertEqual(actions.last?.rowKey, "account")
631
+ XCTAssertEqual(actions.last?.slot, 0)
632
+ XCTAssertEqual(actions.last?.inset, 7)
633
+ let accountOrigin = try XCTUnwrap(actions.last)
634
+ XCTAssertEqual(accountOrigin.width - 2 * accountOrigin.inset, 24, accuracy: 0.5)
635
+
636
+ let finalOrdinary = try bind([ordinary], key: "ordinary-again")
637
+ try dispatchAccessoryTouchUpInside(finalOrdinary, on: trailing)
638
+ XCTAssertEqual(actions.last?.rowKey, "ordinary-again")
639
+ XCTAssertEqual(actions.last?.inset, 0)
640
+ XCTAssertEqual(actions.count, 5)
641
+ }
642
+
643
+ func testValuePairSegmentsStyleAndPlainRebindOnProductionAccessoryStack() throws {
644
+ let stack = NativeListAccessoryStack(frame: CGRect(x: 0, y: 0, width: 180, height: 48))
645
+ let item = try NativeListItem(data: [
646
+ "key": "pair", "type": "identity", "title": "Pair",
647
+ "leading": ["kind": "icon", "name": "coin"],
648
+ ])
649
+ let pair: [String: Any] = [
650
+ "kind": "valuePair", "primary": "0.001", "secondary": "$0.01",
651
+ "primaryTextSegments": [["text": "0.00"], ["text": "1", "style": "subscript"]],
652
+ "secondaryTextSegments": [["text": "$0.0"], ["text": "1", "style": "subscript"]],
653
+ ]
654
+ func bind(_ descriptor: [String: Any], size: Int? = nil) {
655
+ let style: [String: Any] = size.map { ["value": ["fontSize": $0]] } ?? [:]
656
+ stack.bind(item, descriptors: [descriptor], theme: nil, style: style,
657
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
658
+ }
659
+ func fontSize(_ title: NSAttributedString, at index: Int) throws -> CGFloat {
660
+ try XCTUnwrap(title.attribute(.font, at: index, effectiveRange: nil) as? UIFont).pointSize
661
+ }
662
+ bind(pair)
663
+ let button = try XCTUnwrap(stack.arrangedSubviews.compactMap { $0 as? UIButton }
664
+ .first { !$0.isHidden })
665
+ let rich = try XCTUnwrap(button.attributedTitle(for: .normal))
666
+ XCTAssertEqual(rich.string, "0.001\n$0.01")
667
+ XCTAssertEqual(try fontSize(rich, at: 0), 16)
668
+ XCTAssertEqual(try fontSize(rich, at: 4), 10)
669
+ XCTAssertEqual(try fontSize(rich, at: 6), 14)
670
+ XCTAssertEqual(try fontSize(rich, at: 10), 9)
671
+ bind(pair, size: 20)
672
+ let styled = try XCTUnwrap(button.attributedTitle(for: .normal))
673
+ XCTAssertEqual(try fontSize(styled, at: 0), 20)
674
+ XCTAssertEqual(try fontSize(styled, at: 4), 12)
675
+ XCTAssertEqual(try fontSize(styled, at: 10), 12)
676
+ bind(["kind": "valuePair", "primary": "10", "secondary": "$2"])
677
+ let plain = try XCTUnwrap(button.attributedTitle(for: .normal))
678
+ XCTAssertEqual(plain.string, "10\n$2")
679
+ XCTAssertEqual(try fontSize(plain, at: 0), 16)
680
+ XCTAssertEqual(try fontSize(plain, at: 3), 14)
681
+ bind(["kind": "valuePair", "primary": "10", "secondary": "$2",
682
+ "primaryTextSegments": [], "secondaryTextSegments": []])
683
+ XCTAssertEqual(button.attributedTitle(for: .normal)?.string, "10\n$2")
684
+ stack.reset()
685
+ XCTAssertNil(button.title(for: .normal))
686
+ XCTAssertNil(button.attributedTitle(for: .normal))
687
+ XCTAssertTrue(button.isHidden)
688
+ bind(["kind": "value", "text": "Updated"])
689
+ XCTAssertEqual(button.title(for: .normal), "Updated")
690
+ XCTAssertEqual(button.titleLabel?.text, "Updated")
691
+ XCTAssertNil(button.attributedTitle(for: .normal))
692
+ }
693
+
694
+ func testDecorativeRefreshKeepsSixteenPointFrameAcrossActionRebind() throws {
695
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 56))
696
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 80))
697
+ window.addSubview(cell)
698
+ let stack = try XCTUnwrap(Mirror(reflecting: cell).children.first {
699
+ $0.label == "trailingStack"
700
+ }?.value as? NativeListAccessoryStack)
701
+ func bind(actionKey: String? = nil) throws {
702
+ var icon: [String: Any] = ["kind": "icon", "name": "RefreshCcwOutline"]
703
+ if let actionKey { icon["actionKey"] = actionKey }
704
+ let item = try NativeListItem(data: [
705
+ "key": "refresh", "type": "identity", "title": "Network", "height": 56,
706
+ "leading": ["kind": "icon", "name": "coin"], "trailing": [icon],
707
+ ])
708
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
709
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
710
+ window.layoutIfNeeded()
711
+ cell.layoutIfNeeded()
712
+ }
713
+ try bind()
714
+ let button = try XCTUnwrap(stack.firstVisibleControl as? UIButton)
715
+ XCTAssertEqual(button.bounds.width, 16, accuracy: 0.5)
716
+ XCTAssertEqual(button.bounds.height, 16, accuracy: 0.5)
717
+ XCTAssertNotNil(button.image(for: .normal))
718
+ XCTAssertEqual(button.image(for: .normal)?.size.width, 16)
719
+ XCTAssertEqual(button.image(for: .normal)?.size.height, 16)
720
+ XCTAssertFalse(button.isUserInteractionEnabled)
721
+ try bind(actionKey: "refresh")
722
+ XCTAssertEqual(button.bounds.width, 36, accuracy: 0.5)
723
+ XCTAssertEqual(button.bounds.height, 36, accuracy: 0.5)
724
+ XCTAssertTrue(button.isUserInteractionEnabled)
725
+ try bind()
726
+ XCTAssertEqual(button.bounds.width, 16, accuracy: 0.5)
727
+ XCTAssertEqual(button.bounds.height, 16, accuracy: 0.5)
728
+ XCTAssertEqual(button.image(for: .normal)?.size.width, 16)
729
+ XCTAssertEqual(button.image(for: .normal)?.size.height, 16)
730
+ XCTAssertFalse(button.isUserInteractionEnabled)
731
+ }
732
+
733
+ func testLowValueAndOverviewAccessoryLayoutsOnProductionIdentityCell() throws {
734
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 60))
735
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 180))
736
+ window.addSubview(cell)
737
+ let main = try XCTUnwrap(Mirror(reflecting: cell).children.first { $0.label == "mainStack" }?
738
+ .value as? UIStackView)
739
+ let trailing = try XCTUnwrap(Mirror(reflecting: cell).children.first {
740
+ $0.label == "trailingStack"
741
+ }?.value as? NativeListAccessoryStack)
742
+ func bind(_ data: [String: Any], height: CGFloat) throws {
743
+ cell.frame.size.height = height
744
+ cell.bind(item: try NativeListItem(data: data), theme: nil, layout: "linear",
745
+ selected: false, checkboxState: { _, _, fallback in fallback },
746
+ fonts: NativeListFontFamilies())
747
+ window.layoutIfNeeded()
748
+ cell.layoutIfNeeded()
749
+ }
750
+ let pair: [String: Any] = ["kind": "valuePair", "primary": "1.0193B",
751
+ "secondary": "$1,018,849,363.70"]
752
+ let lowValue: [String: Any] = ["key": "low", "type": "identity", "height": 60,
753
+ "title": "FRAX", "subtitleSegments": [
754
+ ["text": "$0.9918", "tone": "secondary", "textSegments": [
755
+ ["text": "$0.99"], ["text": "18", "style": "subscript"]]],
756
+ ["text": "\u{00a0}+0.05%", "tone": "positive"]],
757
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
758
+ "trailing": [pair], "style": ["horizontalPadding": 12, "verticalPadding": 8,
759
+ "leadingGap": 12, "image": ["width": 40, "height": 40]]]
760
+ try bind(lowValue, height: 60)
761
+ let priceLabels = try XCTUnwrap(Mirror(reflecting: cell).children.first {
762
+ $0.label == "semanticSubtitleLabels"
763
+ }?.value as? [UILabel])
764
+ XCTAssertEqual(priceLabels.count, 2)
765
+ XCTAssertGreaterThan(main.bounds.width, 150)
766
+ XCTAssertTrue(priceLabels.allSatisfy { $0.bounds.width > 0 && !$0.isHidden })
767
+ XCTAssertLessThanOrEqual(priceLabels.last?.frame.maxX ?? .infinity, main.bounds.width + 0.5)
768
+ XCTAssertEqual(trailing.bounds.width, trailing.firstVisibleControl?.bounds.width ?? -1,
769
+ accuracy: 0.5)
770
+ let detail: [String: Any] = ["key": "detail", "type": "identity", "height": 60,
771
+ "title": "Ethereum", "subtitle": "100.0%",
772
+ "leading": ["kind": "network", "fallbackIcon": ["name": "GlobusOutline"]],
773
+ "trailing": [pair, ["kind": "chevron"]],
774
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
775
+ "trailingGap": 12, "image": ["width": 32, "height": 32]]]
776
+ try bind(detail, height: 60)
777
+ XCTAssertEqual(trailing.axis, .horizontal)
778
+ let detailControls = trailing.arrangedSubviews.filter { !$0.isHidden }
779
+ XCTAssertEqual(detailControls.count, 2)
780
+ let detailRects = detailControls.map { $0.convert($0.bounds, to: cell) }
781
+ XCTAssertTrue(detailRects.allSatisfy { $0.minY >= 0 && $0.maxY <= 60 })
782
+ XCTAssertEqual(detailRects[0].midY, detailRects[1].midY, accuracy: 1)
783
+ XCTAssertEqual(detailRects[1].minX - detailRects[0].maxX, 12, accuracy: 0.5)
784
+ XCTAssertEqual(detailRects[1].maxX, cell.bounds.maxX - 12, accuracy: 0.5)
785
+ let missing: [String: Any] = ["key": "missing", "type": "identity", "height": 48,
786
+ "title": "Ethereum", "leading": ["kind": "network",
787
+ "fallbackIcon": ["name": "GlobusOutline"]],
788
+ "trailing": [["kind": "icon", "name": "RefreshCcwOutline"], ["kind": "chevron"]],
789
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
790
+ "trailingGap": 12, "image": ["width": 32, "height": 32]]]
791
+ try bind(missing, height: 48)
792
+ XCTAssertEqual(trailing.axis, .horizontal)
793
+ let missingControls = trailing.arrangedSubviews.filter { !$0.isHidden }
794
+ XCTAssertEqual(missingControls.count, 2)
795
+ XCTAssertEqual(missingControls[0].bounds.width, 16, accuracy: 0.5)
796
+ XCTAssertEqual(missingControls[1].bounds.width, 24, accuracy: 0.5)
797
+ let missingRects = missingControls.map { $0.convert($0.bounds, to: cell) }
798
+ XCTAssertTrue(missingRects.allSatisfy { $0.minY >= 0 && $0.maxY <= 48 })
799
+ XCTAssertEqual(missingRects[0].midY, missingRects[1].midY, accuracy: 1)
800
+ XCTAssertEqual(missingRects[1].minX - missingRects[0].maxX, 12, accuracy: 0.5)
801
+ XCTAssertEqual(missingRects[1].maxX, cell.bounds.maxX - 12, accuracy: 0.5)
802
+ try bind(detail, height: 60)
803
+ XCTAssertEqual(trailing.axis, .horizontal)
804
+ try bind(["key": "plain", "type": "identity", "title": "Plain", "height": 56,
805
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]]],
806
+ height: 56)
807
+ let remainingConstraints = try XCTUnwrap(Mirror(reflecting: cell).children.first {
808
+ $0.label == "selectorConstraints"
809
+ }?.value as? [NSLayoutConstraint])
810
+ XCTAssertTrue(remainingConstraints.isEmpty)
811
+ }
812
+
813
+ func testSwapValuePairAndTertiaryMenuIconFitAndKeepActionState() throws {
814
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 60))
815
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 120))
816
+ window.addSubview(cell)
817
+ defer { cell.removeFromSuperview() }
818
+ let trailing = try XCTUnwrap(Mirror(reflecting: cell).children.first {
819
+ $0.label == "trailingStack"
820
+ }?.value as? NativeListAccessoryStack)
821
+ var actions: [(String, Int?)] = []
822
+ cell.onAction = { _, action, _, origin in actions.append((action, origin?.slot)) }
823
+ func bind(disabled: Bool) throws {
824
+ let item = try NativeListItem(data: [
825
+ "key": "swap-token", "type": "identity", "height": 60,
826
+ "title": "ETH", "subtitle": "Ethereum",
827
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
828
+ "trailing": [
829
+ ["kind": "valuePair", "primary": "0.001328", "secondary": "$3.08"],
830
+ ["kind": "icon", "name": "DotVerSolid", "buttonStyle": "tertiary",
831
+ "actionKey": "menu", "disabled": disabled],
832
+ ],
833
+ "style": ["horizontalPadding": 20, "verticalPadding": 8,
834
+ "leadingGap": 12, "trailingGap": 8,
835
+ "image": ["width": 40, "height": 40]],
836
+ ])
837
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
838
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
839
+ window.layoutIfNeeded()
840
+ cell.layoutIfNeeded()
841
+ }
842
+ try bind(disabled: false)
843
+ XCTAssertEqual(trailing.axis, .horizontal)
844
+ let controls = trailing.arrangedSubviews.compactMap { !$0.isHidden ? $0 as? UIButton : nil }
845
+ XCTAssertEqual(controls.count, 2)
846
+ let rects = controls.map { $0.convert($0.bounds, to: cell) }
847
+ XCTAssertTrue(rects.allSatisfy { $0.minY >= 0 && $0.maxY <= cell.bounds.height })
848
+ let amountLabel = try XCTUnwrap(controls[0].titleLabel)
849
+ let amountRect = amountLabel.convert(amountLabel.bounds, to: cell)
850
+ XCTAssertEqual(amountLabel.numberOfLines, 2)
851
+ XCTAssertGreaterThan(amountRect.height, 30)
852
+ XCTAssertGreaterThanOrEqual(amountRect.minY, 0)
853
+ XCTAssertLessThanOrEqual(amountRect.maxY, cell.bounds.height)
854
+ XCTAssertEqual(rects[0].midY, rects[1].midY, accuracy: 1)
855
+ XCTAssertEqual(rects[1].minX - rects[0].maxX, 8, accuracy: 0.5)
856
+ XCTAssertEqual(controls[1].bounds.height, 38, accuracy: 0.5)
857
+ XCTAssertTrue(controls[1].isEnabled)
858
+ try dispatchAccessoryTouchUpInside(controls[1], on: trailing)
859
+ XCTAssertEqual(actions.count, 1)
860
+ let action = try XCTUnwrap(actions.first)
861
+ XCTAssertEqual(action.0, "menu")
862
+ XCTAssertEqual(action.1, 1)
863
+
864
+ try bind(disabled: true)
865
+ let disabledIcon = try XCTUnwrap(trailing.arrangedSubviews.filter { !$0.isHidden }.last as? UIButton)
866
+ XCTAssertFalse(disabledIcon.isEnabled)
867
+ try dispatchAccessoryTouchUpInside(disabledIcon, on: trailing)
868
+ XCTAssertEqual(actions.count, 1)
869
+ }
870
+
871
+ func testRiskIdentityRatioKeepsTitleVisibleWithAndWithoutButton() throws {
872
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 56))
873
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 200))
874
+ window.addSubview(cell)
875
+ let titleLabel = try XCTUnwrap(
876
+ Mirror(reflecting: cell).children.first { $0.label == "titleLabel" }?.value as? UILabel)
877
+ let mainStack = try XCTUnwrap(
878
+ Mirror(reflecting: cell).children.first { $0.label == "mainStack" }?.value as? UIStackView)
879
+ let trailing = try XCTUnwrap(
880
+ Mirror(reflecting: cell).children.first { $0.label == "trailingStack" }?.value
881
+ as? NativeListAccessoryStack)
882
+ let base: [String: Any] = [
883
+ "key": "risk", "type": "identity", "title": "XSR", "height": 56,
884
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
885
+ "style": [
886
+ "horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
887
+ "leadingContentMaxWidthRatio": 0.6,
888
+ "image": ["width": 40, "height": 40, "shape": "circle"],
889
+ "title": ["fontSize": 16, "lineHeight": 24, "fontWeight": "medium", "lines": 1],
890
+ ],
891
+ ]
892
+
893
+ func bind(_ data: [String: Any], capped: Bool = true) throws {
894
+ cell.bind(item: try NativeListItem(data: data), theme: nil, layout: "linear",
895
+ selected: false, checkboxState: { _, _, fallback in fallback },
896
+ fonts: NativeListFontFamilies())
897
+ window.layoutIfNeeded()
898
+ cell.layoutIfNeeded()
899
+ XCTAssertFalse(titleLabel.isHidden)
900
+ XCTAssertGreaterThan(titleLabel.bounds.width, 0.5,
901
+ "A visible token title must not collapse when the row reserves trailing space")
902
+ XCTAssertEqual(titleLabel.bounds.height, 24, accuracy: 0.5)
903
+ let intrinsicWidth = titleLabel.intrinsicContentSize.width
904
+ let capWidth = cell.root.bounds.width * 0.6 - 52
905
+ let requiredTitleWidth = capped ? min(intrinsicWidth, capWidth) : intrinsicWidth
906
+ XCTAssertGreaterThanOrEqual(titleLabel.bounds.width, requiredTitleWidth - 0.5,
907
+ "title=\(data["title"] ?? "") intrinsic=\(intrinsicWidth) "
908
+ + "rendered=\(titleLabel.bounds.width) root=\(cell.root.bounds.width) "
909
+ + "trailing=\(trailing.bounds.width)")
910
+ XCTAssertGreaterThanOrEqual(mainStack.bounds.width, titleLabel.bounds.width - 0.5)
911
+ XCTAssertEqual(trailing.frame.maxX, cell.root.bounds.maxX, accuracy: 0.5)
912
+ if capped {
913
+ XCTAssertLessThanOrEqual(mainStack.bounds.width, cell.root.bounds.width * 0.6 - 52 + 0.5)
914
+ }
915
+ }
916
+
917
+ try bind(base)
918
+ XCTAssertNil(trailing.firstVisibleControl)
919
+ try bind(base.merging(["trailing": [[
920
+ "kind": "button", "label": "Show on home", "actionKey": "show",
921
+ ]]]) { _, newer in newer })
922
+ let button = try XCTUnwrap(trailing.firstVisibleControl)
923
+ XCTAssertGreaterThan(button.bounds.width, 100)
924
+ XCTAssertEqual(trailing.frame.minX + button.frame.maxX, cell.root.bounds.maxX, accuracy: 0.5)
925
+ cell.frame.size.height = 88
926
+ try bind(base.merging(["trailing": [
927
+ ["kind": "button", "label": "A", "actionKey": "first"],
928
+ ["kind": "button", "label": "Longer action", "actionKey": "second"],
929
+ ], "height": 88]) { _, newer in newer })
930
+ let visibleButtons = trailing.arrangedSubviews.compactMap { $0 as? NativeListAccessoryButton }
931
+ .filter { !$0.isHidden }
932
+ XCTAssertEqual(visibleButtons.count, 2)
933
+ XCTAssertGreaterThan(visibleButtons[1].bounds.width, visibleButtons[0].bounds.width)
934
+ XCTAssertEqual(trailing.frame.minX + visibleButtons[1].frame.maxX,
935
+ cell.root.bounds.maxX, accuracy: 0.5)
936
+ cell.frame.size.height = 56
937
+ try bind(base.merging(["title": "A very long token symbol that must truncate within the cap"])
938
+ { _, newer in newer })
939
+ XCTAssertLessThan(titleLabel.bounds.width, titleLabel.intrinsicContentSize.width)
940
+ try bind(base)
941
+ XCTAssertNil(trailing.firstVisibleControl)
942
+ try bind(base.merging(["key": "searched-risk", "title": "rkl"]) { _, newer in newer })
943
+ XCTAssertNil(trailing.firstVisibleControl)
944
+ try bind(base)
945
+ var unrestricted = base
946
+ var unrestrictedStyle = try XCTUnwrap(base["style"] as? [String: Any])
947
+ unrestrictedStyle.removeValue(forKey: "leadingContentMaxWidthRatio")
948
+ unrestricted["style"] = unrestrictedStyle
949
+ try bind(unrestricted, capped: false)
950
+ XCTAssertEqual(cell.root.arrangedSubviews.count, 3)
951
+ XCTAssertEqual(mainStack.contentHuggingPriority(for: .horizontal).rawValue, 1, accuracy: 0.1)
952
+ let spacing = cell.root.customSpacing(after: mainStack)
953
+ XCTAssertTrue(spacing == UIStackView.spacingUseDefault || spacing == cell.root.spacing)
954
+ }
955
+
956
+ func testAutoHeightIdentityReservesMeasuredTrailingWidth() throws {
957
+ let subtitle = "A long recipient address that must wrap within the space left beside its values and controls"
958
+ func item(
959
+ trailing: [[String: Any]], horizontalPadding: Double? = nil,
960
+ presentation: String = ""
961
+ ) throws -> NativeListItem {
962
+ var style: [String: Any] = ["image": ["width": 40, "height": 40]]
963
+ if let horizontalPadding { style["horizontalPadding"] = horizontalPadding }
964
+ return try NativeListItem(data: [
965
+ "key": "recipient", "type": "identity", "title": "Recipient", "subtitle": subtitle,
966
+ "subtitleLines": 0, "contentHeight": "auto", "style": style,
967
+ "presentation": presentation,
968
+ "trailing": trailing,
969
+ ])
970
+ }
971
+ func height(width: CGFloat, item: NativeListItem) throws -> CGFloat {
972
+ return try XCTUnwrap(NativeListIdentityCell.measure(
973
+ item, width: width, theme: nil, layout: "linear", fonts: NativeListFontFamilies()))
974
+ }
975
+
976
+ let pair: [[String: Any]] = [[
977
+ "kind": "valuePair", "primary": "$123,456.78", "secondary": "12345 TOKEN",
978
+ ]]
979
+ let pairAndMenu = pair + [["kind": "menu", "actionKey": "menu"]]
980
+ let pairItem = try item(trailing: pair)
981
+ let pairHeight = try height(width: 240, item: pairItem)
982
+ XCTAssertGreaterThan(pairHeight, try height(width: 240, item: item(trailing: [])))
983
+ XCTAssertGreaterThanOrEqual(try height(width: 240, item: item(trailing: pairAndMenu)),
984
+ pairHeight)
985
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 240, height: pairHeight))
986
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 240, height: pairHeight))
987
+ window.addSubview(cell)
988
+ cell.bind(item: pairItem, theme: nil, layout: "linear", selected: false,
989
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
990
+ window.layoutIfNeeded()
991
+ cell.layoutIfNeeded()
992
+ let subtitleLabel = try XCTUnwrap(Mirror(reflecting: cell).children.first {
993
+ $0.label == "subtitleLabel"
994
+ }?.value as? UILabel)
995
+ XCTAssertGreaterThan(subtitleLabel.bounds.width, 0.5)
996
+ XCTAssertGreaterThanOrEqual(subtitleLabel.bounds.height + 0.5,
997
+ subtitleLabel.sizeThatFits(CGSize(
998
+ width: subtitleLabel.bounds.width, height: .greatestFiniteMagnitude)).height)
999
+ let accountIcon: [[String: Any]] = [[
1000
+ "kind": "icon", "name": "DotHorOutline", "actionKey": "menu",
1001
+ ]]
1002
+ XCTAssertGreaterThanOrEqual(
1003
+ try height(width: 220, item: item(trailing: accountIcon,
1004
+ horizontalPadding: 28, presentation: "accountSelector")),
1005
+ try height(width: 220, item: item(trailing: accountIcon,
1006
+ presentation: "accountSelector")))
1007
+ }
1008
+
156
1009
  func testFixedFooterReplacesRendererAndKeepsActionRouting() throws {
157
1010
  let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
158
1011
  var actions: [[String: Any]] = []
@@ -246,6 +1099,35 @@ final class NativeListLifecycleTests: XCTestCase {
246
1099
  XCTAssertEqual(footer.accessibilityLabel, "Continue")
247
1100
  }
248
1101
 
1102
+ func testPaddedSquareNetworkOverlayRoundsInnerImageAndResetsOnRebind() throws {
1103
+ let visual = NativeListLeadingVisual(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
1104
+ func bind(_ overlay: [String: Any]) {
1105
+ visual.bind(["kind": "token", "overlays": [overlay]], style: [:], key: "overlay",
1106
+ theme: nil, isUnread: false, fonts: NativeListFontFamilies())
1107
+ visual.layoutIfNeeded()
1108
+ }
1109
+ let image: [String: Any] = ["uri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9xvY0AAAAASUVORK5CYII="]
1110
+ bind(["position": "bottomRight", "size": 20, "width": 20, "height": 20,
1111
+ "padding": 2, "image": image, "fallbackIcon": ["name": "GlobusOutline"]])
1112
+ let slots = try XCTUnwrap(Mirror(reflecting: visual).children.first {
1113
+ $0.label == "overlaySlots"
1114
+ }?.value as? [NativeListImageSlot])
1115
+ let slot = try XCTUnwrap(slots.first?.view)
1116
+ XCTAssertEqual(slot.bounds.size, CGSize(width: 16, height: 16))
1117
+ XCTAssertEqual(slot.layer.cornerRadius, 8, accuracy: 0.5)
1118
+ XCTAssertTrue(slot.clipsToBounds)
1119
+ bind(["position": "bottomRight", "width": 20, "height": 14,
1120
+ "padding": 2, "image": image])
1121
+ XCTAssertEqual(slot.layer.cornerRadius, 0)
1122
+ XCTAssertFalse(slot.clipsToBounds)
1123
+ bind(["position": "bottomRight", "size": 20, "padding": 2, "text": "E"])
1124
+ XCTAssertEqual(slot.layer.cornerRadius, 0)
1125
+ XCTAssertFalse(slot.clipsToBounds)
1126
+ bind(["position": "bottomRight", "size": 20, "padding": 2, "image": image])
1127
+ XCTAssertEqual(slot.layer.cornerRadius, 8, accuracy: 0.5)
1128
+ visual.recycle()
1129
+ }
1130
+
249
1131
  func testNestedWalletMembersAndDragBadgeFollowEachBindMapping() throws {
250
1132
  let group = NativeListWalletGroupCell(frame: CGRect(x: 0, y: 0, width: 320, height: 200))
251
1133
  let item = try NativeListItem(data: [
@@ -346,9 +1228,11 @@ final class NativeListLifecycleTests: XCTestCase {
346
1228
  list.layoutIfNeeded()
347
1229
  let header = try XCTUnwrap(slots[0].superview)
348
1230
  XCTAssertTrue(header.clipsToBounds)
349
- XCTAssertEqual(header.bounds.height, 0, "An unmeasured header cannot draw over the first rows")
1231
+ XCTAssertEqual(header.bounds.height, 44, "The mounted Fabric header reserves its first-frame height")
1232
+ let firstRow = try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)))
1233
+ XCTAssertEqual(firstRow.frame.minY, 44, accuracy: 0.5)
350
1234
 
351
- view.setContainerSlotHeightsJson("[44,44,60]")
1235
+ view.setContainerSlotHeightsJson("[44,44,60,0]")
352
1236
  view.layoutIfNeeded()
353
1237
  list.layoutIfNeeded()
354
1238
  XCTAssertEqual(slots[0].convert(CGPoint.zero, to: list), CGPoint(x: 16, y: 0))
@@ -363,10 +1247,2081 @@ final class NativeListLifecycleTests: XCTestCase {
363
1247
  XCTAssertNil(slots[2].superview)
364
1248
  }
365
1249
 
1250
+ func testPendingHeaderReservesMountedGeometryInEitherPropertyOrder() throws {
1251
+ for pendingBeforeMount in [true, false] {
1252
+ let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
1253
+ view.applySnapshotJson(try scrollingSnapshot(count: 3))
1254
+ let header = UIView(frame: CGRect(x: 16, y: 0, width: 288, height: 44.2))
1255
+ if pendingBeforeMount { view.setContainerSlotHeightsJson("[null,0,0,0,0,0]") }
1256
+ view.mountContainerSlot(header, atIndex: 0)
1257
+ if !pendingBeforeMount { view.setContainerSlotHeightsJson("[null,0,0,0,0,0]") }
1258
+ view.layoutIfNeeded()
1259
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1260
+ list.layoutIfNeeded()
1261
+ let host = try XCTUnwrap(header.superview)
1262
+ XCTAssertTrue(host.clipsToBounds)
1263
+ XCTAssertEqual(host.bounds.height, 45, accuracy: 0.5)
1264
+ let firstRow = try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)))
1265
+ XCTAssertEqual(firstRow.frame.minY, 45, accuracy: 0.5)
1266
+
1267
+ view.setContainerSlotHeightsJson("[null,0,18,0,0,0]")
1268
+ view.layoutIfNeeded()
1269
+ list.layoutIfNeeded()
1270
+ XCTAssertEqual(host.bounds.height, 45, accuracy: 0.5)
1271
+ XCTAssertEqual(list.layoutAttributesForItem(
1272
+ at: IndexPath(item: 0, section: 0))?.frame.minY, 45)
1273
+
1274
+ view.setContainerSlotHeightsJson("[18,0,0,0,0,0]")
1275
+ view.layoutIfNeeded()
1276
+ list.layoutIfNeeded()
1277
+ XCTAssertEqual(host.bounds.height, 18, accuracy: 0.5)
1278
+ XCTAssertEqual(list.collectionViewLayout.layoutAttributesForItem(
1279
+ at: IndexPath(item: 0, section: 0))?.frame.minY, 18)
1280
+ view.setContainerSlotHeightsJson("[0,0,0,0,0,0]")
1281
+ view.layoutIfNeeded()
1282
+ list.layoutIfNeeded()
1283
+ XCTAssertEqual(host.bounds.height, 0)
1284
+ XCTAssertEqual(list.collectionViewLayout.layoutAttributesForItem(
1285
+ at: IndexPath(item: 0, section: 0))?.frame.minY, 0)
1286
+ view.dispose()
1287
+ }
1288
+ }
1289
+
1290
+ func testNumericHeaderHeightIsAuthoritativeBeforeRootMounts() throws {
1291
+ for height in [0, 24] {
1292
+ let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
1293
+ view.setContainerSlotHeightsJson("[\(height),0,0,0]")
1294
+ view.applySnapshotJson(try scrollingSnapshot(count: 3))
1295
+ let header = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
1296
+ view.mountContainerSlot(header, atIndex: 0)
1297
+ view.layoutIfNeeded()
1298
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1299
+ list.layoutIfNeeded()
1300
+ XCTAssertEqual(header.superview?.bounds.height, CGFloat(height))
1301
+ XCTAssertEqual(list.layoutAttributesForItem(
1302
+ at: IndexPath(item: 0, section: 0))?.frame.minY, CGFloat(height))
1303
+ view.dispose()
1304
+ }
1305
+ }
1306
+
1307
+ func testPendingHeaderDoesNotInheritAnUnmountedRootsHeight() throws {
1308
+ let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
1309
+ view.applySnapshotJson(try scrollingSnapshot(count: 3))
1310
+ view.setContainerSlotHeightsJson("[null,0,0,0,0,0]")
1311
+ let first = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
1312
+ view.mountContainerSlot(first, atIndex: 0)
1313
+ XCTAssertEqual(first.superview?.bounds.height, 44)
1314
+ view.unmountContainerSlot(first)
1315
+ let empty = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 0))
1316
+ view.mountContainerSlot(empty, atIndex: 0)
1317
+ XCTAssertEqual(empty.superview?.bounds.height, 0)
1318
+ view.unmountContainerSlot(empty)
1319
+ let replacement = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 27))
1320
+ view.mountContainerSlot(replacement, atIndex: 0)
1321
+ XCTAssertEqual(replacement.superview?.bounds.height, 27)
1322
+ view.setContainerSlotHeightsJson("[0,0,0,0,0,0]")
1323
+ view.unmountContainerSlot(replacement)
1324
+ let authoritativeZero = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 60))
1325
+ view.mountContainerSlot(authoritativeZero, atIndex: 0)
1326
+ XCTAssertEqual(authoritativeZero.superview?.bounds.height, 0)
1327
+ view.dispose()
1328
+ }
1329
+
1330
+ func testPendingHeaderOnlyAcceptsNullAtTheHeaderSlot() throws {
1331
+ let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
1332
+ view.setContainerSlotHeightsJson("[24,0,0,0,0,0]")
1333
+ let header = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
1334
+ view.mountContainerSlot(header, atIndex: 0)
1335
+ for invalid in ["[null,null,0,0,0,0]", "[\"invalid\",0,0,0,0,0]",
1336
+ "[null,0,0,0,-1,0]", "[null,0,0,0,0,null]"] {
1337
+ view.setContainerSlotHeightsJson(invalid)
1338
+ XCTAssertEqual(header.superview?.bounds.height, 24)
1339
+ }
1340
+ view.dispose()
1341
+ }
1342
+
1343
+ func testFirstUsableBoundsNotifiesPagerBeforeSlotLayout() throws {
1344
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844))
1345
+ let root = UIViewController()
1346
+ window.rootViewController = root
1347
+ window.isHidden = false
1348
+ let view = NativeListView(frame: .zero)
1349
+ root.view.addSubview(view)
1350
+ defer {
1351
+ view.dispose()
1352
+ view.removeFromSuperview()
1353
+ window.rootViewController = nil
1354
+ window.isHidden = true
1355
+ }
1356
+
1357
+ let header = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 65))
1358
+ view.mountContainerSlot(header, atIndex: 0)
1359
+ view.setContainerSlotHeightsJson("[65,0,0,0,0,0]")
1360
+ view.applySnapshotJson(try scrollingSnapshot(count: 6))
1361
+
1362
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1363
+ let owner = NSObject()
1364
+ var readyCount = 0
1365
+ let observer = NotificationCenter.default.addObserver(
1366
+ forName: Notification.Name("OneKeyNativeScrollViewDidBecomeReady"),
1367
+ object: list,
1368
+ queue: nil
1369
+ ) { _ in
1370
+ readyCount += 1
1371
+ view.setPagerStickyHeight(52, forOwner: owner)
1372
+ list.contentInset = UIEdgeInsets(top: 345, left: 0, bottom: 0, right: 0)
1373
+ list.setContentOffset(CGPoint(x: 0, y: -345), animated: false)
1374
+ }
1375
+ defer { NotificationCenter.default.removeObserver(observer) }
1376
+
1377
+ view.frame = CGRect(x: 0, y: 0, width: 390, height: 697)
1378
+ view.layoutIfNeeded()
1379
+
1380
+ let host = try XCTUnwrap(header.superview)
1381
+ XCTAssertEqual(readyCount, 1)
1382
+ XCTAssertEqual(list.contentInset.top, 345, accuracy: 0.01)
1383
+ XCTAssertEqual(list.contentOffset.y, -345, accuracy: 0.01)
1384
+ XCTAssertNil(host.layer.mask)
1385
+ }
1386
+
1387
+ func testSidecarCentersRowsWhenConfiguredBeforeFirstWidth() throws {
1388
+ try assertHomeSidecarGeometry(sidecarBeforeFirstLayout: true)
1389
+ }
1390
+
1391
+ func testSidecarCentersRowsWhenConfiguredAfterFirstWidth() throws {
1392
+ try assertHomeSidecarGeometry(sidecarBeforeFirstLayout: false)
1393
+ }
1394
+
1395
+ func testHomeLinearColumnsStayInsideTheirStackAcrossEmptyMiddleAndReuse() throws {
1396
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 900))
1397
+ let controller = UIViewController()
1398
+ window.rootViewController = controller
1399
+ let view = NativeListView(frame: window.bounds)
1400
+ controller.view.addSubview(view)
1401
+ window.isHidden = false
1402
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1403
+ defer {
1404
+ view.dispose()
1405
+ view.removeFromSuperview()
1406
+ window.isHidden = true
1407
+ window.rootViewController = nil
1408
+ }
1409
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
1410
+ view.setContainerSlotHeightsJson("[0,0,0,1200]")
1411
+ let sidecar = "{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}"
1412
+ view.setSidecarLayoutJson(sidecar)
1413
+
1414
+ func columns(middle: String?, two: Bool = false) -> [[String: Any]] {
1415
+ let first: [String: Any] = ["key": "asset", "text": "USD1",
1416
+ "secondaryText": "Public fixture", "weight": 1]
1417
+ let balance: [String: Any] = ["key": "balance", "text": middle ?? "",
1418
+ "secondaryText": middle == nil ? "" : "$0.01", "alignment": "end", "weight": 1]
1419
+ let price: [String: Any] = ["key": "price", "text": "$1.00",
1420
+ "secondaryText": "0.01%", "alignment": "end", "weight": 1]
1421
+ return two ? [first, price] : [first, balance, price]
1422
+ }
1423
+ let rows: [[String: Any]] = (0..<30).map { index in
1424
+ ["key": "row-\(index)", "type": "dataRow", "height": 60,
1425
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
1426
+ "columns": index == 20 ? columns(middle: "0.01") : homeSidecarColumns(index, updated: false),
1427
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]],
1428
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
1429
+ "columns": ["token": "$bodyLg", "fontWeight": "medium", "lines": 1],
1430
+ "columnSecondary": ["token": "$bodyMd", "lines": 1],
1431
+ "image": ["width": 32, "height": 32]]]
1432
+ }
1433
+ let snapshot: [String: Any] = ["schemaVersion": 1, "generation": 1,
1434
+ "layout": ["kind": "linear", "contentPaddingHorizontal": 8], "rows": rows]
1435
+ view.applySnapshotJson(String(decoding: try JSONSerialization.data(withJSONObject: snapshot),
1436
+ as: UTF8.self))
1437
+ list.contentInsetAdjustmentBehavior = .never
1438
+ func layout() {
1439
+ window.layoutIfNeeded()
1440
+ view.layoutIfNeeded()
1441
+ list.layoutIfNeeded()
1442
+ }
1443
+ func check(_ phase: String, count: Int, width: CGFloat, weights: [Int]? = nil) throws {
1444
+ layout()
1445
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1446
+ as? NativeListDataRowCell, phase)
1447
+ let stack = try XCTUnwrap(cell.root.arrangedSubviews[3] as? UIStackView, phase)
1448
+ let visible = stack.arrangedSubviews.filter { !$0.isHidden }
1449
+ XCTAssertEqual(stack.arrangedSubviews.count, 4, phase)
1450
+ XCTAssertEqual(stack.arrangedSubviews.map(\.isHidden),
1451
+ (0..<4).map { $0 >= count }, phase)
1452
+ XCTAssertEqual(visible.count, count, phase)
1453
+ let cellFrame = cell.convert(cell.bounds, to: list)
1454
+ let stackFrame = stack.convert(stack.bounds, to: list)
1455
+ let attributes = try XCTUnwrap(list.layoutAttributesForItem(
1456
+ at: IndexPath(item: 20, section: 0)), phase)
1457
+ XCTAssertEqual(attributes.frame.width, width, accuracy: 1, phase)
1458
+ XCTAssertEqual(cellFrame.width, width, accuracy: 1,
1459
+ "\(phase) window=\(window.frame) controller=\(controller.view.frame) view=\(view.frame) list=\(list.frame) bounds=\(list.bounds) attributes=\(attributes.frame)")
1460
+ let rowConstraints = Mirror(reflecting: cell).children.first {
1461
+ $0.label == "rowConstraints"
1462
+ }?.value as? [NSLayoutConstraint] ?? []
1463
+ let columnWidthConstraints = Mirror(reflecting: cell).children.first {
1464
+ $0.label == "columnWidthConstraints"
1465
+ }?.value as? [NSLayoutConstraint] ?? []
1466
+ let constraints = rowConstraints + columnWidthConstraints
1467
+ let constraintState = constraints.map { constraint in
1468
+ let first = stack.arrangedSubviews.firstIndex {
1469
+ $0 === constraint.firstItem as? UIView
1470
+ } ?? -1
1471
+ let second = stack.arrangedSubviews.firstIndex {
1472
+ $0 === constraint.secondItem as? UIView
1473
+ } ?? -1
1474
+ return "\(first):\(second):\(constraint.multiplier):\(constraint.isActive)"
1475
+ }.joined(separator: ",")
1476
+ let hidingState = stack.arrangedSubviews.enumerated().map { index, column in
1477
+ let hiding = (stack.constraints + column.constraints).filter {
1478
+ $0.isActive && $0.identifier == "UISV-hiding"
1479
+ }.map { "\($0.constant)" }.joined(separator: ",")
1480
+ return "\(index):\(column.isHidden):\(hiding)"
1481
+ }.joined(separator: ",")
1482
+ let geometry = "\(phase) model=\(count) cell=\(cellFrame) stack=\(stackFrame) "
1483
+ + "columns=\(stack.arrangedSubviews.map { "\($0.isHidden):\($0.convert($0.bounds, to: list))" }) "
1484
+ + "constraints=\(constraintState) hiding=\(hidingState)"
1485
+ XCTAssertGreaterThanOrEqual(stackFrame.minX, cellFrame.minX - 0.5, geometry)
1486
+ XCTAssertLessThanOrEqual(stackFrame.maxX, cellFrame.maxX + 0.5, geometry)
1487
+ for column in visible {
1488
+ let columnFrame = column.convert(column.bounds, to: list)
1489
+ XCTAssertGreaterThan(columnFrame.width, 0, geometry)
1490
+ XCTAssertGreaterThanOrEqual(columnFrame.minX, stackFrame.minX - 0.5, geometry)
1491
+ XCTAssertLessThanOrEqual(columnFrame.maxX, stackFrame.maxX + 0.5, geometry)
1492
+ let primaryLine = (column as? UIStackView)?.arrangedSubviews.first
1493
+ if let primaryLine {
1494
+ let lineFrame = primaryLine.convert(primaryLine.bounds, to: list)
1495
+ XCTAssertGreaterThanOrEqual(lineFrame.minX, columnFrame.minX - 0.5, geometry)
1496
+ XCTAssertLessThanOrEqual(lineFrame.maxX, columnFrame.maxX + 0.5, geometry)
1497
+ }
1498
+ for label in labels(in: column) where !label.isHidden {
1499
+ let labelFrame = label.convert(label.bounds, to: list)
1500
+ XCTAssertGreaterThanOrEqual(labelFrame.minX, columnFrame.minX - 0.5,
1501
+ "\(geometry) label=\(labelFrame)")
1502
+ XCTAssertLessThanOrEqual(labelFrame.maxX, columnFrame.maxX + 0.5,
1503
+ "\(geometry) label=\(labelFrame)")
1504
+ }
1505
+ }
1506
+ if count >= 2 {
1507
+ let expectedWeights = weights ?? Array(repeating: 1, count: count)
1508
+ XCTAssertEqual(expectedWeights.count, count, geometry)
1509
+ for index in 1..<count {
1510
+ XCTAssertEqual(visible[index].bounds.width,
1511
+ visible[0].bounds.width * CGFloat(expectedWeights[index])
1512
+ / CGFloat(expectedWeights[0]),
1513
+ accuracy: 1, geometry)
1514
+ let previous = visible[index - 1].convert(visible[index - 1].bounds, to: stack)
1515
+ let current = visible[index].convert(visible[index].bounds, to: stack)
1516
+ XCTAssertGreaterThanOrEqual(current.minX, previous.maxX - 0.5, geometry)
1517
+ XCTAssertEqual(current.minX - previous.maxX, stack.spacing,
1518
+ accuracy: 0.5, geometry)
1519
+ }
1520
+ }
1521
+ }
1522
+ func patch(_ next: [[String: Any]]) throws {
1523
+ let patches: [[String: Any]] = [["key": "row-20", "type": "dataRow",
1524
+ "changes": ["columns": next]]]
1525
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patches),
1526
+ as: UTF8.self))
1527
+ }
1528
+ func widthConstraints() throws -> [NSLayoutConstraint] {
1529
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1530
+ as? NativeListDataRowCell)
1531
+ return try XCTUnwrap(Mirror(reflecting: cell).children.first {
1532
+ $0.label == "columnWidthConstraints"
1533
+ }?.value as? [NSLayoutConstraint])
1534
+ }
1535
+ func sizeConstraints() throws -> [NSLayoutConstraint] {
1536
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1537
+ as? NativeListDataRowCell)
1538
+ return try XCTUnwrap(Mirror(reflecting: cell).children.first {
1539
+ $0.label == "rowConstraints"
1540
+ }?.value as? [NSLayoutConstraint])
1541
+ }
1542
+ layout()
1543
+ list.setContentOffset(CGPoint(x: 0, y: 18 * 60), animated: false)
1544
+ try check("three populated", count: 3, width: 700)
1545
+ try patch(columns(middle: nil))
1546
+ try check("three empty middle", count: 3, width: 700)
1547
+ try patch(columns(middle: "0.02"))
1548
+ try check("three restored", count: 3, width: 700)
1549
+ try patch(columns(middle: nil, two: true))
1550
+ try check("two columns", count: 2, width: 700)
1551
+ try patch(columns(middle: nil))
1552
+ try check("three after two", count: 3, width: 700)
1553
+ let stableConstraints = try widthConstraints()
1554
+ let stableSizeConstraints = try sizeConstraints()
1555
+ XCTAssertEqual(stableConstraints.count, 2)
1556
+ XCTAssertEqual(stableSizeConstraints.count, 4)
1557
+ for update in 0..<10 {
1558
+ var next = columns(middle: nil)
1559
+ next[2]["text"] = "$1.\(update)"
1560
+ try patch(next)
1561
+ try check("same-shape price \(update)", count: 3, width: 700)
1562
+ let retained = try widthConstraints()
1563
+ XCTAssertEqual(retained.count, stableConstraints.count)
1564
+ XCTAssertTrue(zip(stableConstraints, retained).allSatisfy { $0 === $1 })
1565
+ XCTAssertTrue(retained.allSatisfy(\.isActive))
1566
+ let size = try sizeConstraints()
1567
+ XCTAssertEqual(size.count, stableSizeConstraints.count)
1568
+ XCTAssertTrue(zip(stableSizeConstraints, size).allSatisfy { $0 === $1 })
1569
+ XCTAssertTrue(size.allSatisfy(\.isActive))
1570
+ }
1571
+ var equivalentWeights = columns(middle: nil)
1572
+ for index in equivalentWeights.indices { equivalentWeights[index]["weight"] = 2 }
1573
+ try patch(equivalentWeights)
1574
+ try check("equivalent weights", count: 3, width: 700, weights: [2, 2, 2])
1575
+ let equivalentConstraints = try widthConstraints()
1576
+ XCTAssertEqual(equivalentConstraints.count, stableConstraints.count)
1577
+ XCTAssertTrue(zip(stableConstraints, equivalentConstraints).allSatisfy { $0 === $1 })
1578
+ var unequalWeights = columns(middle: nil)
1579
+ unequalWeights[0]["weight"] = 2
1580
+ try patch(unequalWeights)
1581
+ try check("unequal weights", count: 3, width: 700, weights: [2, 1, 1])
1582
+ let unequalConstraints = try widthConstraints()
1583
+ XCTAssertEqual(unequalConstraints.count, 2)
1584
+ XCTAssertTrue(stableConstraints.allSatisfy { !$0.isActive })
1585
+ try patch(columns(middle: nil, two: true))
1586
+ try check("two after weights", count: 2, width: 700)
1587
+ let twoConstraints = try widthConstraints()
1588
+ XCTAssertEqual(twoConstraints.count, 1)
1589
+ XCTAssertTrue(unequalConstraints.allSatisfy { !$0.isActive })
1590
+ try patch([])
1591
+ try check("zero columns", count: 0, width: 700)
1592
+ XCTAssertTrue((try widthConstraints()).isEmpty)
1593
+ XCTAssertTrue(twoConstraints.allSatisfy { !$0.isActive })
1594
+ try patch(columns(middle: nil))
1595
+ try check("three after zero", count: 3, width: 700)
1596
+ list.setContentOffset(.zero, animated: false)
1597
+ layout()
1598
+ XCTAssertFalse(list.indexPathsForVisibleItems.contains(IndexPath(item: 20, section: 0)))
1599
+ list.setContentOffset(CGPoint(x: 0, y: 18 * 60), animated: false)
1600
+ try check("after scroll reuse", count: 3, width: 700)
1601
+ window.frame.size.width = 1032
1602
+ controller.view.frame = window.bounds
1603
+ view.frame = window.bounds
1604
+ view.setSidecarLayoutJson("")
1605
+ drainMainQueue()
1606
+ try check("narrow no sidecar", count: 3, width: 1016)
1607
+ window.frame.size.width = 1376
1608
+ controller.view.frame = window.bounds
1609
+ view.frame = window.bounds
1610
+ view.setSidecarLayoutJson(sidecar)
1611
+ drainMainQueue()
1612
+ try check("wide sidecar restored", count: 3, width: 700)
1613
+ func animatedPatch(_ next: [[String: Any]], phase: String, count: Int) throws {
1614
+ let patches: [[String: Any]] = [["key": "row-20", "type": "dataRow",
1615
+ "changes": ["columns": next]]]
1616
+ let json = String(decoding: try JSONSerialization.data(withJSONObject: patches), as: UTF8.self)
1617
+ let finished = expectation(description: "Home column animation: \(phase)")
1618
+ UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState) {
1619
+ view.applyPatchesJson(json)
1620
+ view.layoutIfNeeded()
1621
+ list.layoutIfNeeded()
1622
+ } completion: { _ in finished.fulfill() }
1623
+ wait(for: [finished], timeout: 1)
1624
+ try check(phase, count: count, width: 700)
1625
+ waitForStructuralFrames(0.1)
1626
+ try check("\(phase) stable", count: count, width: 700)
1627
+ }
1628
+ try animatedPatch(columns(middle: nil, two: true), phase: "animated two", count: 2)
1629
+ try animatedPatch(columns(middle: nil), phase: "animated three", count: 3)
1630
+ try animatedPatch(columns(middle: "0.06"), phase: "animated nonempty", count: 3)
1631
+ }
1632
+
1633
+ func testStructuralShrinkUsesTheTallerFinalColumnForOffsetClamping() throws {
1634
+ let cases: [(name: String, sidecar: Int, offset: CGFloat, height: CGFloat,
1635
+ zeroInset: Bool)] = [
1636
+ ("sidecar stays taller", 2200, 1450, 2200, false),
1637
+ ("left column stays taller", 1000, 1100, 1560, false),
1638
+ ("left column zero inset", 1000, 1100, 1560, true),
1639
+ ("sidecar becomes taller", 1700, 1050, 1700, false),
1640
+ ]
1641
+ for testCase in cases {
1642
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
1643
+ let controller = UIViewController()
1644
+ window.rootViewController = controller
1645
+ let view = NativeListView(frame: window.bounds)
1646
+ controller.view.addSubview(view)
1647
+ window.isHidden = false
1648
+ defer {
1649
+ view.dispose()
1650
+ view.removeFromSuperview()
1651
+ window.isHidden = true
1652
+ window.rootViewController = nil
1653
+ }
1654
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1655
+ // Keep the viewport insets fixed while testing structural offset clamping.
1656
+ let explicitInset = testCase.zeroInset ? UIEdgeInsets.zero :
1657
+ UIEdgeInsets(top: 62, left: 0, bottom: 34, right: 0)
1658
+ list.contentInsetAdjustmentBehavior = .never
1659
+ list.contentInset = explicitInset
1660
+ view.mountContainerSlot(UIView(), atIndex: 0)
1661
+ view.mountContainerSlot(UIView(), atIndex: 1)
1662
+ let footer = UIView()
1663
+ view.mountContainerSlot(footer, atIndex: 2)
1664
+ let sidecar = UIView()
1665
+ view.mountContainerSlot(sidecar, atIndex: 3)
1666
+ view.setContainerSlotHeightsJson("[0,0,60,\(testCase.sidecar)]")
1667
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
1668
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30))
1669
+ view.layoutIfNeeded()
1670
+ list.layoutIfNeeded()
1671
+ drainMainQueue()
1672
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1673
+ XCTAssertEqual(list.contentSize.height, max(1860, CGFloat(testCase.sidecar)),
1674
+ accuracy: 1, testCase.name)
1675
+ list.contentOffset.y = testCase.offset
1676
+ list.layoutIfNeeded()
1677
+ XCTAssertEqual(list.contentOffset.y, testCase.offset, accuracy: 1, testCase.name)
1678
+
1679
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, transitionID: testCase.name))
1680
+ let completed = expectation(description: "Native structural display link: \(testCase.name)")
1681
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { completed.fulfill() }
1682
+ wait(for: [completed], timeout: 1)
1683
+ list.layoutIfNeeded()
1684
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1685
+ XCTAssertEqual(list.contentSize.height, testCase.height, accuracy: 1, testCase.name)
1686
+ let inset = list.adjustedContentInset
1687
+ let finalMaximum = max(-inset.top, testCase.height - list.bounds.height + inset.bottom)
1688
+ let footerTop: CGFloat = 1500
1689
+ let footerBottom: CGFloat = footerTop + 60
1690
+ let footerVisibleMinimum = footerBottom - list.bounds.height + inset.bottom
1691
+ let footerVisibleMaximum = footerTop - inset.top
1692
+ let expectedOffset = min(max(testCase.offset, footerVisibleMinimum),
1693
+ min(footerVisibleMaximum, finalMaximum))
1694
+ XCTAssertEqual(list.contentOffset.y, expectedOffset, accuracy: 1, testCase.name)
1695
+ XCTAssertNotNil(sidecar.superview, testCase.name)
1696
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1500, accuracy: 1, testCase.name)
1697
+ waitForStructuralFrames(0.1)
1698
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1699
+ XCTAssertEqual(list.contentSize.height, testCase.height, accuracy: 1, testCase.name)
1700
+ XCTAssertEqual(list.contentOffset.y, expectedOffset, accuracy: 1, testCase.name)
1701
+ }
1702
+ }
1703
+
1704
+ func testStructuralTransitionFromGridOrHorizontalCommitsAtomically() throws {
1705
+ try requireStructuralAnimation()
1706
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 600))
1707
+ let controller = UIViewController()
1708
+ window.rootViewController = controller
1709
+ let view = NativeListView(frame: window.bounds)
1710
+ controller.view.addSubview(view)
1711
+ window.isHidden = false
1712
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1713
+ defer {
1714
+ view.dispose()
1715
+ view.removeFromSuperview()
1716
+ window.isHidden = true
1717
+ window.rootViewController = nil
1718
+ }
1719
+ view.applySnapshotJson(try structuralRowsSnapshot(
1720
+ count: 6, generation: 1, layoutKind: "grid"))
1721
+ view.layoutIfNeeded()
1722
+ view.applySnapshotJson(try structuralRowsSnapshot(
1723
+ count: 8, generation: 2, transitionID: "from-grid", layoutKind: "linear"))
1724
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1725
+ XCTAssertEqual(list.numberOfItems(inSection: 0), 8)
1726
+
1727
+ view.applySnapshotJson(try structuralRowsSnapshot(
1728
+ count: 6, generation: 3, orientation: "horizontal"))
1729
+ view.layoutIfNeeded()
1730
+ view.applySnapshotJson(try structuralRowsSnapshot(
1731
+ count: 8, generation: 4, transitionID: "from-horizontal", layoutKind: "table"))
1732
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1733
+ XCTAssertEqual(list.numberOfItems(inSection: 0), 8)
1734
+ }
1735
+
1736
+ func testVisibleNativeCellsRemainBoundedAsRowsGrowTenfold() throws {
1737
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1738
+ let controller = UIViewController()
1739
+ window.rootViewController = controller
1740
+ let view = NativeListView(frame: window.bounds)
1741
+ controller.view.addSubview(view)
1742
+ window.isHidden = false
1743
+ defer {
1744
+ view.dispose()
1745
+ view.removeFromSuperview()
1746
+ window.isHidden = true
1747
+ window.rootViewController = nil
1748
+ }
1749
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1750
+ // Measure renderer reuse without UIKit's timing-dependent speculative prefetch cells.
1751
+ list.isPrefetchingEnabled = false
1752
+ func sampleCells(count: Int) throws -> [(visible: Int, attached: Int)] {
1753
+ view.applySnapshotJson(try structuralRowsSnapshot(count: count))
1754
+ view.layoutIfNeeded()
1755
+ list.layoutIfNeeded()
1756
+ let lastOffset = CGFloat(count * 60 - 600)
1757
+ return [CGFloat(0), lastOffset / 2, lastOffset].map { offset in
1758
+ list.setContentOffset(CGPoint(x: 0, y: offset), animated: false)
1759
+ list.layoutIfNeeded()
1760
+ drainMainQueue()
1761
+ list.layoutIfNeeded()
1762
+ return (list.visibleCells.count,
1763
+ list.subviews.compactMap { $0 as? NativeListRowHost }.count)
1764
+ }
1765
+ }
1766
+ let hundredCells = try sampleCells(count: 100)
1767
+ let thousandCells = try sampleCells(count: 1000)
1768
+ print("NativeList 100 visible/attached first/mid/tail: \(hundredCells)")
1769
+ print("NativeList 1000 visible/attached first/mid/tail: \(thousandCells)")
1770
+ let visibleCellLimit = Int(ceil(list.bounds.height / 60)) + 2
1771
+ XCTAssertTrue(hundredCells.allSatisfy {
1772
+ $0.visible > 0 && $0.visible <= visibleCellLimit && $0.attached >= $0.visible
1773
+ })
1774
+ XCTAssertTrue(thousandCells.allSatisfy {
1775
+ $0.visible > 0 && $0.visible <= visibleCellLimit && $0.attached >= $0.visible
1776
+ })
1777
+ // UIKit also retains offscreen cells in subviews. Their count may exceed
1778
+ // the visible budget, but must remain bounded as the data grows tenfold.
1779
+ XCTAssertLessThanOrEqual(thousandCells.map(\.attached).max() ?? 0,
1780
+ (hundredCells.map(\.attached).max() ?? 0) + 4)
1781
+ }
1782
+
1783
+ func testStructuralTransitionRapidReversalKeepsRetiringContentAtNaturalHeight() throws {
1784
+ try requireStructuralAnimation()
1785
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1786
+ let controller = UIViewController()
1787
+ window.rootViewController = controller
1788
+ let view = NativeListView(frame: window.bounds)
1789
+ controller.view.addSubview(view)
1790
+ window.isHidden = false
1791
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
1792
+ let footer = UIView()
1793
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
1794
+ view.mountContainerSlot(footer, atIndex: 2)
1795
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
1796
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 1))
1797
+ view.layoutIfNeeded()
1798
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1799
+ list.layoutIfNeeded()
1800
+ drainMainQueue()
1801
+ list.contentOffset.y = 900
1802
+ list.layoutIfNeeded()
1803
+
1804
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 2,
1805
+ transitionID: "expand-first", durationMs: 400))
1806
+ waitForStructuralFrames(0.08)
1807
+ list.contentOffset.y = 1100
1808
+ list.layoutIfNeeded()
1809
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 3,
1810
+ transitionID: "collapse-middle", durationMs: 400))
1811
+ waitForStructuralFrames(0.08)
1812
+ list.layoutIfNeeded()
1813
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
1814
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
1815
+ let clip = try XCTUnwrap(flow.tailClip)
1816
+ let retiring = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 25, section: 0)) as? NativeListRowHost)
1817
+ XCTAssertGreaterThan(clip.endY, 1500)
1818
+ XCTAssertLessThan(clip.endY, 1800)
1819
+ XCTAssertEqual(retiring.bounds.height, 60, accuracy: 1)
1820
+ XCTAssertEqual(retiring.contentView.bounds.height, 60, accuracy: 1)
1821
+ XCTAssertNil(retiring.structuralContentHeight)
1822
+ XCTAssertEqual(retiring.alpha, 1, accuracy: 0.01)
1823
+ XCTAssertFalse(retiring.isUserInteractionEnabled)
1824
+ XCTAssertTrue(retiring.accessibilityElementsHidden)
1825
+ XCTAssertEqual(footer.convert(.zero, to: list).y,
1826
+ clip.endY, accuracy: 1)
1827
+
1828
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 4,
1829
+ transitionID: "expand-last", durationMs: 400))
1830
+ waitForStructuralFrames(0.5)
1831
+ list.layoutIfNeeded()
1832
+ let keys = source.snapshot().itemIdentifiers
1833
+ XCTAssertEqual(keys, (0..<30).map { "row-\($0)" })
1834
+ XCTAssertEqual(Set(keys).count, 30)
1835
+ XCTAssertEqual(list.contentSize.height, 1860, accuracy: 1)
1836
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1800, accuracy: 1)
1837
+ XCTAssertGreaterThanOrEqual(list.contentOffset.y, -list.adjustedContentInset.top - 1)
1838
+ XCTAssertLessThanOrEqual(list.contentOffset.y,
1839
+ list.contentSize.height - list.bounds.height + list.adjustedContentInset.bottom + 1)
1840
+ for case let cell as NativeListRowHost in list.visibleCells {
1841
+ XCTAssertEqual(cell.alpha, 1, accuracy: 0.01)
1842
+ XCTAssertNil(cell.structuralContentHeight)
1843
+ }
1844
+ }
1845
+
1846
+ func testHybridSettlementListenerFollowsRegistration() throws {
1847
+ let hybrid = HybridNativeList()
1848
+ let host = try XCTUnwrap(hybrid.view as? NativeListView)
1849
+ var first: [String] = []
1850
+ var second: [String] = []
1851
+ XCTAssertNil(host.onStructuralTransitionSettled)
1852
+
1853
+ hybrid.onStructuralTransitionSettled = { first.append($0) }
1854
+ host.onStructuralTransitionSettled?("first")
1855
+ XCTAssertEqual(first, ["first"])
1856
+
1857
+ hybrid.onStructuralTransitionSettled = { second.append($0) }
1858
+ host.onStructuralTransitionSettled?("second")
1859
+ XCTAssertEqual(first, ["first"])
1860
+ XCTAssertEqual(second, ["second"])
1861
+
1862
+ hybrid.onStructuralTransitionSettled = nil
1863
+ XCTAssertNil(host.onStructuralTransitionSettled)
1864
+ hybrid.dispose()
1865
+ }
1866
+
1867
+ func testDisclosureWithoutListenerStillSettlesWithoutReplay() throws {
1868
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1869
+ let controller = UIViewController()
1870
+ window.rootViewController = controller
1871
+ let view = NativeListView(frame: window.bounds)
1872
+ controller.view.addSubview(view)
1873
+ window.isHidden = false
1874
+ defer {
1875
+ view.dispose()
1876
+ view.removeFromSuperview()
1877
+ window.isHidden = true
1878
+ window.rootViewController = nil
1879
+ }
1880
+ for index in 0..<6 { view.mountContainerSlot(UIView(), atIndex: index) }
1881
+ view.setContainerSlotHeightsJson("[0,0,60,0,100,40]")
1882
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1883
+ disclosureExpanded: false))
1884
+ view.layoutIfNeeded()
1885
+
1886
+ let first = try structuralRowsSnapshot(count: 6, generation: 2,
1887
+ transitionID: "without-listener", durationMs: 0, disclosureExpanded: true)
1888
+ view.applySnapshotJson(first)
1889
+ drainMainQueue()
1890
+ XCTAssertEqual(Mirror(reflecting: view).descendant("pendingDisclosureSettlement")
1891
+ .map { Mirror(reflecting: $0).children.count }, 0)
1892
+
1893
+ var settlements: [[String: Any]] = []
1894
+ view.onStructuralTransitionSettled = { payload in
1895
+ guard let data = payload.data(using: .utf8),
1896
+ let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1897
+ return
1898
+ }
1899
+ settlements.append(value)
1900
+ }
1901
+ view.applySnapshotJson(first)
1902
+ drainMainQueue()
1903
+ XCTAssertTrue(settlements.isEmpty)
1904
+
1905
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
1906
+ transitionID: "with-listener", durationMs: 0, disclosureExpanded: false))
1907
+ drainMainQueue()
1908
+ XCTAssertEqual(settlements.count, 1)
1909
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "with-listener")
1910
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
1911
+ }
1912
+
1913
+ func testDisclosureInitialEndpoints() throws {
1914
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1915
+ let controller = UIViewController()
1916
+ window.rootViewController = controller
1917
+ let view = NativeListView(frame: window.bounds)
1918
+ controller.view.addSubview(view)
1919
+ window.isHidden = false
1920
+ defer {
1921
+ view.dispose()
1922
+ view.removeFromSuperview()
1923
+ window.isHidden = true
1924
+ window.rootViewController = nil
1925
+ }
1926
+ let slots = (0..<6).map { _ in UIView() }
1927
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
1928
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1929
+ var settlements: [String] = []
1930
+ view.onStructuralTransitionSettled = { settlements.append($0) }
1931
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1932
+ list.contentInsetAdjustmentBehavior = .never
1933
+ list.contentInset = .zero
1934
+
1935
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1936
+ disclosureExpanded: false))
1937
+ view.layoutIfNeeded()
1938
+ list.layoutIfNeeded()
1939
+ let footerHost = try XCTUnwrap(slots[2].superview)
1940
+ let contentHost = try XCTUnwrap(slots[4].superview)
1941
+ let toggleHost = try XCTUnwrap(slots[5].superview)
1942
+ XCTAssertEqual(contentHost.frame.minY, 360, accuracy: 1)
1943
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1944
+ XCTAssertTrue(contentHost.isHidden)
1945
+ XCTAssertFalse(contentHost.isUserInteractionEnabled)
1946
+ XCTAssertTrue(contentHost.accessibilityElementsHidden)
1947
+ XCTAssertEqual(toggleHost.frame.minY, 360, accuracy: 1)
1948
+ XCTAssertEqual(footerHost.frame.minY, 400, accuracy: 1)
1949
+ XCTAssertEqual(list.contentSize.height, 540, accuracy: 1)
1950
+ XCTAssertTrue(toggleHost.point(inside: CGPoint(x: 10, y: 10), with: nil))
1951
+ XCTAssertTrue(settlements.isEmpty)
1952
+
1953
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
1954
+ disclosureExpanded: true))
1955
+ view.layoutIfNeeded()
1956
+ list.layoutIfNeeded()
1957
+ XCTAssertEqual(contentHost.frame.minY, 360, accuracy: 1)
1958
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1959
+ XCTAssertFalse(contentHost.isHidden)
1960
+ XCTAssertTrue(contentHost.isUserInteractionEnabled)
1961
+ XCTAssertFalse(contentHost.accessibilityElementsHidden)
1962
+ XCTAssertEqual(toggleHost.frame.minY, 460, accuracy: 1)
1963
+ XCTAssertEqual(footerHost.frame.minY, 520, accuracy: 1)
1964
+ XCTAssertEqual(list.contentSize.height, 660, accuracy: 1)
1965
+ XCTAssertTrue(settlements.isEmpty)
1966
+ }
1967
+
1968
+ func testDisclosureCollapseClock() throws {
1969
+ try requireStructuralAnimation()
1970
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1971
+ let controller = UIViewController()
1972
+ window.rootViewController = controller
1973
+ let view = NativeListView(frame: window.bounds)
1974
+ controller.view.addSubview(view)
1975
+ window.isHidden = false
1976
+ defer {
1977
+ view.dispose()
1978
+ view.removeFromSuperview()
1979
+ window.isHidden = true
1980
+ window.rootViewController = nil
1981
+ }
1982
+ let slots = (0..<6).map { _ in UIView() }
1983
+ let expandedChild = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 100))
1984
+ slots[4].addSubview(expandedChild)
1985
+ let toggle = UIButton(frame: CGRect(x: 0, y: 0, width: 320, height: 40))
1986
+ for index in 0..<6 {
1987
+ view.mountContainerSlot(index == 5 ? toggle : slots[index], atIndex: index)
1988
+ }
1989
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1990
+ var settlements: [[String: Any]] = []
1991
+ view.onStructuralTransitionSettled = { payload in
1992
+ guard let data = payload.data(using: .utf8),
1993
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1994
+ return
1995
+ }
1996
+ settlements.append(object)
1997
+ }
1998
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1999
+ list.contentInsetAdjustmentBehavior = .never
2000
+ list.contentInset = .zero
2001
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1,
2002
+ disclosureExpanded: true))
2003
+ view.layoutIfNeeded()
2004
+ list.layoutIfNeeded()
2005
+ drainMainQueue()
2006
+ list.contentOffset.y = 2400
2007
+ list.layoutIfNeeded()
2008
+
2009
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2010
+ transitionID: "disclosure-collapse", durationMs: 800,
2011
+ disclosureExpanded: false))
2012
+ waitForStructuralFrames(0.16)
2013
+ list.layoutIfNeeded()
2014
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2015
+ let clip = try XCTUnwrap(flow.tailClip)
2016
+ let contentHost = try XCTUnwrap(slots[4].superview)
2017
+ let toggleHost = try XCTUnwrap(toggle.superview)
2018
+ let footerHost = try XCTUnwrap(slots[2].superview)
2019
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
2020
+ XCTAssertEqual(contentHost.frame.minY, clip.endY, accuracy: 1)
2021
+ let contentVisible = toggleHost.frame.minY - contentHost.frame.minY
2022
+ XCTAssertGreaterThan(contentVisible, 0)
2023
+ XCTAssertLessThan(contentVisible, 100)
2024
+ XCTAssertEqual(try XCTUnwrap(contentHost.layer.mask).frame.height,
2025
+ contentVisible, accuracy: 1)
2026
+ XCTAssertFalse(contentHost.isUserInteractionEnabled)
2027
+ XCTAssertTrue(contentHost.accessibilityElementsHidden)
2028
+ XCTAssertTrue(toggleHost.isUserInteractionEnabled)
2029
+ XCTAssertFalse(toggleHost.accessibilityElementsHidden)
2030
+ XCTAssertTrue(toggleHost.point(inside: CGPoint(x: 10, y: 10), with: nil))
2031
+ XCTAssertEqual(toggleHost.frame.minY, clip.endY + contentVisible, accuracy: 1)
2032
+ let inset = footerHost.frame.minY - toggleHost.frame.maxY
2033
+ XCTAssertGreaterThan(inset, 0)
2034
+ XCTAssertLessThan(inset, 20)
2035
+ XCTAssertTrue(settlements.isEmpty)
2036
+
2037
+ waitForStructuralFrames(0.75)
2038
+ list.layoutIfNeeded()
2039
+ XCTAssertNil(flow.tailClip)
2040
+ XCTAssertEqual(toggleHost.frame.minY, 360, accuracy: 1)
2041
+ XCTAssertEqual(footerHost.frame.minY, 400, accuracy: 1)
2042
+ XCTAssertTrue(contentHost.isHidden)
2043
+ XCTAssertEqual(settlements.count, 1)
2044
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "disclosure-collapse")
2045
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
2046
+ XCTAssertEqual(settlements.first?["settledExpanded"] as? Bool, false)
2047
+
2048
+ let roots = (0..<6).map { $0 == 5 ? toggle : slots[$0] }
2049
+ let hosts = roots.map(\.superview)
2050
+ XCTAssertTrue(hosts.allSatisfy { $0 != nil })
2051
+ let toggleWindowOrigin = toggleHost.convert(CGPoint.zero, to: window)
2052
+ let footerWindowOrigin = footerHost.convert(CGPoint.zero, to: window)
2053
+ let settledOffset = list.contentOffset
2054
+ let settledSize = list.contentSize
2055
+ expandedChild.removeFromSuperview()
2056
+ view.setContainerSlotHeightsJson("[0,0,140,0,0,40]")
2057
+ view.layoutIfNeeded()
2058
+ list.layoutIfNeeded()
2059
+ drainMainQueue()
2060
+ view.layoutIfNeeded()
2061
+ list.layoutIfNeeded()
2062
+ for (root, host) in zip(roots, hosts) {
2063
+ XCTAssertTrue(root.superview === host)
2064
+ XCTAssertTrue(root.window === window)
2065
+ }
2066
+ XCTAssertEqual(toggleHost.convert(CGPoint.zero, to: window).x, toggleWindowOrigin.x, accuracy: 1)
2067
+ XCTAssertEqual(toggleHost.convert(CGPoint.zero, to: window).y, toggleWindowOrigin.y, accuracy: 1)
2068
+ XCTAssertEqual(footerHost.convert(CGPoint.zero, to: window).x, footerWindowOrigin.x, accuracy: 1)
2069
+ XCTAssertEqual(footerHost.convert(CGPoint.zero, to: window).y, footerWindowOrigin.y, accuracy: 1)
2070
+ XCTAssertEqual(list.contentOffset.x, settledOffset.x, accuracy: 1)
2071
+ XCTAssertEqual(list.contentOffset.y, settledOffset.y, accuracy: 1)
2072
+ XCTAssertEqual(list.contentSize.width, settledSize.width, accuracy: 1)
2073
+ XCTAssertEqual(list.contentSize.height, settledSize.height, accuracy: 1)
2074
+ XCTAssertEqual(settlements.count, 1)
2075
+ }
2076
+
2077
+ func testDisclosureAckLatest() throws {
2078
+ try requireStructuralAnimation()
2079
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2080
+ let controller = UIViewController()
2081
+ window.rootViewController = controller
2082
+ let view = NativeListView(frame: window.bounds)
2083
+ controller.view.addSubview(view)
2084
+ window.isHidden = false
2085
+ defer {
2086
+ view.dispose()
2087
+ view.removeFromSuperview()
2088
+ window.isHidden = true
2089
+ window.rootViewController = nil
2090
+ }
2091
+ let slots = (0..<6).map { _ in UIView() }
2092
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
2093
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
2094
+ var settlements: [(String, String, Bool)] = []
2095
+ let latestSettled = expectation(description: "Latest disclosure transition settled")
2096
+ view.onStructuralTransitionSettled = { payload in
2097
+ guard let data = payload.data(using: .utf8),
2098
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
2099
+ let id = object["transitionId"] as? String,
2100
+ let status = object["status"] as? String,
2101
+ let expanded = object["settledExpanded"] as? Bool else { return }
2102
+ settlements.append((id, status, expanded))
2103
+ if id == "collapse-latest" { latestSettled.fulfill() }
2104
+ }
2105
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
2106
+ disclosureExpanded: false))
2107
+ view.layoutIfNeeded()
2108
+ drainMainQueue()
2109
+ XCTAssertTrue(settlements.isEmpty)
2110
+
2111
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2112
+ transitionID: "same-rows", durationMs: 400, disclosureExpanded: false))
2113
+ drainMainQueue()
2114
+ XCTAssertEqual(settlements.map(\.0), ["same-rows"])
2115
+ XCTAssertEqual(settlements.first?.1, "completed")
2116
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2117
+ transitionID: "same-rows", durationMs: 400, disclosureExpanded: false))
2118
+ drainMainQueue()
2119
+ XCTAssertEqual(settlements.count, 1)
2120
+
2121
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 4,
2122
+ transitionID: "expand-superseded", durationMs: 400,
2123
+ disclosureExpanded: true))
2124
+ // Supersede on the same main-thread turn: a timed wait can outlast the
2125
+ // expansion on a busy simulator and legitimately deliver its settlement.
2126
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink")
2127
+ as? CADisplayLink)
2128
+ XCTAssertEqual(settlements.map(\.0), ["same-rows"])
2129
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 5,
2130
+ transitionID: "collapse-latest", durationMs: 400,
2131
+ disclosureExpanded: false))
2132
+ wait(for: [latestSettled], timeout: 2)
2133
+ XCTAssertEqual(settlements.map(\.0), ["same-rows", "collapse-latest"])
2134
+ XCTAssertEqual(settlements.last?.1, "completed")
2135
+ XCTAssertEqual(settlements.last?.2, false)
2136
+ XCTAssertTrue(slots[4].superview?.isHidden ?? false)
2137
+
2138
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 0, generation: 6,
2139
+ transitionID: "empty-immediate", durationMs: 0,
2140
+ disclosureExpanded: false))
2141
+ drainMainQueue()
2142
+ XCTAssertEqual(settlements.map(\.0),
2143
+ ["same-rows", "collapse-latest", "empty-immediate"])
2144
+ XCTAssertEqual(settlements.last?.1, "completed")
2145
+ }
2146
+
2147
+ func testDisclosureGeometryFallbackUsesLatestSnapshot() throws {
2148
+ try requireStructuralAnimation()
2149
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2150
+ let controller = UIViewController()
2151
+ window.rootViewController = controller
2152
+ let view = NativeListView(frame: window.bounds)
2153
+ controller.view.addSubview(view)
2154
+ window.isHidden = false
2155
+ defer {
2156
+ view.dispose()
2157
+ view.removeFromSuperview()
2158
+ window.isHidden = true
2159
+ window.rootViewController = nil
2160
+ }
2161
+ let slots = (0..<6).map { _ in UIView() }
2162
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
2163
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
2164
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2165
+ list.contentInsetAdjustmentBehavior = .never
2166
+ var settlements: [(String, String)] = []
2167
+ view.onStructuralTransitionSettled = { payload in
2168
+ guard let data = payload.data(using: .utf8),
2169
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
2170
+ let id = object["transitionId"] as? String,
2171
+ let status = object["status"] as? String else { return }
2172
+ settlements.append((id, status))
2173
+ }
2174
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
2175
+ disclosureExpanded: false))
2176
+ view.layoutIfNeeded()
2177
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2178
+ transitionID: "expand", durationMs: 800, disclosureExpanded: true))
2179
+ waitForStructuralFrames(0.08)
2180
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2181
+
2182
+ view.setContainerSlotHeightsJson("[0,0,160,0,100,40]", followedBySnapshot: true)
2183
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
2184
+ transitionID: "expand", durationMs: 800, disclosureExpanded: true))
2185
+ drainMainQueue()
2186
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2187
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
2188
+ let contentHost = try XCTUnwrap(slots[4].superview)
2189
+ let toggleHost = try XCTUnwrap(slots[5].superview)
2190
+ let footerHost = try XCTUnwrap(slots[2].superview)
2191
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
2192
+ XCTAssertEqual(toggleHost.frame.minY, 3_100, accuracy: 1)
2193
+ XCTAssertEqual(footerHost.frame.minY, 3_160, accuracy: 1)
2194
+ XCTAssertEqual(footerHost.bounds.height, 160, accuracy: 1)
2195
+ XCTAssertEqual(settlements.map(\.0), ["expand"])
2196
+ XCTAssertEqual(settlements.last?.1, "interrupted")
2197
+
2198
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 4,
2199
+ transitionID: "collapse", durationMs: 800, disclosureExpanded: false))
2200
+ waitForStructuralFrames(0.08)
2201
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 5,
2202
+ transitionID: "collapse", durationMs: 800))
2203
+ drainMainQueue()
2204
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2205
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
2206
+ XCTAssertEqual(settlements.map(\.0), ["expand"],
2207
+ "Removing disclosure without a new command cannot acknowledge the old target")
2208
+ }
2209
+
2210
+ func testDisclosureLateCompletionCannotSettleNewCommand() throws {
2211
+ try requireStructuralAnimation()
2212
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2213
+ let controller = UIViewController()
2214
+ window.rootViewController = controller
2215
+ let view = NativeListView(frame: window.bounds)
2216
+ controller.view.addSubview(view)
2217
+ window.isHidden = false
2218
+ defer {
2219
+ view.dispose()
2220
+ view.removeFromSuperview()
2221
+ window.isHidden = true
2222
+ window.rootViewController = nil
2223
+ }
2224
+ for index in 0..<6 { view.mountContainerSlot(UIView(), atIndex: index) }
2225
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
2226
+ var settled: [String] = []
2227
+ view.onStructuralTransitionSettled = { payload in
2228
+ guard let data = payload.data(using: .utf8),
2229
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
2230
+ let id = object["transitionId"] as? String else { return }
2231
+ settled.append(id)
2232
+ }
2233
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
2234
+ disclosureExpanded: false))
2235
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2236
+ transitionID: "old-direct", disclosureExpanded: false))
2237
+ let oldCompletedBeforeReplacement = settled.contains("old-direct")
2238
+ XCTAssertFalse(oldCompletedBeforeReplacement,
2239
+ "The older diffable completion must remain pending when its replacement starts")
2240
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
2241
+ transitionID: "latest-expand", durationMs: 800, disclosureExpanded: true))
2242
+ drainMainQueue()
2243
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2244
+ XCTAssertTrue(settled.isEmpty,
2245
+ "An older diffable completion must not settle the active newer transition")
2246
+ waitForStructuralFrames(0.9)
2247
+ XCTAssertEqual(settled, ["latest-expand"])
2248
+ }
2249
+
2250
+ func testDisclosureContentGrowthAndDragSettlement() throws {
2251
+ try requireStructuralAnimation()
2252
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2253
+ let controller = UIViewController()
2254
+ window.rootViewController = controller
2255
+ let view = NativeListView(frame: window.bounds)
2256
+ controller.view.addSubview(view)
2257
+ window.isHidden = false
2258
+ defer {
2259
+ view.dispose()
2260
+ view.removeFromSuperview()
2261
+ window.isHidden = true
2262
+ window.rootViewController = nil
2263
+ }
2264
+ let slots = (0..<6).map { _ in UIView() }
2265
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
2266
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
2267
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2268
+ list.contentInsetAdjustmentBehavior = .never
2269
+ let contentHost = try XCTUnwrap(slots[4].superview)
2270
+ var settlements: [(String, String)] = []
2271
+ let growSettled = expectation(description: "Disclosure growth settles")
2272
+ view.onStructuralTransitionSettled = { payload in
2273
+ guard let data = payload.data(using: .utf8),
2274
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
2275
+ let id = object["transitionId"] as? String,
2276
+ let status = object["status"] as? String else { return }
2277
+ settlements.append((id, status))
2278
+ if id == "grow" && status == "completed" { growSettled.fulfill() }
2279
+ }
2280
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
2281
+ disclosureExpanded: false))
2282
+ view.layoutIfNeeded()
2283
+ list.layoutIfNeeded()
2284
+ drainMainQueue()
2285
+ XCTAssertTrue(contentHost.isHidden, "Initial collapsed content must be hidden")
2286
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2287
+
2288
+ let growthPhase = expectation(description: "Disclosure growth presents a partial content mask")
2289
+ var growthObserved = false
2290
+ var growthLast = "no frame sampled"
2291
+ let growthStartedAt = CACurrentMediaTime()
2292
+ let growthProbe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in
2293
+ let clock = Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink
2294
+ let tail = Mirror(reflecting: view).descendant("structuralTail")
2295
+ let tailActive = tail.map { !Mirror(reflecting: $0).children.isEmpty } ?? false
2296
+ let maskHeight = contentHost.layer.mask?.frame.height
2297
+ growthLast = "clock=\(clock != nil) tail=\(tailActive) "
2298
+ + "mask=\(String(describing: maskHeight)) bounds=\(contentHost.bounds.height) "
2299
+ + "elapsed=\(CACurrentMediaTime() - growthStartedAt) settlements=\(settlements)"
2300
+ guard !growthObserved, let clock, tailActive, let maskHeight,
2301
+ maskHeight > 0, maskHeight < 100 else { return }
2302
+ growthObserved = true
2303
+ let animationStart = Mirror(reflecting: view).descendant("structuralAnimationStart")
2304
+ as? CFTimeInterval
2305
+ let animationDuration = Mirror(reflecting: view).descendant("structuralAnimationDuration")
2306
+ as? CFTimeInterval
2307
+ XCTAssertNotNil(animationStart, "The active disclosure clock must have a start time")
2308
+ XCTAssertNotNil(animationDuration, "The active disclosure clock must have a duration")
2309
+ view.setContainerSlotHeightsJson("[0,0,140,0,140,40]")
2310
+ XCTAssertTrue(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink
2311
+ === clock, "Content growth must retain the active display link")
2312
+ XCTAssertEqual(Mirror(reflecting: view).descendant("structuralAnimationStart")
2313
+ as? CFTimeInterval, animationStart, "Content growth must keep the original deadline")
2314
+ XCTAssertEqual(Mirror(reflecting: view).descendant("structuralAnimationDuration")
2315
+ as? CFTimeInterval, animationDuration, "Content growth must keep the original duration")
2316
+ XCTAssertEqual(contentHost.layer.mask?.frame.height ?? -1, maskHeight, accuracy: 1,
2317
+ "Content growth must not jump the visible mask")
2318
+ growthPhase.fulfill()
2319
+ }
2320
+ RunLoop.main.add(growthProbe, forMode: .common)
2321
+ defer { growthProbe.invalidate() }
2322
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2323
+ transitionID: "grow", durationMs: 800, disclosureExpanded: true))
2324
+ wait(for: [growthPhase], timeout: 1.5)
2325
+ guard growthObserved else {
2326
+ XCTFail("No partial disclosure growth frame observed: \(growthLast)")
2327
+ return
2328
+ }
2329
+ growthProbe.invalidate()
2330
+ wait(for: [growSettled], timeout: 1.5)
2331
+ XCTAssertEqual(contentHost.bounds.height, 140, accuracy: 1)
2332
+ XCTAssertNil(contentHost.layer.mask)
2333
+ XCTAssertTrue(contentHost.isUserInteractionEnabled)
2334
+ XCTAssertEqual(settlements.map(\.0), ["grow"], "Growth must settle exactly once")
2335
+ XCTAssertEqual(settlements.last?.1, "completed")
2336
+
2337
+ let collapsePhase = expectation(description: "Disclosure collapse presents a partial content mask")
2338
+ var collapseObserved = false
2339
+ var collapseLast = "no frame sampled"
2340
+ let collapseStartedAt = CACurrentMediaTime()
2341
+ let collapseProbe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in
2342
+ let clock = Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink
2343
+ let tail = Mirror(reflecting: view).descendant("structuralTail")
2344
+ let tailActive = tail.map { !Mirror(reflecting: $0).children.isEmpty } ?? false
2345
+ let maskHeight = contentHost.layer.mask?.frame.height
2346
+ collapseLast = "clock=\(clock != nil) tail=\(tailActive) "
2347
+ + "mask=\(String(describing: maskHeight)) bounds=\(contentHost.bounds.height) "
2348
+ + "elapsed=\(CACurrentMediaTime() - collapseStartedAt) settlements=\(settlements)"
2349
+ guard !collapseObserved, clock != nil, tailActive, let maskHeight,
2350
+ maskHeight > 0, maskHeight < 140 else { return }
2351
+ collapseObserved = true
2352
+ view.scrollViewWillBeginDragging(list)
2353
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink,
2354
+ "Dragging must stop the active disclosure display link")
2355
+ let remainingTail = Mirror(reflecting: view).descendant("structuralTail")
2356
+ XCTAssertNotNil(remainingTail, "The structural tail field must remain observable")
2357
+ XCTAssertFalse(remainingTail.map { !Mirror(reflecting: $0).children.isEmpty } ?? true,
2358
+ "Dragging must clear the temporary structural tail")
2359
+ XCTAssertTrue(contentHost.isHidden, "Dragging a collapse must hide content")
2360
+ XCTAssertEqual(settlements.map(\.0), ["grow", "drag"],
2361
+ "Dragging must settle the collapse exactly once")
2362
+ XCTAssertEqual(settlements.last?.1, "interrupted")
2363
+ collapsePhase.fulfill()
2364
+ }
2365
+ RunLoop.main.add(collapseProbe, forMode: .common)
2366
+ defer { collapseProbe.invalidate() }
2367
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2368
+ transitionID: "drag", durationMs: 800, disclosureExpanded: false))
2369
+ wait(for: [collapsePhase], timeout: 1.5)
2370
+ guard collapseObserved else {
2371
+ XCTFail("No partial disclosure collapse frame observed: \(collapseLast)")
2372
+ return
2373
+ }
2374
+ collapseProbe.invalidate()
2375
+ }
2376
+
2377
+ func testDisclosureDirectCollapseKeepsToggleVisible() throws {
2378
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 600))
2379
+ let controller = UIViewController()
2380
+ window.rootViewController = controller
2381
+ let view = NativeListView(frame: window.bounds)
2382
+ controller.view.addSubview(view)
2383
+ window.isHidden = false
2384
+ defer {
2385
+ view.dispose()
2386
+ view.removeFromSuperview()
2387
+ window.isHidden = true
2388
+ window.rootViewController = nil
2389
+ }
2390
+ let slots = (0..<6).map { _ in UIView() }
2391
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
2392
+ view.setSidecarLayoutJson("{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}")
2393
+ view.setContainerSlotHeightsJson("[0,0,900,2200,100,40]")
2394
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2395
+ list.contentInsetAdjustmentBehavior = .never
2396
+ list.contentInset = .zero
2397
+ var settlements: [[String: Any]] = []
2398
+ view.onStructuralTransitionSettled = { payload in
2399
+ guard let data = payload.data(using: .utf8),
2400
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
2401
+ return
2402
+ }
2403
+ settlements.append(object)
2404
+ }
2405
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1,
2406
+ disclosureExpanded: true))
2407
+ view.layoutIfNeeded()
2408
+ list.layoutIfNeeded()
2409
+ list.contentOffset.y = 2_600
2410
+ list.layoutIfNeeded()
2411
+ XCTAssertEqual(list.contentOffset.y, 2_600, accuracy: 1)
2412
+
2413
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2414
+ transitionID: "direct-collapse", durationMs: 0, disclosureExpanded: false))
2415
+ drainMainQueue()
2416
+ list.layoutIfNeeded()
2417
+ let toggle = try XCTUnwrap(slots[5].superview)
2418
+ XCTAssertEqual(toggle.frame.minY, 360, accuracy: 1)
2419
+ XCTAssertEqual(list.contentSize.height, 2_200, accuracy: 1)
2420
+ XCTAssertEqual(list.contentOffset.y, 360, accuracy: 1,
2421
+ "A direct collapsed endpoint must expose the stable toggle despite a taller sidecar")
2422
+ XCTAssertEqual(settlements.count, 1)
2423
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "direct-collapse")
2424
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
2425
+
2426
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
2427
+ disclosureExpanded: true))
2428
+ drainMainQueue()
2429
+ view.frame.size.height = 0
2430
+ view.layoutIfNeeded()
2431
+ XCTAssertEqual(list.bounds.height, 0)
2432
+ view.scrollToOffset(500, animated: false)
2433
+ let pending = try XCTUnwrap(Mirror(reflecting: view).descendant("pendingScrollRequest"))
2434
+ XCTAssertEqual(Mirror(reflecting: pending).children.count, 1,
2435
+ "The explicit command must still be queued when the direct collapse is accepted")
2436
+ view.frame.size.height = 600
2437
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 4,
2438
+ transitionID: "direct-collapse-after-pending-scroll", durationMs: 0,
2439
+ disclosureExpanded: false))
2440
+ drainMainQueue()
2441
+ view.layoutIfNeeded()
2442
+ list.layoutIfNeeded()
2443
+ drainMainQueue()
2444
+ XCTAssertEqual(list.contentOffset.y, 500, accuracy: 1,
2445
+ "A direct collapse must not replace an already pending explicit scroll")
2446
+ XCTAssertEqual(settlements.count, 2)
2447
+ XCTAssertEqual(settlements.last?["transitionId"] as? String,
2448
+ "direct-collapse-after-pending-scroll")
2449
+ }
2450
+
2451
+ func testStructuralTailKeepsMiddleRowsNaturalAndFooterAttachedDuringCollapse() throws {
2452
+ try requireStructuralAnimation()
2453
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2454
+ let controller = UIViewController()
2455
+ window.rootViewController = controller
2456
+ let view = NativeListView(frame: window.bounds)
2457
+ var retiredActions = 0
2458
+ view.onRowAction = { _ in retiredActions += 1 }
2459
+ controller.view.addSubview(view)
2460
+ window.isHidden = false
2461
+ defer {
2462
+ view.dispose()
2463
+ view.removeFromSuperview()
2464
+ window.isHidden = true
2465
+ window.rootViewController = nil
2466
+ }
2467
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2468
+ let footer = UIView()
2469
+ view.mountContainerSlot(footer, atIndex: 2)
2470
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2471
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2472
+ list.contentInsetAdjustmentBehavior = .never
2473
+ list.contentInset = .zero
2474
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2475
+ view.layoutIfNeeded()
2476
+ list.layoutIfNeeded()
2477
+ drainMainQueue()
2478
+ list.contentOffset.y = 2400
2479
+ list.layoutIfNeeded()
2480
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2481
+ transitionID: "tail-50-to-6", durationMs: 800))
2482
+ waitForStructuralFrames(0.16)
2483
+ list.layoutIfNeeded()
2484
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2485
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2486
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2487
+ let clip = try XCTUnwrap(flow.tailClip)
2488
+ XCTAssertEqual(clip.firstIndex, 6)
2489
+ XCTAssertGreaterThan(clip.endY, 360)
2490
+ XCTAssertLessThan(clip.endY, 3000)
2491
+ let tailCells = list.visibleCells.compactMap { cell -> NativeListRowHost? in
2492
+ guard let path = list.indexPath(for: cell), path.item >= 6 else { return nil }
2493
+ return cell as? NativeListRowHost
2494
+ }
2495
+ XCTAssertFalse(tailCells.isEmpty)
2496
+ XCTAssertTrue(tailCells.allSatisfy { abs($0.bounds.height - 60) <= 1 && $0.alpha == 1 })
2497
+ XCTAssertTrue(tailCells.allSatisfy { !$0.isUserInteractionEnabled && $0.accessibilityElementsHidden })
2498
+ XCTAssertFalse(view.collectionView(list, shouldSelectItemAt: IndexPath(item: 25, section: 0)))
2499
+ view.collectionView(list, didSelectItemAt: IndexPath(item: 25, section: 0))
2500
+ XCTAssertEqual(retiredActions, 0)
2501
+ XCTAssertEqual(footer.convert(.zero, to: list).y, clip.endY, accuracy: 1)
2502
+ let footerBottomBeforeResize = footer.convert(.zero, to: list).y + 60
2503
+ view.setContainerSlotHeightsJson("[0,0,80,0]")
2504
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 80,
2505
+ footerBottomBeforeResize, accuracy: 1)
2506
+ let footerHost = try XCTUnwrap(footer.superview)
2507
+ let hiddenTop = try XCTUnwrap(flow.tailClip).endY - footerHost.frame.minY
2508
+ if hiddenTop > 1 {
2509
+ XCTAssertFalse(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop / 2), with: nil))
2510
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop + 1), with: nil))
2511
+ }
2512
+ waitForStructuralFrames(0.06)
2513
+ list.layoutIfNeeded()
2514
+ XCTAssertEqual(footer.convert(.zero, to: list).y, try XCTUnwrap(flow.tailClip).endY,
2515
+ accuracy: 1)
2516
+ let footerBottomBeforeSecondResize = footer.convert(.zero, to: list).y + 80
2517
+ view.setContainerSlotHeightsJson("[0,0,100,0]")
2518
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 100,
2519
+ footerBottomBeforeSecondResize, accuracy: 1)
2520
+ waitForStructuralFrames(0.7)
2521
+ list.layoutIfNeeded()
2522
+ XCTAssertNil(flow.tailClip)
2523
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2524
+ XCTAssertEqual(list.contentSize.height, 460, accuracy: 1)
2525
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 360, accuracy: 1)
2526
+ XCTAssertEqual(list.contentOffset.y, 0, accuracy: 1)
2527
+ }
2528
+
2529
+ func testStructuralTailCollapsePaintsEveryExpectedViewportRow() throws {
2530
+ try requireStructuralAnimation()
2531
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2532
+ let controller = UIViewController()
2533
+ window.rootViewController = controller
2534
+ let view = NativeListView(frame: window.bounds)
2535
+ controller.view.addSubview(view)
2536
+ window.isHidden = false
2537
+ defer {
2538
+ view.dispose()
2539
+ view.removeFromSuperview()
2540
+ window.isHidden = true
2541
+ window.rootViewController = nil
2542
+ }
2543
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2544
+ view.mountContainerSlot(UIView(), atIndex: 2)
2545
+ view.mountContainerSlot(UIView(), atIndex: 3)
2546
+ view.setContainerSlotHeightsJson("[0,0,60,3000]")
2547
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2548
+ list.contentInsetAdjustmentBehavior = .never
2549
+ list.contentInset = .zero
2550
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2551
+ view.layoutIfNeeded()
2552
+ list.layoutIfNeeded()
2553
+ drainMainQueue()
2554
+ list.contentOffset.y = 2400
2555
+ list.layoutIfNeeded()
2556
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2557
+ var checkedFrames = 0
2558
+ var failures: [String] = []
2559
+ let probe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in
2560
+ guard let clip = flow.tailClip else { return }
2561
+ list.layoutIfNeeded()
2562
+ let viewportTop = list.contentOffset.y
2563
+ let viewportBottom = viewportTop + list.bounds.height
2564
+ var expectedCount = 0
2565
+ var attributesCount = 0
2566
+ var attachedCount = 0
2567
+ var visibleCellsCount = 0
2568
+ var firstFailure: String?
2569
+ let attachedCells = list.subviews.compactMap { $0 as? NativeListRowHost }
2570
+ let visibleCells = list.visibleCells
2571
+ for index in 6..<50 {
2572
+ let rowTop = CGFloat(index * 60)
2573
+ let rowBottom = rowTop + 60
2574
+ let expectedTop = max(rowTop, viewportTop)
2575
+ let expectedBottom = min(rowBottom, viewportBottom, clip.endY)
2576
+ guard expectedBottom - expectedTop >= 8 else { continue }
2577
+ expectedCount += 1
2578
+ let path = IndexPath(item: index, section: 0)
2579
+ let attributes = flow.layoutAttributesForItem(at: path)
2580
+ if attributes != nil { attributesCount += 1 }
2581
+ let cell = attachedCells.first { list.indexPath(for: $0) == path }
2582
+ if cell != nil { attachedCount += 1 }
2583
+ let inVisibleCells = cell.map { visibleCells.contains($0) } ?? false
2584
+ if inVisibleCells { visibleCellsCount += 1 }
2585
+ let maskEnd = cell?.layer.mask?.frame.maxY ?? 60
2586
+ let neededMaskEnd = expectedBottom - rowTop
2587
+ if cell == nil || cell?.isHidden == true || cell?.alpha != 1
2588
+ || maskEnd + 1 < neededMaskEnd {
2589
+ if firstFailure == nil {
2590
+ let hidden = cell.map { String($0.isHidden) } ?? "nil"
2591
+ let frame = cell.map { String(describing: $0.frame) } ?? "nil"
2592
+ firstFailure = "row=\(index) offset=\(Int(viewportTop)) clip=\(Int(clip.endY)) "
2593
+ + "attached=\(cell != nil) visibleCells=\(inVisibleCells) hidden=\(hidden) "
2594
+ + "frame=\(frame) attributes=\(String(describing: attributes?.frame)) "
2595
+ + "maskEnd=\(Int(maskEnd)) alpha=\(cell?.alpha ?? -1)"
2596
+ }
2597
+ }
2598
+ }
2599
+ if expectedCount > 0 { checkedFrames += 1 }
2600
+ if let firstFailure, failures.count < 8 {
2601
+ failures.append("expected=\(expectedCount) attrs=\(attributesCount) "
2602
+ + "attached=\(attachedCount) visibleCells=\(visibleCellsCount) " + firstFailure)
2603
+ }
2604
+ }
2605
+ RunLoop.main.add(probe, forMode: .common)
2606
+ defer { probe.invalidate() }
2607
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2608
+ transitionID: "tail-viewport-paint", durationMs: 800))
2609
+ waitForStructuralFrames(0.82)
2610
+ XCTAssertGreaterThanOrEqual(checkedFrames, 5)
2611
+ XCTAssertTrue(failures.isEmpty, failures.joined(separator: "\n"))
2612
+ }
2613
+
2614
+ func testStructuralTailGeometryChangeWithSameIDCommitsFinalLayout() throws {
2615
+ try requireStructuralAnimation()
2616
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2617
+ let controller = UIViewController()
2618
+ window.rootViewController = controller
2619
+ let view = NativeListView(frame: window.bounds)
2620
+ controller.view.addSubview(view)
2621
+ window.isHidden = false
2622
+ defer {
2623
+ view.dispose()
2624
+ view.removeFromSuperview()
2625
+ window.isHidden = true
2626
+ window.rootViewController = nil
2627
+ }
2628
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2629
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2630
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2631
+ list.contentInsetAdjustmentBehavior = .never
2632
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2633
+ view.layoutIfNeeded()
2634
+ list.layoutIfNeeded()
2635
+ drainMainQueue()
2636
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2637
+ transitionID: "same-id-geometry", durationMs: 400))
2638
+ waitForStructuralFrames(0.08)
2639
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2640
+ transitionID: "same-id-geometry", durationMs: 400, firstRowHeight: 70))
2641
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2642
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2643
+ list.layoutIfNeeded()
2644
+ XCTAssertNil(flow.tailClip)
2645
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2646
+ XCTAssertEqual(list.contentSize.height, 430, accuracy: 1)
2647
+ waitForStructuralFrames(0.42)
2648
+ XCTAssertEqual(list.contentSize.height, 430, accuracy: 1)
2649
+ }
2650
+
2651
+ func testStructuralTailSameIDOrientationChangeStopsVerticalTimeline() throws {
2652
+ try requireStructuralAnimation()
2653
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2654
+ let controller = UIViewController()
2655
+ window.rootViewController = controller
2656
+ let view = NativeListView(frame: window.bounds)
2657
+ controller.view.addSubview(view)
2658
+ window.isHidden = false
2659
+ defer {
2660
+ view.dispose()
2661
+ view.removeFromSuperview()
2662
+ window.isHidden = true
2663
+ window.rootViewController = nil
2664
+ }
2665
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2666
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2667
+ view.layoutIfNeeded()
2668
+ list.layoutIfNeeded()
2669
+ drainMainQueue()
2670
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2671
+ transitionID: "same-id-orientation", durationMs: 400))
2672
+ waitForStructuralFrames(0.08)
2673
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2674
+ transitionID: "same-id-orientation", durationMs: 400, orientation: "horizontal"))
2675
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2676
+ XCTAssertNil(flow.tailClip)
2677
+ XCTAssertEqual(flow.scrollDirection, .horizontal)
2678
+ waitForStructuralFrames(0.42)
2679
+ XCTAssertEqual(flow.scrollDirection, .horizontal)
2680
+ XCTAssertNil(flow.tailClip)
2681
+ }
2682
+
2683
+ func testStructuralTailHostLimitFallsBackToAtomicSnapshot() throws {
2684
+ try requireStructuralAnimation()
2685
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2686
+ let controller = UIViewController()
2687
+ window.rootViewController = controller
2688
+ let view = NativeListView(frame: window.bounds)
2689
+ controller.view.addSubview(view)
2690
+ window.isHidden = false
2691
+ defer {
2692
+ view.dispose()
2693
+ view.removeFromSuperview()
2694
+ window.isHidden = true
2695
+ window.rootViewController = nil
2696
+ }
2697
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2698
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2699
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2700
+ list.contentInsetAdjustmentBehavior = .never
2701
+ // Six retained rows plus 129 retiring rows still exceed the 128-host limit
2702
+ // inside three viewports, without materializing hundreds of 1-point cells.
2703
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 135, generation: 1,
2704
+ uniformHeight: 10))
2705
+ view.layoutIfNeeded()
2706
+ list.layoutIfNeeded()
2707
+ drainMainQueue()
2708
+ var phases: [Int] = []
2709
+ let observer = NotificationCenter.default.addObserver(
2710
+ forName: Notification.Name("OneKeyNativeListScrollCommandAccepted"),
2711
+ object: list, queue: nil
2712
+ ) { notification in
2713
+ if let phase = notification.userInfo?["phase"] as? Int { phases.append(phase) }
2714
+ }
2715
+ defer { NotificationCenter.default.removeObserver(observer) }
2716
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2717
+ transitionID: "tail-host-limit", durationMs: 400, uniformHeight: 10))
2718
+ list.layoutIfNeeded()
2719
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2720
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2721
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2722
+ XCTAssertNil(flow.tailClip)
2723
+ XCTAssertTrue(phases.isEmpty)
2724
+ }
2725
+
2726
+ func testStructuralTailExpansionKeepsOffsetWithTallerInitialSidecar() throws {
2727
+ try requireStructuralAnimation()
2728
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2729
+ let controller = UIViewController()
2730
+ window.rootViewController = controller
2731
+ let view = NativeListView(frame: window.bounds)
2732
+ controller.view.addSubview(view)
2733
+ window.isHidden = false
2734
+ defer {
2735
+ view.dispose()
2736
+ view.removeFromSuperview()
2737
+ window.isHidden = true
2738
+ window.rootViewController = nil
2739
+ }
2740
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
2741
+ view.setContainerSlotHeightsJson("[0,0,60,2200]")
2742
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2743
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2744
+ list.contentInsetAdjustmentBehavior = .never
2745
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2746
+ view.layoutIfNeeded()
2747
+ list.layoutIfNeeded()
2748
+ drainMainQueue()
2749
+ XCTAssertEqual(list.contentSize.height, 2200, accuracy: 1)
2750
+ list.contentOffset.y = 1000
2751
+ list.layoutIfNeeded()
2752
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2753
+ transitionID: "tail-6-to-50", durationMs: 400))
2754
+ list.layoutIfNeeded()
2755
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2756
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2757
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2758
+ var checkedActiveTail = false
2759
+ func checkActiveTail() {
2760
+ guard let clip = flow.tailClip else { return }
2761
+ checkedActiveTail = true
2762
+ list.layoutIfNeeded()
2763
+ XCTAssertGreaterThanOrEqual(clip.endY, 360)
2764
+ XCTAssertLessThanOrEqual(clip.endY, 3000)
2765
+ let suffixCells = list.visibleCells.filter {
2766
+ (list.indexPath(for: $0)?.item ?? -1) >= 6
2767
+ }
2768
+ if clip.endY > list.contentOffset.y + 60 {
2769
+ XCTAssertFalse(suffixCells.isEmpty)
2770
+ }
2771
+ XCTAssertTrue(suffixCells.allSatisfy {
2772
+ !$0.isUserInteractionEnabled && $0.accessibilityElementsHidden
2773
+ })
2774
+ XCTAssertEqual(list.contentOffset.y, 1000, accuracy: 1)
2775
+ }
2776
+ // Inspect actual active frames instead of assuming a delayed callback lands
2777
+ // inside a 400 ms animation on a busy CI runner.
2778
+ checkActiveTail()
2779
+ let probe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in checkActiveTail() }
2780
+ RunLoop.main.add(probe, forMode: .common)
2781
+ defer { probe.invalidate() }
2782
+ let finished = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
2783
+ flow.tailClip == nil &&
2784
+ Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink == nil
2785
+ }, object: nil)
2786
+ wait(for: [finished], timeout: 5)
2787
+ probe.invalidate()
2788
+ XCTAssertTrue(checkedActiveTail)
2789
+ list.layoutIfNeeded()
2790
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2791
+ XCTAssertEqual(list.contentSize.height, 3060, accuracy: 1)
2792
+ XCTAssertEqual(list.contentOffset.y, 1000, accuracy: 1)
2793
+ XCTAssertNil(flow.tailClip)
2794
+ }
2795
+
2796
+ func testStructuralTailDifferentPrefixDuringExpansionCommitsAtomicSnapshot() throws {
2797
+ try requireStructuralAnimation()
2798
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2799
+ let controller = UIViewController()
2800
+ window.rootViewController = controller
2801
+ let view = NativeListView(frame: window.bounds)
2802
+ controller.view.addSubview(view)
2803
+ window.isHidden = false
2804
+ defer {
2805
+ view.dispose()
2806
+ view.removeFromSuperview()
2807
+ window.isHidden = true
2808
+ window.rootViewController = nil
2809
+ }
2810
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
2811
+ view.setContainerSlotHeightsJson("[0,0,60,1600]")
2812
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2813
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2814
+ list.contentInsetAdjustmentBehavior = .never
2815
+ list.contentInset = .zero
2816
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2817
+ view.layoutIfNeeded()
2818
+ list.layoutIfNeeded()
2819
+ drainMainQueue()
2820
+ XCTAssertEqual(list.adjustedContentInset.top, 0, accuracy: 0.01)
2821
+ XCTAssertEqual(list.adjustedContentInset.bottom, 0, accuracy: 0.01)
2822
+ list.contentOffset.y = 900
2823
+ list.layoutIfNeeded()
2824
+
2825
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2826
+ transitionID: "tail-first-six", durationMs: 1200))
2827
+ waitForStructuralFrames(0.12)
2828
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2829
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2830
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2831
+ XCTAssertGreaterThan(try XCTUnwrap(flow.tailClip).endY, 360)
2832
+
2833
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 10, generation: 3,
2834
+ transitionID: "tail-next-ten", durationMs: 1200))
2835
+ list.layoutIfNeeded()
2836
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<10).map { "row-\($0)" })
2837
+ XCTAssertNil(flow.tailClip)
2838
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2839
+ XCTAssertEqual(Mirror(reflecting: view).descendant("structuralSpacerHeight") as? CGFloat ?? -1,
2840
+ 0, accuracy: 1)
2841
+ XCTAssertEqual(list.contentSize.height, 1600, accuracy: 1)
2842
+ XCTAssertEqual(list.contentOffset.y, 900, accuracy: 1)
2843
+ waitForStructuralFrames(1.25)
2844
+ list.layoutIfNeeded()
2845
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<10).map { "row-\($0)" })
2846
+ XCTAssertEqual(list.contentSize.height, 1600, accuracy: 1)
2847
+ XCTAssertEqual(list.contentOffset.y, 900, accuracy: 1)
2848
+ }
2849
+
2850
+ func testStructuralTailInterruptedExpansionRestoresBoundaryCellInteraction() throws {
2851
+ try requireStructuralAnimation()
2852
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2853
+ let controller = UIViewController()
2854
+ window.rootViewController = controller
2855
+ let view = NativeListView(frame: window.bounds)
2856
+ controller.view.addSubview(view)
2857
+ window.isHidden = false
2858
+ defer {
2859
+ view.dispose()
2860
+ view.removeFromSuperview()
2861
+ window.isHidden = true
2862
+ window.rootViewController = nil
2863
+ }
2864
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2865
+ let footer = UIView()
2866
+ view.mountContainerSlot(footer, atIndex: 2)
2867
+ view.mountContainerSlot(UIView(), atIndex: 3)
2868
+ view.setContainerSlotHeightsJson("[0,0,60,2200]")
2869
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2870
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2871
+ list.contentInsetAdjustmentBehavior = .never
2872
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2873
+ view.layoutIfNeeded()
2874
+ list.layoutIfNeeded()
2875
+ drainMainQueue()
2876
+ list.contentOffset.y = 300
2877
+ list.layoutIfNeeded()
2878
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2879
+ transitionID: "interrupt-boundary", durationMs: 1200))
2880
+ let footerBottomBeforeResize = footer.convert(.zero, to: list).y + 60
2881
+ view.setContainerSlotHeightsJson("[0,0,80,2200]")
2882
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 80,
2883
+ footerBottomBeforeResize, accuracy: 1)
2884
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2885
+ let prefixBottom = try XCTUnwrap(flow.layoutAttributesForItem(
2886
+ at: IndexPath(item: 5, section: 0))).frame.maxY
2887
+ let footerHost = try XCTUnwrap(footer.superview)
2888
+ let hiddenTop = prefixBottom - footerHost.frame.minY
2889
+ XCTAssertGreaterThan(hiddenTop, 0)
2890
+ XCTAssertFalse(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop / 2), with: nil))
2891
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop + 1), with: nil))
2892
+ var boundaryCell: NativeListRowHost?
2893
+ let deadline = Date().addingTimeInterval(1)
2894
+ while boundaryCell == nil && Date() < deadline {
2895
+ if let clip = flow.tailClip {
2896
+ for case let cell as NativeListRowHost in list.visibleCells {
2897
+ guard let path = list.indexPath(for: cell), path.item >= 6,
2898
+ let mask = cell.layer.mask else { continue }
2899
+ let visibleHeight = clip.endY - cell.frame.minY
2900
+ if clip.endY > cell.frame.minY + 2 &&
2901
+ clip.endY < cell.frame.maxY - 2 &&
2902
+ mask.frame.height > 2 &&
2903
+ mask.frame.height < cell.bounds.height - 2 &&
2904
+ abs(mask.frame.height - visibleHeight) <= 1 {
2905
+ boundaryCell = cell
2906
+ break
2907
+ }
2908
+ }
2909
+ }
2910
+ if boundaryCell == nil { RunLoop.main.run(until: Date().addingTimeInterval(0.01)) }
2911
+ }
2912
+ let boundary = try XCTUnwrap(boundaryCell)
2913
+ let displayLink = try XCTUnwrap(
2914
+ Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2915
+ displayLink.isPaused = true
2916
+ defer { displayLink.isPaused = false }
2917
+ let mask = try XCTUnwrap(boundary.layer.mask)
2918
+ XCTAssertGreaterThan(mask.frame.height, 2)
2919
+ XCTAssertLessThan(mask.frame.height, boundary.bounds.height - 2)
2920
+ XCTAssertFalse(boundary.isUserInteractionEnabled)
2921
+ XCTAssertTrue(boundary.accessibilityElementsHidden)
2922
+ let offsetBeforeInterruption = list.contentOffset.y
2923
+ view.scrollViewWillBeginDragging(list)
2924
+ list.layoutIfNeeded()
2925
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2926
+ XCTAssertNil(boundary.layer.mask)
2927
+ XCTAssertFalse(boundary.isHidden)
2928
+ XCTAssertTrue(boundary.isUserInteractionEnabled)
2929
+ XCTAssertFalse(boundary.accessibilityElementsHidden)
2930
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: 1), with: nil))
2931
+ XCTAssertEqual(list.contentOffset.y, offsetBeforeInterruption, accuracy: 1)
2932
+ XCTAssertEqual(list.contentOffset.y, 300, accuracy: 1)
2933
+ }
2934
+
2935
+ func testStructuralTailExplicitScrollTakesOwnershipFromExpansion() throws {
2936
+ try requireStructuralAnimation()
2937
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2938
+ let controller = UIViewController()
2939
+ window.rootViewController = controller
2940
+ let view = NativeListView(frame: window.bounds)
2941
+ controller.view.addSubview(view)
2942
+ window.isHidden = false
2943
+ defer {
2944
+ view.dispose()
2945
+ view.removeFromSuperview()
2946
+ window.isHidden = true
2947
+ window.rootViewController = nil
2948
+ }
2949
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2950
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2951
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2952
+ list.contentInsetAdjustmentBehavior = .never
2953
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2954
+ view.layoutIfNeeded()
2955
+ list.layoutIfNeeded()
2956
+ drainMainQueue()
2957
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2958
+ transitionID: "explicit-scroll-over-expansion", durationMs: 400))
2959
+ waitForStructuralFrames(0.08)
2960
+ view.scrollToIndex(40, animated: false, alignment: "start")
2961
+ drainMainQueue()
2962
+ list.layoutIfNeeded()
2963
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2964
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2965
+ XCTAssertEqual(list.contentOffset.y, 2400, accuracy: 1)
2966
+ waitForStructuralFrames(0.4)
2967
+ XCTAssertEqual(list.contentOffset.y, 2400, accuracy: 1)
2968
+ XCTAssertTrue(list.visibleCells.allSatisfy {
2969
+ $0.isUserInteractionEnabled && !$0.accessibilityElementsHidden && $0.layer.mask == nil
2970
+ })
2971
+ }
2972
+
2973
+ func testStructuralTransitionSurvivesVisibleDataRowPatch() throws {
2974
+ try requireStructuralAnimation()
2975
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2976
+ let controller = UIViewController()
2977
+ window.rootViewController = controller
2978
+ let view = NativeListView(frame: window.bounds)
2979
+ controller.view.addSubview(view)
2980
+ window.isHidden = false
2981
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
2982
+ let footer = UIView()
2983
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2984
+ view.mountContainerSlot(footer, atIndex: 2)
2985
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2986
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1, dataRows: true))
2987
+ view.layoutIfNeeded()
2988
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2989
+ list.layoutIfNeeded()
2990
+ drainMainQueue()
2991
+ list.contentOffset.y = 1100
2992
+ list.layoutIfNeeded()
2993
+
2994
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
2995
+ transitionID: "collapse-with-patch", durationMs: 800, dataRows: true))
2996
+ waitForStructuralFrames(0.3)
2997
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2998
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2999
+ let heightBeforePatch = try XCTUnwrap(flow.tailClip).endY
3000
+ XCTAssertGreaterThan(heightBeforePatch, 1500)
3001
+ let retiring = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 25, section: 0)) as? NativeListRowHost)
3002
+ XCTAssertEqual(retiring.bounds.height, 60, accuracy: 1)
3003
+ func storedContent(_ key: String) throws -> String {
3004
+ let items = try XCTUnwrap(Mirror(reflecting: view).descendant("itemsByKey")
3005
+ as? [String: NativeListItem])
3006
+ return try XCTUnwrap(items[key]).content
3007
+ }
3008
+ let oldAcceptedContent = try storedContent("row-20")
3009
+ let retiredContent = try storedContent("row-25")
3010
+ let patch: [[String: Any]] = [[
3011
+ "key": "row-20", "type": "dataRow", "changes": [
3012
+ "revision": 2,
3013
+ "columns": [["key": "asset", "text": "Asset"],
3014
+ ["key": "price", "text": "$123.45"]],
3015
+ ],
3016
+ ]]
3017
+ let invalidRetiredPatch: [String: Any] = ["key": "row-25", "type": "dataRow",
3018
+ "changes": ["revision": 2]]
3019
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(
3020
+ withJSONObject: patch + [invalidRetiredPatch]), as: UTF8.self))
3021
+ XCTAssertEqual(try storedContent("row-20"), oldAcceptedContent)
3022
+ XCTAssertEqual(try storedContent("row-25"), retiredContent)
3023
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patch),
3024
+ as: UTF8.self))
3025
+ XCTAssertNotEqual(try storedContent("row-20"), oldAcceptedContent)
3026
+ XCTAssertEqual(try storedContent("row-25"), retiredContent)
3027
+ list.layoutIfNeeded()
3028
+ let patched = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0)))
3029
+ XCTAssertTrue(labels(in: patched).contains { $0.text == "$123.45" })
3030
+ waitForStructuralFrames(0.05)
3031
+ list.layoutIfNeeded()
3032
+ XCTAssertLessThan(try XCTUnwrap(flow.tailClip).endY, heightBeforePatch)
3033
+ waitForStructuralFrames(0.55)
3034
+ list.layoutIfNeeded()
3035
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<25).map { "row-\($0)" })
3036
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
3037
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1500, accuracy: 1)
3038
+ let finalPatched = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0)))
3039
+ XCTAssertTrue(labels(in: finalPatched).contains { $0.text == "$123.45" })
3040
+ }
3041
+
3042
+ func testStructuralTransitionDoesNotOverrideUserDrag() throws {
3043
+ try requireStructuralAnimation()
3044
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
3045
+ let controller = UIViewController()
3046
+ window.rootViewController = controller
3047
+ let view = NativeListView(frame: window.bounds)
3048
+ controller.view.addSubview(view)
3049
+ window.isHidden = false
3050
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
3051
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
3052
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
3053
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1))
3054
+ view.layoutIfNeeded()
3055
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
3056
+ list.layoutIfNeeded()
3057
+ drainMainQueue()
3058
+ list.contentOffset.y = 1100
3059
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
3060
+ transitionID: "collapse-drag", durationMs: 400))
3061
+ waitForStructuralFrames(0.08)
3062
+ view.scrollViewWillBeginDragging(list)
3063
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
3064
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
3065
+ list.contentOffset.y = 600
3066
+ list.layoutIfNeeded()
3067
+ waitForStructuralFrames(0.15)
3068
+ XCTAssertEqual(list.contentOffset.y, 600, accuracy: 1)
3069
+ waitForStructuralFrames(0.35)
3070
+ list.layoutIfNeeded()
3071
+ XCTAssertEqual(list.contentOffset.y, 600, accuracy: 1)
3072
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
3073
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<25).map { "row-\($0)" })
3074
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
3075
+ XCTAssertTrue(list.visibleCells.allSatisfy { abs($0.alpha - 1) < 0.01 })
3076
+ }
3077
+
3078
+ func testStructuralTransitionDetachAndDisposeReleaseView() throws {
3079
+ try requireStructuralAnimation()
3080
+ for dispose in [false, true] {
3081
+ var callbacks = 0
3082
+ let reference = try detachStructuralTransition(dispose: dispose) { callbacks += 1 }
3083
+ if dispose {
3084
+ drainMainQueue()
3085
+ XCTAssertNil(reference.view)
3086
+ let countAtDispose = callbacks
3087
+ waitForStructuralFrames(0.5)
3088
+ XCTAssertEqual(callbacks, countAtDispose)
3089
+ } else {
3090
+ waitForStructuralFrames(0.5)
3091
+ XCTAssertNil(reference.view)
3092
+ }
3093
+ }
3094
+ }
3095
+
3096
+ private final class WeakListReference {
3097
+ weak var view: NativeListView?
3098
+ }
3099
+
3100
+ private func detachStructuralTransition(
3101
+ dispose: Bool, onCallback: @escaping () -> Void
3102
+ ) throws -> WeakListReference {
3103
+ try autoreleasepool {
3104
+ let reference = WeakListReference()
3105
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
3106
+ let controller = UIViewController()
3107
+ window.rootViewController = controller
3108
+ let view = NativeListView(frame: window.bounds)
3109
+ controller.view.addSubview(view)
3110
+ window.isHidden = false
3111
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
3112
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
3113
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1))
3114
+ view.layoutIfNeeded()
3115
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
3116
+ view.onVisibleRangeChanged = { _ in onCallback() }
3117
+ view.onEndReached = { _ in onCallback() }
3118
+ list.layoutIfNeeded()
3119
+ drainMainQueue()
3120
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
3121
+ transitionID: dispose ? "dispose-mid-transition" : "detach-mid-transition",
3122
+ durationMs: 400))
3123
+ // Interrupt an active transition without racing a wall-clock delay on a busy runner.
3124
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
3125
+ reference.view = view
3126
+ if dispose {
3127
+ view.dispose()
3128
+ XCTAssertNil(list.delegate)
3129
+ XCTAssertNil(list.dataSource)
3130
+ }
3131
+ view.removeFromSuperview()
3132
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
3133
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
3134
+ window.isHidden = true
3135
+ window.rootViewController = nil
3136
+ return reference
3137
+ }
3138
+ }
3139
+
3140
+ private func dispatchAccessoryTouchUpInside(
3141
+ _ control: UIButton, on stack: NativeListAccessoryStack,
3142
+ file: StaticString = #filePath, line: UInt = #line
3143
+ ) throws {
3144
+ guard control.allTargets.contains(stack) else {
3145
+ XCTFail("Accessory control is not attached to its stack", file: file, line: line)
3146
+ return
3147
+ }
3148
+ let actions = try XCTUnwrap(
3149
+ control.actions(forTarget: stack, forControlEvent: .touchUpInside),
3150
+ file: file, line: line)
3151
+ guard !actions.isEmpty else {
3152
+ XCTFail("Accessory control has no touch-up action", file: file, line: line)
3153
+ return
3154
+ }
3155
+ // This pod XCTest has no UIApplication to dispatch UIControl.sendActions.
3156
+ guard control.isEnabled else { return }
3157
+ for action in actions {
3158
+ let selector = NSSelectorFromString(action)
3159
+ guard stack.responds(to: selector) else {
3160
+ XCTFail("Accessory action selector is missing: \(action)", file: file, line: line)
3161
+ continue
3162
+ }
3163
+ if action.hasSuffix(":") { _ = stack.perform(selector, with: control) }
3164
+ else { _ = stack.perform(selector) }
3165
+ }
3166
+ }
3167
+
3168
+ private func requireStructuralAnimation() throws {
3169
+ if UIAccessibility.isReduceMotionEnabled {
3170
+ throw XCTSkip("Structural animation is disabled by Reduce Motion")
3171
+ }
3172
+ }
3173
+
3174
+ private func waitForStructuralFrames(_ seconds: TimeInterval) {
3175
+ let completed = expectation(description: "Native structural display link ran for \(seconds)s")
3176
+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { completed.fulfill() }
3177
+ wait(for: [completed], timeout: seconds + 1)
3178
+ }
3179
+
3180
+ private func labels(in view: UIView) -> [UILabel] {
3181
+ let current = (view as? UILabel).map { [$0] } ?? []
3182
+ return current + view.subviews.flatMap(labels(in:))
3183
+ }
3184
+
3185
+ private func structuralRowsSnapshot(
3186
+ count: Int, generation: Int? = nil, transitionID: String? = nil,
3187
+ durationMs: Int = 80, dataRows: Bool = false, firstRowHeight: Int? = nil,
3188
+ uniformHeight: Int = 60, orientation: String = "vertical", layoutKind: String = "linear",
3189
+ disclosureExpanded: Bool? = nil, disclosureInset: Int = 20
3190
+ ) throws -> String {
3191
+ let rows: [[String: Any]] = (0..<count).map {
3192
+ let height = $0 == 0 ? firstRowHeight ?? uniformHeight : uniformHeight
3193
+ if dataRows {
3194
+ return ["key": "row-\($0)", "type": "dataRow", "height": height,
3195
+ "columns": [["key": "asset", "text": "Asset"],
3196
+ ["key": "price", "text": "$1.00"]]]
3197
+ }
3198
+ return ["key": "row-\($0)", "type": "action", "title": "Row", "height": height]
3199
+ }
3200
+ var layout: [String: Any] = ["kind": layoutKind, "orientation": orientation]
3201
+ if layoutKind == "grid" { layout["gridColumns"] = 2 }
3202
+ var value: [String: Any] = [
3203
+ "schemaVersion": 1, "generation": generation ?? count + 1,
3204
+ "layout": layout, "rows": rows,
3205
+ ]
3206
+ if let transitionID {
3207
+ value["structuralTransition"] = [
3208
+ "id": transitionID, "durationMs": durationMs, "anchorKey": "row-24",
3209
+ ]
3210
+ }
3211
+ if let disclosureExpanded {
3212
+ value["disclosure"] = ["expanded": disclosureExpanded,
3213
+ "expandedTrailingInset": disclosureInset]
3214
+ }
3215
+ return String(decoding: try JSONSerialization.data(withJSONObject: value), as: UTF8.self)
3216
+ }
3217
+
3218
+ private func assertHomeSidecarGeometry(sidecarBeforeFirstLayout: Bool) throws {
3219
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 900))
3220
+ let controller = UIViewController()
3221
+ window.rootViewController = controller
3222
+ let view = NativeListView(frame: window.bounds)
3223
+ controller.view.addSubview(view)
3224
+ window.isHidden = false
3225
+ defer {
3226
+ view.dispose()
3227
+ view.removeFromSuperview()
3228
+ window.isHidden = true
3229
+ window.rootViewController = nil
3230
+ }
3231
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
3232
+ view.setContainerSlotHeightsJson("[0,0,0,1200]")
3233
+ let sidecar = "{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}"
3234
+ if sidecarBeforeFirstLayout { view.setSidecarLayoutJson(sidecar) }
3235
+ view.applySnapshotJson(try homeSidecarSnapshot())
3236
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
3237
+ list.contentInsetAdjustmentBehavior = .never
3238
+ func layout() {
3239
+ window.layoutIfNeeded()
3240
+ view.layoutIfNeeded()
3241
+ list.layoutIfNeeded()
3242
+ }
3243
+ func assertRows(x: CGFloat, width: CGFloat) {
3244
+ let cells = list.visibleCells.compactMap { $0 as? NativeListDataRowCell }
3245
+ XCTAssertFalse(cells.isEmpty)
3246
+ for cell in cells {
3247
+ let frame = cell.convert(cell.bounds, to: list)
3248
+ XCTAssertEqual(frame.minX, x, accuracy: 1)
3249
+ XCTAssertEqual(frame.width, width, accuracy: 1)
3250
+ if let path = list.indexPath(for: cell),
3251
+ let attributes = list.layoutAttributesForItem(at: path)
3252
+ {
3253
+ XCTAssertEqual(attributes.frame.minX, x, accuracy: 1)
3254
+ XCTAssertEqual(attributes.frame.width, width, accuracy: 1)
3255
+ }
3256
+ let root = cell.root.convert(cell.root.bounds, to: list)
3257
+ XCTAssertGreaterThanOrEqual(root.minX, frame.minX - 1)
3258
+ XCTAssertLessThanOrEqual(root.maxX, frame.maxX + 1)
3259
+ }
3260
+ }
3261
+ layout()
3262
+ if !sidecarBeforeFirstLayout {
3263
+ assertRows(x: 8, width: 1360)
3264
+ view.setSidecarLayoutJson(sidecar)
3265
+ layout()
3266
+ }
3267
+ assertRows(x: 126, width: 700)
3268
+ list.contentOffset.y = 18 * 60
3269
+ layout()
3270
+ assertRows(x: 126, width: 700)
3271
+ let patch: [[String: Any]] = [[
3272
+ "key": "row-20", "type": "dataRow",
3273
+ "changes": ["columns": homeSidecarColumns(20, updated: true),
3274
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]]],
3275
+ ]]
3276
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patch),
3277
+ as: UTF8.self))
3278
+ layout()
3279
+ assertRows(x: 126, width: 700)
3280
+ window.frame.size.width = 1024
3281
+ controller.view.frame = window.bounds
3282
+ view.frame = window.bounds
3283
+ layout()
3284
+ assertRows(x: 8, width: 584)
3285
+ window.frame.size.width = 1376
3286
+ controller.view.frame = window.bounds
3287
+ view.frame = window.bounds
3288
+ layout()
3289
+ assertRows(x: 126, width: 700)
3290
+ view.setSidecarLayoutJson("")
3291
+ layout()
3292
+ assertRows(x: 8, width: 1360)
3293
+ }
3294
+
3295
+ private func homeSidecarSnapshot() throws -> String {
3296
+ let rows: [[String: Any]] = (0..<30).map { index in
3297
+ ["key": "row-\(index)", "type": "dataRow", "height": 60,
3298
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
3299
+ "columns": homeSidecarColumns(index, updated: false),
3300
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]],
3301
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
3302
+ "image": ["width": 32, "height": 32]]]
3303
+ }
3304
+ let snapshot: [String: Any] = [
3305
+ "schemaVersion": 1, "generation": 1,
3306
+ "layout": ["kind": "linear", "contentPaddingHorizontal": 8], "rows": rows,
3307
+ ]
3308
+ return String(decoding: try JSONSerialization.data(withJSONObject: snapshot), as: UTF8.self)
3309
+ }
3310
+
3311
+ private func homeSidecarColumns(_ index: Int, updated: Bool) -> [[String: Any]] {
3312
+ [
3313
+ ["key": "asset", "text": "Asset \(index)", "secondaryText": "Public fixture", "weight": 1],
3314
+ ["key": "balance", "text": updated ? "0.2966" : "0.000175",
3315
+ "secondaryText": "$0.13", "alignment": "end", "weight": 1],
3316
+ ["key": "price", "text": updated ? "$739.22" : "$0.9989",
3317
+ "secondaryText": "-0.04%", "alignment": "end", "weight": 1],
3318
+ ]
3319
+ }
3320
+
366
3321
  private func makeScrollingList() throws -> NativeListView {
367
3322
  let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
368
3323
  for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
369
- view.setContainerSlotHeightsJson("[44,44,44]")
3324
+ view.setContainerSlotHeightsJson("[44,44,44,0]")
370
3325
  view.applySnapshotJson(try scrollingSnapshot(count: 40))
371
3326
  view.layoutIfNeeded()
372
3327
  let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)