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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/README.md +312 -375
  2. package/android/src/main/java/com/onekey/nativelist/HybridNativeList.kt +14 -1
  3. package/android/src/main/java/com/onekey/nativelist/NativeListAccessoryStack.kt +250 -9
  4. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +35 -7
  5. package/android/src/main/java/com/onekey/nativelist/NativeListActivityRenderer.kt +25 -3
  6. package/android/src/main/java/com/onekey/nativelist/NativeListAdapter.kt +17 -1
  7. package/android/src/main/java/com/onekey/nativelist/NativeListButtonGroupRenderer.kt +102 -0
  8. package/android/src/main/java/com/onekey/nativelist/NativeListContainerSlotAdapter.kt +12 -0
  9. package/android/src/main/java/com/onekey/nativelist/NativeListDataRowRenderer.kt +102 -7
  10. package/android/src/main/java/com/onekey/nativelist/NativeListGeneratedIcons.kt +47 -0
  11. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +225 -11
  12. package/android/src/main/java/com/onekey/nativelist/NativeListLeadingVisual.kt +152 -33
  13. package/android/src/main/java/com/onekey/nativelist/NativeListMarketRenderer.kt +92 -28
  14. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPlaceholderView.kt +244 -0
  15. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPreviewSlot.kt +66 -31
  16. package/android/src/main/java/com/onekey/nativelist/NativeListMediaTileRenderer.kt +32 -11
  17. package/android/src/main/java/com/onekey/nativelist/NativeListMessageRenderer.kt +25 -0
  18. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +149 -3
  19. package/android/src/main/java/com/onekey/nativelist/NativeListPrimitives.kt +120 -287
  20. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRegistry.kt +2 -0
  21. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRowView.kt +7 -0
  22. package/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +3 -2
  23. package/android/src/main/java/com/onekey/nativelist/NativeListSectionHeaderRenderer.kt +69 -0
  24. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +55 -1
  25. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +1978 -136
  26. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListActivityHostClipPolicyTest.kt +35 -0
  27. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListIdentityTrailingAxisTest.kt +36 -0
  28. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingSlotFrameTest.kt +68 -0
  29. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingVisualClipPolicyTest.kt +44 -0
  30. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +10 -0
  31. package/docs/ROW_TEMPLATES.md +74 -13
  32. package/docs/SPEC.md +1232 -16
  33. package/docs/STYLE_SPEC.md +14 -0
  34. package/ios/HybridNativeList.swift +21 -2
  35. package/ios/NativeListAccessoryStack.swift +237 -51
  36. package/ios/NativeListActivityDetailsView.swift +30 -11
  37. package/ios/NativeListActivityRenderer.swift +8 -2
  38. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  39. package/ios/NativeListDataRowRenderer.swift +167 -30
  40. package/ios/NativeListDesignAssets.swift +13 -75
  41. package/ios/NativeListGeneratedIcons.swift +55 -0
  42. package/ios/NativeListIconBinding.swift +171 -0
  43. package/ios/NativeListIdentityRenderer.swift +256 -39
  44. package/ios/NativeListLeadingVisual.swift +127 -28
  45. package/ios/NativeListMarketRenderer.swift +120 -31
  46. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  47. package/ios/NativeListMediaPreviewSlot.swift +122 -61
  48. package/ios/NativeListMediaTileRenderer.swift +15 -11
  49. package/ios/NativeListMessageRenderer.swift +34 -1
  50. package/ios/NativeListMetricCardRenderer.swift +4 -2
  51. package/ios/NativeListModels.swift +42 -2
  52. package/ios/NativeListRendererRegistry.swift +1 -0
  53. package/ios/NativeListResolvedText.swift +2 -1
  54. package/ios/NativeListRowHost.swift +14 -0
  55. package/ios/NativeListSectionHeaderRenderer.swift +100 -4
  56. package/ios/RNCNativeListView.swift +1093 -59
  57. package/ios/tests/NativeListAccessoryStackTests.swift +101 -0
  58. package/ios/tests/NativeListAccountSelectorLayoutTests.swift +96 -0
  59. package/ios/tests/NativeListActivityPresentationTests.swift +153 -0
  60. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +81 -0
  61. package/ios/tests/NativeListLeadingVisualPairBackdropTests.swift +50 -0
  62. package/ios/tests/NativeListLifecycleTests.swift +2915 -4
  63. package/ios/tests/NativeListMarketMetricsTests.swift +117 -0
  64. package/ios/tests/NativeListMediaVisibilityTests.swift +26 -1
  65. package/ios/tests/NativeListSharedIconTests.swift +236 -0
  66. package/lib/module/NativeList.js +236 -38
  67. package/lib/module/NativeList.web.js +167 -46
  68. package/lib/module/index.js +1 -1
  69. package/lib/module/models.js +3 -0
  70. package/lib/module/selection.js +1 -1
  71. package/lib/module/validation.js +1246 -48
  72. package/lib/module/web/NativeListGeneratedIcons.js +31 -0
  73. package/lib/module/web/NativeListWebEngine.js +513 -275
  74. package/lib/module/web/templates/ActivityRowRenderer.js +12 -31
  75. package/lib/module/web/templates/ButtonGroupRowRenderer.js +47 -0
  76. package/lib/module/web/templates/DataRowRenderer.js +40 -5
  77. package/lib/module/web/templates/IdentityRowRenderer.js +158 -6
  78. package/lib/module/web/templates/MarketTableRowRenderer.js +36 -19
  79. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -25
  80. package/lib/module/web/templates/MessageRowRenderer.js +18 -2
  81. package/lib/module/web/templates/RowContainerStyle.js +1 -0
  82. package/lib/module/web/templates/RowRendererRegistry.js +3 -0
  83. package/lib/module/web/templates/SectionHeaderRowRenderer.js +36 -2
  84. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  85. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  86. package/lib/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  87. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  88. package/lib/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  89. package/lib/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  90. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  91. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  92. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  93. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  94. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  95. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  96. package/lib/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  97. package/lib/typescript/src/NativeList.d.ts +3 -3
  98. package/lib/typescript/src/NativeList.nitro.d.ts +2 -0
  99. package/lib/typescript/src/NativeList.types.d.ts +20 -2
  100. package/lib/typescript/src/index.d.ts +2 -2
  101. package/lib/typescript/src/models.d.ts +126 -17
  102. package/lib/typescript/src/validation.d.ts +20 -0
  103. package/lib/typescript/src/web/NativeListGeneratedIcons.d.ts +2 -0
  104. package/lib/typescript/src/web/NativeListWebEngine.d.ts +32 -1
  105. package/lib/typescript/src/web/templates/ButtonGroupRowRenderer.d.ts +14 -0
  106. package/lib/typescript/src/web/templates/IdentityRowRenderer.d.ts +1 -1
  107. package/lib/typescript/src/web/templates/MessageRowRenderer.d.ts +9 -3
  108. package/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  109. package/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  110. package/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  111. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  112. package/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  113. package/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  114. package/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  115. package/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  116. package/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  117. package/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  118. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  119. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  120. package/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  121. package/package.json +16 -10
  122. package/react-native-native-list.podspec +2 -6
  123. package/scripts/generate-icons.mjs +150 -0
  124. package/scripts/generate-icons.test.mjs +288 -0
  125. package/scripts/native-list-icons.json +260 -0
  126. package/src/NativeList.nitro.ts +2 -0
  127. package/src/NativeList.tsx +439 -91
  128. package/src/NativeList.types.ts +24 -2
  129. package/src/NativeList.web.tsx +295 -89
  130. package/src/index.ts +2 -0
  131. package/src/models.ts +263 -144
  132. package/src/selection.ts +1 -0
  133. package/src/validation.ts +3013 -152
  134. package/src/web/NativeListGeneratedIcons.ts +28 -0
  135. package/src/web/NativeListWebEngine.ts +818 -343
  136. package/src/web/templates/ActivityRowRenderer.ts +29 -59
  137. package/src/web/templates/ButtonGroupRowRenderer.ts +58 -0
  138. package/src/web/templates/DataRowRenderer.ts +93 -20
  139. package/src/web/templates/IdentityRowRenderer.ts +231 -6
  140. package/src/web/templates/MarketTableRowRenderer.ts +53 -33
  141. package/src/web/templates/MediaTileRowRenderer.ts +90 -28
  142. package/src/web/templates/MessageRowRenderer.ts +23 -7
  143. package/src/web/templates/RowContainerStyle.ts +2 -0
  144. package/src/web/templates/RowRendererRegistry.ts +11 -1
  145. package/src/web/templates/SectionHeaderRowRenderer.ts +47 -4
  146. package/ios/Resources/NativeListIcons.xcassets/Contents.json +0 -1
  147. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/Contents.json +0 -1
  148. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_bottom.imageset/icon.svg +0 -1
  149. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/Contents.json +0 -1
  150. package/ios/Resources/NativeListIcons.xcassets/onekey_arrow_top.imageset/icon.svg +0 -1
  151. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/Contents.json +0 -1
  152. package/ios/Resources/NativeListIcons.xcassets/onekey_badge_verified_solid.imageset/icon.svg +0 -1
  153. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/Contents.json +0 -1
  154. package/ios/Resources/NativeListIcons.xcassets/onekey_chart_trending_up.imageset/icon.svg +0 -1
  155. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/Contents.json +0 -1
  156. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_checked.imageset/icon.svg +0 -1
  157. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/Contents.json +0 -1
  158. package/ios/Resources/NativeListIcons.xcassets/onekey_checkbox_indeterminate.imageset/icon.svg +0 -1
  159. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/Contents.json +0 -1
  160. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_bottom.imageset/icon.svg +0 -1
  161. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/Contents.json +0 -1
  162. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_grabber_ver.imageset/icon.svg +0 -1
  163. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/Contents.json +0 -1
  164. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_right_small.imageset/icon.svg +0 -1
  165. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/Contents.json +0 -1
  166. package/ios/Resources/NativeListIcons.xcassets/onekey_chevron_top.imageset/icon.svg +0 -1
  167. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/Contents.json +0 -1
  168. package/ios/Resources/NativeListIcons.xcassets/onekey_dot_hor.imageset/icon.svg +0 -1
  169. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/Contents.json +0 -1
  170. package/ios/Resources/NativeListIcons.xcassets/onekey_drag.imageset/icon.svg +0 -1
  171. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/Contents.json +0 -1
  172. package/ios/Resources/NativeListIcons.xcassets/onekey_error_solid.imageset/icon.svg +0 -1
  173. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/Contents.json +0 -1
  174. package/ios/Resources/NativeListIcons.xcassets/onekey_image_square_waves.imageset/icon.svg +0 -1
  175. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/Contents.json +0 -1
  176. package/ios/Resources/NativeListIcons.xcassets/onekey_info_circle.imageset/icon.svg +0 -1
  177. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/Contents.json +0 -1
  178. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle.imageset/icon.svg +0 -1
  179. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/Contents.json +0 -1
  180. package/ios/Resources/NativeListIcons.xcassets/onekey_minus_circle_solid.imageset/icon.svg +0 -1
  181. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/Contents.json +0 -1
  182. package/ios/Resources/NativeListIcons.xcassets/onekey_pencil.imageset/icon.svg +0 -1
  183. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/Contents.json +0 -1
  184. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_circle.imageset/icon.svg +0 -1
  185. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/Contents.json +0 -1
  186. package/ios/Resources/NativeListIcons.xcassets/onekey_plus_small.imageset/icon.svg +0 -1
  187. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/Contents.json +0 -1
  188. package/ios/Resources/NativeListIcons.xcassets/onekey_questionmark_solid.imageset/icon.svg +0 -1
  189. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/Contents.json +0 -15
  190. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_account_error_custom.imageset/icon.svg +0 -14
  191. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/Contents.json +0 -15
  192. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_all_networks_solid.imageset/icon.svg +0 -12
  193. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/Contents.json +0 -15
  194. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_apple_brand.imageset/icon.svg +0 -6
  195. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/Contents.json +0 -15
  196. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_bot_illus.imageset/icon.svg +0 -15
  197. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/Contents.json +0 -15
  198. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_crossed_small_solid.imageset/icon.svg +0 -3
  199. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/Contents.json +0 -15
  200. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_globus_outline.imageset/icon.svg +0 -7
  201. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/Contents.json +0 -15
  202. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_google_illus.imageset/icon.svg +0 -18
  203. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/Contents.json +0 -15
  204. package/ios/Resources/NativeListIcons.xcassets/onekey_selector_lock_solid.imageset/icon.svg +0 -7
  205. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/Contents.json +0 -1
  206. package/ios/Resources/NativeListIcons.xcassets/onekey_shield_exclamation.imageset/icon.svg +0 -1
  207. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/Contents.json +0 -1
  208. package/ios/Resources/NativeListIcons.xcassets/onekey_speaker_promote.imageset/icon.svg +0 -1
  209. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/Contents.json +0 -1
  210. package/ios/Resources/NativeListIcons.xcassets/onekey_star.imageset/icon.svg +0 -1
  211. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/Contents.json +0 -1
  212. package/ios/Resources/NativeListIcons.xcassets/onekey_star_solid.imageset/icon.svg +0 -1
  213. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/Contents.json +0 -1
  214. package/ios/Resources/NativeListIcons.xcassets/onekey_swap_hor.imageset/icon.svg +0 -1
@@ -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,2037 @@ 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 testSidecarCentersRowsWhenConfiguredBeforeFirstWidth() throws {
1344
+ try assertHomeSidecarGeometry(sidecarBeforeFirstLayout: true)
1345
+ }
1346
+
1347
+ func testSidecarCentersRowsWhenConfiguredAfterFirstWidth() throws {
1348
+ try assertHomeSidecarGeometry(sidecarBeforeFirstLayout: false)
1349
+ }
1350
+
1351
+ func testHomeLinearColumnsStayInsideTheirStackAcrossEmptyMiddleAndReuse() throws {
1352
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 900))
1353
+ let controller = UIViewController()
1354
+ window.rootViewController = controller
1355
+ let view = NativeListView(frame: window.bounds)
1356
+ controller.view.addSubview(view)
1357
+ window.isHidden = false
1358
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1359
+ defer {
1360
+ view.dispose()
1361
+ view.removeFromSuperview()
1362
+ window.isHidden = true
1363
+ window.rootViewController = nil
1364
+ }
1365
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
1366
+ view.setContainerSlotHeightsJson("[0,0,0,1200]")
1367
+ let sidecar = "{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}"
1368
+ view.setSidecarLayoutJson(sidecar)
1369
+
1370
+ func columns(middle: String?, two: Bool = false) -> [[String: Any]] {
1371
+ let first: [String: Any] = ["key": "asset", "text": "USD1",
1372
+ "secondaryText": "Public fixture", "weight": 1]
1373
+ let balance: [String: Any] = ["key": "balance", "text": middle ?? "",
1374
+ "secondaryText": middle == nil ? "" : "$0.01", "alignment": "end", "weight": 1]
1375
+ let price: [String: Any] = ["key": "price", "text": "$1.00",
1376
+ "secondaryText": "0.01%", "alignment": "end", "weight": 1]
1377
+ return two ? [first, price] : [first, balance, price]
1378
+ }
1379
+ let rows: [[String: Any]] = (0..<30).map { index in
1380
+ ["key": "row-\(index)", "type": "dataRow", "height": 60,
1381
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
1382
+ "columns": index == 20 ? columns(middle: "0.01") : homeSidecarColumns(index, updated: false),
1383
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]],
1384
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
1385
+ "columns": ["token": "$bodyLg", "fontWeight": "medium", "lines": 1],
1386
+ "columnSecondary": ["token": "$bodyMd", "lines": 1],
1387
+ "image": ["width": 32, "height": 32]]]
1388
+ }
1389
+ let snapshot: [String: Any] = ["schemaVersion": 1, "generation": 1,
1390
+ "layout": ["kind": "linear", "contentPaddingHorizontal": 8], "rows": rows]
1391
+ view.applySnapshotJson(String(decoding: try JSONSerialization.data(withJSONObject: snapshot),
1392
+ as: UTF8.self))
1393
+ list.contentInsetAdjustmentBehavior = .never
1394
+ func layout() {
1395
+ window.layoutIfNeeded()
1396
+ view.layoutIfNeeded()
1397
+ list.layoutIfNeeded()
1398
+ }
1399
+ func check(_ phase: String, count: Int, width: CGFloat, weights: [Int]? = nil) throws {
1400
+ layout()
1401
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1402
+ as? NativeListDataRowCell, phase)
1403
+ let stack = try XCTUnwrap(cell.root.arrangedSubviews[3] as? UIStackView, phase)
1404
+ let visible = stack.arrangedSubviews.filter { !$0.isHidden }
1405
+ XCTAssertEqual(stack.arrangedSubviews.count, 4, phase)
1406
+ XCTAssertEqual(stack.arrangedSubviews.map(\.isHidden),
1407
+ (0..<4).map { $0 >= count }, phase)
1408
+ XCTAssertEqual(visible.count, count, phase)
1409
+ let cellFrame = cell.convert(cell.bounds, to: list)
1410
+ let stackFrame = stack.convert(stack.bounds, to: list)
1411
+ let attributes = try XCTUnwrap(list.layoutAttributesForItem(
1412
+ at: IndexPath(item: 20, section: 0)), phase)
1413
+ XCTAssertEqual(attributes.frame.width, width, accuracy: 1, phase)
1414
+ XCTAssertEqual(cellFrame.width, width, accuracy: 1,
1415
+ "\(phase) window=\(window.frame) controller=\(controller.view.frame) view=\(view.frame) list=\(list.frame) bounds=\(list.bounds) attributes=\(attributes.frame)")
1416
+ let rowConstraints = Mirror(reflecting: cell).children.first {
1417
+ $0.label == "rowConstraints"
1418
+ }?.value as? [NSLayoutConstraint] ?? []
1419
+ let columnWidthConstraints = Mirror(reflecting: cell).children.first {
1420
+ $0.label == "columnWidthConstraints"
1421
+ }?.value as? [NSLayoutConstraint] ?? []
1422
+ let constraints = rowConstraints + columnWidthConstraints
1423
+ let constraintState = constraints.map { constraint in
1424
+ let first = stack.arrangedSubviews.firstIndex {
1425
+ $0 === constraint.firstItem as? UIView
1426
+ } ?? -1
1427
+ let second = stack.arrangedSubviews.firstIndex {
1428
+ $0 === constraint.secondItem as? UIView
1429
+ } ?? -1
1430
+ return "\(first):\(second):\(constraint.multiplier):\(constraint.isActive)"
1431
+ }.joined(separator: ",")
1432
+ let hidingState = stack.arrangedSubviews.enumerated().map { index, column in
1433
+ let hiding = (stack.constraints + column.constraints).filter {
1434
+ $0.isActive && $0.identifier == "UISV-hiding"
1435
+ }.map { "\($0.constant)" }.joined(separator: ",")
1436
+ return "\(index):\(column.isHidden):\(hiding)"
1437
+ }.joined(separator: ",")
1438
+ let geometry = "\(phase) model=\(count) cell=\(cellFrame) stack=\(stackFrame) "
1439
+ + "columns=\(stack.arrangedSubviews.map { "\($0.isHidden):\($0.convert($0.bounds, to: list))" }) "
1440
+ + "constraints=\(constraintState) hiding=\(hidingState)"
1441
+ XCTAssertGreaterThanOrEqual(stackFrame.minX, cellFrame.minX - 0.5, geometry)
1442
+ XCTAssertLessThanOrEqual(stackFrame.maxX, cellFrame.maxX + 0.5, geometry)
1443
+ for column in visible {
1444
+ let columnFrame = column.convert(column.bounds, to: list)
1445
+ XCTAssertGreaterThan(columnFrame.width, 0, geometry)
1446
+ XCTAssertGreaterThanOrEqual(columnFrame.minX, stackFrame.minX - 0.5, geometry)
1447
+ XCTAssertLessThanOrEqual(columnFrame.maxX, stackFrame.maxX + 0.5, geometry)
1448
+ let primaryLine = (column as? UIStackView)?.arrangedSubviews.first
1449
+ if let primaryLine {
1450
+ let lineFrame = primaryLine.convert(primaryLine.bounds, to: list)
1451
+ XCTAssertGreaterThanOrEqual(lineFrame.minX, columnFrame.minX - 0.5, geometry)
1452
+ XCTAssertLessThanOrEqual(lineFrame.maxX, columnFrame.maxX + 0.5, geometry)
1453
+ }
1454
+ for label in labels(in: column) where !label.isHidden {
1455
+ let labelFrame = label.convert(label.bounds, to: list)
1456
+ XCTAssertGreaterThanOrEqual(labelFrame.minX, columnFrame.minX - 0.5,
1457
+ "\(geometry) label=\(labelFrame)")
1458
+ XCTAssertLessThanOrEqual(labelFrame.maxX, columnFrame.maxX + 0.5,
1459
+ "\(geometry) label=\(labelFrame)")
1460
+ }
1461
+ }
1462
+ if count >= 2 {
1463
+ let expectedWeights = weights ?? Array(repeating: 1, count: count)
1464
+ XCTAssertEqual(expectedWeights.count, count, geometry)
1465
+ for index in 1..<count {
1466
+ XCTAssertEqual(visible[index].bounds.width,
1467
+ visible[0].bounds.width * CGFloat(expectedWeights[index])
1468
+ / CGFloat(expectedWeights[0]),
1469
+ accuracy: 1, geometry)
1470
+ let previous = visible[index - 1].convert(visible[index - 1].bounds, to: stack)
1471
+ let current = visible[index].convert(visible[index].bounds, to: stack)
1472
+ XCTAssertGreaterThanOrEqual(current.minX, previous.maxX - 0.5, geometry)
1473
+ XCTAssertEqual(current.minX - previous.maxX, stack.spacing,
1474
+ accuracy: 0.5, geometry)
1475
+ }
1476
+ }
1477
+ }
1478
+ func patch(_ next: [[String: Any]]) throws {
1479
+ let patches: [[String: Any]] = [["key": "row-20", "type": "dataRow",
1480
+ "changes": ["columns": next]]]
1481
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patches),
1482
+ as: UTF8.self))
1483
+ }
1484
+ func widthConstraints() throws -> [NSLayoutConstraint] {
1485
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1486
+ as? NativeListDataRowCell)
1487
+ return try XCTUnwrap(Mirror(reflecting: cell).children.first {
1488
+ $0.label == "columnWidthConstraints"
1489
+ }?.value as? [NSLayoutConstraint])
1490
+ }
1491
+ func sizeConstraints() throws -> [NSLayoutConstraint] {
1492
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1493
+ as? NativeListDataRowCell)
1494
+ return try XCTUnwrap(Mirror(reflecting: cell).children.first {
1495
+ $0.label == "rowConstraints"
1496
+ }?.value as? [NSLayoutConstraint])
1497
+ }
1498
+ layout()
1499
+ list.setContentOffset(CGPoint(x: 0, y: 18 * 60), animated: false)
1500
+ try check("three populated", count: 3, width: 700)
1501
+ try patch(columns(middle: nil))
1502
+ try check("three empty middle", count: 3, width: 700)
1503
+ try patch(columns(middle: "0.02"))
1504
+ try check("three restored", count: 3, width: 700)
1505
+ try patch(columns(middle: nil, two: true))
1506
+ try check("two columns", count: 2, width: 700)
1507
+ try patch(columns(middle: nil))
1508
+ try check("three after two", count: 3, width: 700)
1509
+ let stableConstraints = try widthConstraints()
1510
+ let stableSizeConstraints = try sizeConstraints()
1511
+ XCTAssertEqual(stableConstraints.count, 2)
1512
+ XCTAssertEqual(stableSizeConstraints.count, 4)
1513
+ for update in 0..<10 {
1514
+ var next = columns(middle: nil)
1515
+ next[2]["text"] = "$1.\(update)"
1516
+ try patch(next)
1517
+ try check("same-shape price \(update)", count: 3, width: 700)
1518
+ let retained = try widthConstraints()
1519
+ XCTAssertEqual(retained.count, stableConstraints.count)
1520
+ XCTAssertTrue(zip(stableConstraints, retained).allSatisfy { $0 === $1 })
1521
+ XCTAssertTrue(retained.allSatisfy(\.isActive))
1522
+ let size = try sizeConstraints()
1523
+ XCTAssertEqual(size.count, stableSizeConstraints.count)
1524
+ XCTAssertTrue(zip(stableSizeConstraints, size).allSatisfy { $0 === $1 })
1525
+ XCTAssertTrue(size.allSatisfy(\.isActive))
1526
+ }
1527
+ var equivalentWeights = columns(middle: nil)
1528
+ for index in equivalentWeights.indices { equivalentWeights[index]["weight"] = 2 }
1529
+ try patch(equivalentWeights)
1530
+ try check("equivalent weights", count: 3, width: 700, weights: [2, 2, 2])
1531
+ let equivalentConstraints = try widthConstraints()
1532
+ XCTAssertEqual(equivalentConstraints.count, stableConstraints.count)
1533
+ XCTAssertTrue(zip(stableConstraints, equivalentConstraints).allSatisfy { $0 === $1 })
1534
+ var unequalWeights = columns(middle: nil)
1535
+ unequalWeights[0]["weight"] = 2
1536
+ try patch(unequalWeights)
1537
+ try check("unequal weights", count: 3, width: 700, weights: [2, 1, 1])
1538
+ let unequalConstraints = try widthConstraints()
1539
+ XCTAssertEqual(unequalConstraints.count, 2)
1540
+ XCTAssertTrue(stableConstraints.allSatisfy { !$0.isActive })
1541
+ try patch(columns(middle: nil, two: true))
1542
+ try check("two after weights", count: 2, width: 700)
1543
+ let twoConstraints = try widthConstraints()
1544
+ XCTAssertEqual(twoConstraints.count, 1)
1545
+ XCTAssertTrue(unequalConstraints.allSatisfy { !$0.isActive })
1546
+ try patch([])
1547
+ try check("zero columns", count: 0, width: 700)
1548
+ XCTAssertTrue((try widthConstraints()).isEmpty)
1549
+ XCTAssertTrue(twoConstraints.allSatisfy { !$0.isActive })
1550
+ try patch(columns(middle: nil))
1551
+ try check("three after zero", count: 3, width: 700)
1552
+ list.setContentOffset(.zero, animated: false)
1553
+ layout()
1554
+ XCTAssertFalse(list.indexPathsForVisibleItems.contains(IndexPath(item: 20, section: 0)))
1555
+ list.setContentOffset(CGPoint(x: 0, y: 18 * 60), animated: false)
1556
+ try check("after scroll reuse", count: 3, width: 700)
1557
+ window.frame.size.width = 1032
1558
+ controller.view.frame = window.bounds
1559
+ view.frame = window.bounds
1560
+ view.setSidecarLayoutJson("")
1561
+ drainMainQueue()
1562
+ try check("narrow no sidecar", count: 3, width: 1016)
1563
+ window.frame.size.width = 1376
1564
+ controller.view.frame = window.bounds
1565
+ view.frame = window.bounds
1566
+ view.setSidecarLayoutJson(sidecar)
1567
+ drainMainQueue()
1568
+ try check("wide sidecar restored", count: 3, width: 700)
1569
+ func animatedPatch(_ next: [[String: Any]], phase: String, count: Int) throws {
1570
+ let patches: [[String: Any]] = [["key": "row-20", "type": "dataRow",
1571
+ "changes": ["columns": next]]]
1572
+ let json = String(decoding: try JSONSerialization.data(withJSONObject: patches), as: UTF8.self)
1573
+ let finished = expectation(description: "Home column animation: \(phase)")
1574
+ UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState) {
1575
+ view.applyPatchesJson(json)
1576
+ view.layoutIfNeeded()
1577
+ list.layoutIfNeeded()
1578
+ } completion: { _ in finished.fulfill() }
1579
+ wait(for: [finished], timeout: 1)
1580
+ try check(phase, count: count, width: 700)
1581
+ waitForStructuralFrames(0.1)
1582
+ try check("\(phase) stable", count: count, width: 700)
1583
+ }
1584
+ try animatedPatch(columns(middle: nil, two: true), phase: "animated two", count: 2)
1585
+ try animatedPatch(columns(middle: nil), phase: "animated three", count: 3)
1586
+ try animatedPatch(columns(middle: "0.06"), phase: "animated nonempty", count: 3)
1587
+ }
1588
+
1589
+ func testStructuralShrinkUsesTheTallerFinalColumnForOffsetClamping() throws {
1590
+ let cases: [(name: String, sidecar: Int, offset: CGFloat, height: CGFloat,
1591
+ zeroInset: Bool)] = [
1592
+ ("sidecar stays taller", 2200, 1450, 2200, false),
1593
+ ("left column stays taller", 1000, 1100, 1560, false),
1594
+ ("left column zero inset", 1000, 1100, 1560, true),
1595
+ ("sidecar becomes taller", 1700, 1050, 1700, false),
1596
+ ]
1597
+ for testCase in cases {
1598
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
1599
+ let controller = UIViewController()
1600
+ window.rootViewController = controller
1601
+ let view = NativeListView(frame: window.bounds)
1602
+ controller.view.addSubview(view)
1603
+ window.isHidden = false
1604
+ defer {
1605
+ view.dispose()
1606
+ view.removeFromSuperview()
1607
+ window.isHidden = true
1608
+ window.rootViewController = nil
1609
+ }
1610
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1611
+ // Keep the viewport insets fixed while testing structural offset clamping.
1612
+ let explicitInset = testCase.zeroInset ? UIEdgeInsets.zero :
1613
+ UIEdgeInsets(top: 62, left: 0, bottom: 34, right: 0)
1614
+ list.contentInsetAdjustmentBehavior = .never
1615
+ list.contentInset = explicitInset
1616
+ view.mountContainerSlot(UIView(), atIndex: 0)
1617
+ view.mountContainerSlot(UIView(), atIndex: 1)
1618
+ let footer = UIView()
1619
+ view.mountContainerSlot(footer, atIndex: 2)
1620
+ let sidecar = UIView()
1621
+ view.mountContainerSlot(sidecar, atIndex: 3)
1622
+ view.setContainerSlotHeightsJson("[0,0,60,\(testCase.sidecar)]")
1623
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
1624
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30))
1625
+ view.layoutIfNeeded()
1626
+ list.layoutIfNeeded()
1627
+ drainMainQueue()
1628
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1629
+ XCTAssertEqual(list.contentSize.height, max(1860, CGFloat(testCase.sidecar)),
1630
+ accuracy: 1, testCase.name)
1631
+ list.contentOffset.y = testCase.offset
1632
+ list.layoutIfNeeded()
1633
+ XCTAssertEqual(list.contentOffset.y, testCase.offset, accuracy: 1, testCase.name)
1634
+
1635
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, transitionID: testCase.name))
1636
+ let completed = expectation(description: "Native structural display link: \(testCase.name)")
1637
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { completed.fulfill() }
1638
+ wait(for: [completed], timeout: 1)
1639
+ list.layoutIfNeeded()
1640
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1641
+ XCTAssertEqual(list.contentSize.height, testCase.height, accuracy: 1, testCase.name)
1642
+ let inset = list.adjustedContentInset
1643
+ let finalMaximum = max(-inset.top, testCase.height - list.bounds.height + inset.bottom)
1644
+ let footerTop: CGFloat = 1500
1645
+ let footerBottom: CGFloat = footerTop + 60
1646
+ let footerVisibleMinimum = footerBottom - list.bounds.height + inset.bottom
1647
+ let footerVisibleMaximum = footerTop - inset.top
1648
+ let expectedOffset = min(max(testCase.offset, footerVisibleMinimum),
1649
+ min(footerVisibleMaximum, finalMaximum))
1650
+ XCTAssertEqual(list.contentOffset.y, expectedOffset, accuracy: 1, testCase.name)
1651
+ XCTAssertNotNil(sidecar.superview, testCase.name)
1652
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1500, accuracy: 1, testCase.name)
1653
+ waitForStructuralFrames(0.1)
1654
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1655
+ XCTAssertEqual(list.contentSize.height, testCase.height, accuracy: 1, testCase.name)
1656
+ XCTAssertEqual(list.contentOffset.y, expectedOffset, accuracy: 1, testCase.name)
1657
+ }
1658
+ }
1659
+
1660
+ func testStructuralTransitionFromGridOrHorizontalCommitsAtomically() throws {
1661
+ try requireStructuralAnimation()
1662
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 600))
1663
+ let controller = UIViewController()
1664
+ window.rootViewController = controller
1665
+ let view = NativeListView(frame: window.bounds)
1666
+ controller.view.addSubview(view)
1667
+ window.isHidden = false
1668
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1669
+ defer {
1670
+ view.dispose()
1671
+ view.removeFromSuperview()
1672
+ window.isHidden = true
1673
+ window.rootViewController = nil
1674
+ }
1675
+ view.applySnapshotJson(try structuralRowsSnapshot(
1676
+ count: 6, generation: 1, layoutKind: "grid"))
1677
+ view.layoutIfNeeded()
1678
+ view.applySnapshotJson(try structuralRowsSnapshot(
1679
+ count: 8, generation: 2, transitionID: "from-grid", layoutKind: "linear"))
1680
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1681
+ XCTAssertEqual(list.numberOfItems(inSection: 0), 8)
1682
+
1683
+ view.applySnapshotJson(try structuralRowsSnapshot(
1684
+ count: 6, generation: 3, orientation: "horizontal"))
1685
+ view.layoutIfNeeded()
1686
+ view.applySnapshotJson(try structuralRowsSnapshot(
1687
+ count: 8, generation: 4, transitionID: "from-horizontal", layoutKind: "table"))
1688
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1689
+ XCTAssertEqual(list.numberOfItems(inSection: 0), 8)
1690
+ }
1691
+
1692
+ func testVisibleNativeCellsRemainBoundedAsRowsGrowTenfold() throws {
1693
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1694
+ let controller = UIViewController()
1695
+ window.rootViewController = controller
1696
+ let view = NativeListView(frame: window.bounds)
1697
+ controller.view.addSubview(view)
1698
+ window.isHidden = false
1699
+ defer {
1700
+ view.dispose()
1701
+ view.removeFromSuperview()
1702
+ window.isHidden = true
1703
+ window.rootViewController = nil
1704
+ }
1705
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1706
+ // Measure renderer reuse without UIKit's timing-dependent speculative prefetch cells.
1707
+ list.isPrefetchingEnabled = false
1708
+ func sampleCells(count: Int) throws -> [(visible: Int, attached: Int)] {
1709
+ view.applySnapshotJson(try structuralRowsSnapshot(count: count))
1710
+ view.layoutIfNeeded()
1711
+ list.layoutIfNeeded()
1712
+ let lastOffset = CGFloat(count * 60 - 600)
1713
+ return [CGFloat(0), lastOffset / 2, lastOffset].map { offset in
1714
+ list.setContentOffset(CGPoint(x: 0, y: offset), animated: false)
1715
+ list.layoutIfNeeded()
1716
+ drainMainQueue()
1717
+ list.layoutIfNeeded()
1718
+ return (list.visibleCells.count,
1719
+ list.subviews.compactMap { $0 as? NativeListRowHost }.count)
1720
+ }
1721
+ }
1722
+ let hundredCells = try sampleCells(count: 100)
1723
+ let thousandCells = try sampleCells(count: 1000)
1724
+ print("NativeList 100 visible/attached first/mid/tail: \(hundredCells)")
1725
+ print("NativeList 1000 visible/attached first/mid/tail: \(thousandCells)")
1726
+ let visibleCellLimit = Int(ceil(list.bounds.height / 60)) + 2
1727
+ XCTAssertTrue(hundredCells.allSatisfy {
1728
+ $0.visible > 0 && $0.visible <= visibleCellLimit && $0.attached >= $0.visible
1729
+ })
1730
+ XCTAssertTrue(thousandCells.allSatisfy {
1731
+ $0.visible > 0 && $0.visible <= visibleCellLimit && $0.attached >= $0.visible
1732
+ })
1733
+ // UIKit also retains offscreen cells in subviews. Their count may exceed
1734
+ // the visible budget, but must remain bounded as the data grows tenfold.
1735
+ XCTAssertLessThanOrEqual(thousandCells.map(\.attached).max() ?? 0,
1736
+ (hundredCells.map(\.attached).max() ?? 0) + 4)
1737
+ }
1738
+
1739
+ func testStructuralTransitionRapidReversalKeepsRetiringContentAtNaturalHeight() throws {
1740
+ try requireStructuralAnimation()
1741
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1742
+ let controller = UIViewController()
1743
+ window.rootViewController = controller
1744
+ let view = NativeListView(frame: window.bounds)
1745
+ controller.view.addSubview(view)
1746
+ window.isHidden = false
1747
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
1748
+ let footer = UIView()
1749
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
1750
+ view.mountContainerSlot(footer, atIndex: 2)
1751
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
1752
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 1))
1753
+ view.layoutIfNeeded()
1754
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1755
+ list.layoutIfNeeded()
1756
+ drainMainQueue()
1757
+ list.contentOffset.y = 900
1758
+ list.layoutIfNeeded()
1759
+
1760
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 2,
1761
+ transitionID: "expand-first", durationMs: 400))
1762
+ waitForStructuralFrames(0.08)
1763
+ list.contentOffset.y = 1100
1764
+ list.layoutIfNeeded()
1765
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 3,
1766
+ transitionID: "collapse-middle", durationMs: 400))
1767
+ waitForStructuralFrames(0.08)
1768
+ list.layoutIfNeeded()
1769
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
1770
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
1771
+ let clip = try XCTUnwrap(flow.tailClip)
1772
+ let retiring = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 25, section: 0)) as? NativeListRowHost)
1773
+ XCTAssertGreaterThan(clip.endY, 1500)
1774
+ XCTAssertLessThan(clip.endY, 1800)
1775
+ XCTAssertEqual(retiring.bounds.height, 60, accuracy: 1)
1776
+ XCTAssertEqual(retiring.contentView.bounds.height, 60, accuracy: 1)
1777
+ XCTAssertNil(retiring.structuralContentHeight)
1778
+ XCTAssertEqual(retiring.alpha, 1, accuracy: 0.01)
1779
+ XCTAssertFalse(retiring.isUserInteractionEnabled)
1780
+ XCTAssertTrue(retiring.accessibilityElementsHidden)
1781
+ XCTAssertEqual(footer.convert(.zero, to: list).y,
1782
+ clip.endY, accuracy: 1)
1783
+
1784
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 4,
1785
+ transitionID: "expand-last", durationMs: 400))
1786
+ waitForStructuralFrames(0.5)
1787
+ list.layoutIfNeeded()
1788
+ let keys = source.snapshot().itemIdentifiers
1789
+ XCTAssertEqual(keys, (0..<30).map { "row-\($0)" })
1790
+ XCTAssertEqual(Set(keys).count, 30)
1791
+ XCTAssertEqual(list.contentSize.height, 1860, accuracy: 1)
1792
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1800, accuracy: 1)
1793
+ XCTAssertGreaterThanOrEqual(list.contentOffset.y, -list.adjustedContentInset.top - 1)
1794
+ XCTAssertLessThanOrEqual(list.contentOffset.y,
1795
+ list.contentSize.height - list.bounds.height + list.adjustedContentInset.bottom + 1)
1796
+ for case let cell as NativeListRowHost in list.visibleCells {
1797
+ XCTAssertEqual(cell.alpha, 1, accuracy: 0.01)
1798
+ XCTAssertNil(cell.structuralContentHeight)
1799
+ }
1800
+ }
1801
+
1802
+ func testHybridSettlementListenerFollowsRegistration() throws {
1803
+ let hybrid = HybridNativeList()
1804
+ let host = try XCTUnwrap(hybrid.view as? NativeListView)
1805
+ var first: [String] = []
1806
+ var second: [String] = []
1807
+ XCTAssertNil(host.onStructuralTransitionSettled)
1808
+
1809
+ hybrid.onStructuralTransitionSettled = { first.append($0) }
1810
+ host.onStructuralTransitionSettled?("first")
1811
+ XCTAssertEqual(first, ["first"])
1812
+
1813
+ hybrid.onStructuralTransitionSettled = { second.append($0) }
1814
+ host.onStructuralTransitionSettled?("second")
1815
+ XCTAssertEqual(first, ["first"])
1816
+ XCTAssertEqual(second, ["second"])
1817
+
1818
+ hybrid.onStructuralTransitionSettled = nil
1819
+ XCTAssertNil(host.onStructuralTransitionSettled)
1820
+ hybrid.dispose()
1821
+ }
1822
+
1823
+ func testDisclosureWithoutListenerStillSettlesWithoutReplay() throws {
1824
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1825
+ let controller = UIViewController()
1826
+ window.rootViewController = controller
1827
+ let view = NativeListView(frame: window.bounds)
1828
+ controller.view.addSubview(view)
1829
+ window.isHidden = false
1830
+ defer {
1831
+ view.dispose()
1832
+ view.removeFromSuperview()
1833
+ window.isHidden = true
1834
+ window.rootViewController = nil
1835
+ }
1836
+ for index in 0..<6 { view.mountContainerSlot(UIView(), atIndex: index) }
1837
+ view.setContainerSlotHeightsJson("[0,0,60,0,100,40]")
1838
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1839
+ disclosureExpanded: false))
1840
+ view.layoutIfNeeded()
1841
+
1842
+ let first = try structuralRowsSnapshot(count: 6, generation: 2,
1843
+ transitionID: "without-listener", durationMs: 0, disclosureExpanded: true)
1844
+ view.applySnapshotJson(first)
1845
+ drainMainQueue()
1846
+ XCTAssertEqual(Mirror(reflecting: view).descendant("pendingDisclosureSettlement")
1847
+ .map { Mirror(reflecting: $0).children.count }, 0)
1848
+
1849
+ var settlements: [[String: Any]] = []
1850
+ view.onStructuralTransitionSettled = { payload in
1851
+ guard let data = payload.data(using: .utf8),
1852
+ let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1853
+ return
1854
+ }
1855
+ settlements.append(value)
1856
+ }
1857
+ view.applySnapshotJson(first)
1858
+ drainMainQueue()
1859
+ XCTAssertTrue(settlements.isEmpty)
1860
+
1861
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
1862
+ transitionID: "with-listener", durationMs: 0, disclosureExpanded: false))
1863
+ drainMainQueue()
1864
+ XCTAssertEqual(settlements.count, 1)
1865
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "with-listener")
1866
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
1867
+ }
1868
+
1869
+ func testDisclosureInitialEndpoints() throws {
1870
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1871
+ let controller = UIViewController()
1872
+ window.rootViewController = controller
1873
+ let view = NativeListView(frame: window.bounds)
1874
+ controller.view.addSubview(view)
1875
+ window.isHidden = false
1876
+ defer {
1877
+ view.dispose()
1878
+ view.removeFromSuperview()
1879
+ window.isHidden = true
1880
+ window.rootViewController = nil
1881
+ }
1882
+ let slots = (0..<6).map { _ in UIView() }
1883
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
1884
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1885
+ var settlements: [String] = []
1886
+ view.onStructuralTransitionSettled = { settlements.append($0) }
1887
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1888
+ list.contentInsetAdjustmentBehavior = .never
1889
+ list.contentInset = .zero
1890
+
1891
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1892
+ disclosureExpanded: false))
1893
+ view.layoutIfNeeded()
1894
+ list.layoutIfNeeded()
1895
+ let footerHost = try XCTUnwrap(slots[2].superview)
1896
+ let contentHost = try XCTUnwrap(slots[4].superview)
1897
+ let toggleHost = try XCTUnwrap(slots[5].superview)
1898
+ XCTAssertEqual(contentHost.frame.minY, 360, accuracy: 1)
1899
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1900
+ XCTAssertTrue(contentHost.isHidden)
1901
+ XCTAssertFalse(contentHost.isUserInteractionEnabled)
1902
+ XCTAssertTrue(contentHost.accessibilityElementsHidden)
1903
+ XCTAssertEqual(toggleHost.frame.minY, 360, accuracy: 1)
1904
+ XCTAssertEqual(footerHost.frame.minY, 400, accuracy: 1)
1905
+ XCTAssertEqual(list.contentSize.height, 540, accuracy: 1)
1906
+ XCTAssertTrue(toggleHost.point(inside: CGPoint(x: 10, y: 10), with: nil))
1907
+ XCTAssertTrue(settlements.isEmpty)
1908
+
1909
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
1910
+ disclosureExpanded: true))
1911
+ view.layoutIfNeeded()
1912
+ list.layoutIfNeeded()
1913
+ XCTAssertEqual(contentHost.frame.minY, 360, accuracy: 1)
1914
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1915
+ XCTAssertFalse(contentHost.isHidden)
1916
+ XCTAssertTrue(contentHost.isUserInteractionEnabled)
1917
+ XCTAssertFalse(contentHost.accessibilityElementsHidden)
1918
+ XCTAssertEqual(toggleHost.frame.minY, 460, accuracy: 1)
1919
+ XCTAssertEqual(footerHost.frame.minY, 520, accuracy: 1)
1920
+ XCTAssertEqual(list.contentSize.height, 660, accuracy: 1)
1921
+ XCTAssertTrue(settlements.isEmpty)
1922
+ }
1923
+
1924
+ func testDisclosureCollapseClock() throws {
1925
+ try requireStructuralAnimation()
1926
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1927
+ let controller = UIViewController()
1928
+ window.rootViewController = controller
1929
+ let view = NativeListView(frame: window.bounds)
1930
+ controller.view.addSubview(view)
1931
+ window.isHidden = false
1932
+ defer {
1933
+ view.dispose()
1934
+ view.removeFromSuperview()
1935
+ window.isHidden = true
1936
+ window.rootViewController = nil
1937
+ }
1938
+ let slots = (0..<6).map { _ in UIView() }
1939
+ let expandedChild = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 100))
1940
+ slots[4].addSubview(expandedChild)
1941
+ let toggle = UIButton(frame: CGRect(x: 0, y: 0, width: 320, height: 40))
1942
+ for index in 0..<6 {
1943
+ view.mountContainerSlot(index == 5 ? toggle : slots[index], atIndex: index)
1944
+ }
1945
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1946
+ var settlements: [[String: Any]] = []
1947
+ view.onStructuralTransitionSettled = { payload in
1948
+ guard let data = payload.data(using: .utf8),
1949
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1950
+ return
1951
+ }
1952
+ settlements.append(object)
1953
+ }
1954
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1955
+ list.contentInsetAdjustmentBehavior = .never
1956
+ list.contentInset = .zero
1957
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1,
1958
+ disclosureExpanded: true))
1959
+ view.layoutIfNeeded()
1960
+ list.layoutIfNeeded()
1961
+ drainMainQueue()
1962
+ list.contentOffset.y = 2400
1963
+ list.layoutIfNeeded()
1964
+
1965
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
1966
+ transitionID: "disclosure-collapse", durationMs: 800,
1967
+ disclosureExpanded: false))
1968
+ waitForStructuralFrames(0.16)
1969
+ list.layoutIfNeeded()
1970
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
1971
+ let clip = try XCTUnwrap(flow.tailClip)
1972
+ let contentHost = try XCTUnwrap(slots[4].superview)
1973
+ let toggleHost = try XCTUnwrap(toggle.superview)
1974
+ let footerHost = try XCTUnwrap(slots[2].superview)
1975
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1976
+ XCTAssertEqual(contentHost.frame.minY, clip.endY, accuracy: 1)
1977
+ let contentVisible = toggleHost.frame.minY - contentHost.frame.minY
1978
+ XCTAssertGreaterThan(contentVisible, 0)
1979
+ XCTAssertLessThan(contentVisible, 100)
1980
+ XCTAssertEqual(try XCTUnwrap(contentHost.layer.mask).frame.height,
1981
+ contentVisible, accuracy: 1)
1982
+ XCTAssertFalse(contentHost.isUserInteractionEnabled)
1983
+ XCTAssertTrue(contentHost.accessibilityElementsHidden)
1984
+ XCTAssertTrue(toggleHost.isUserInteractionEnabled)
1985
+ XCTAssertFalse(toggleHost.accessibilityElementsHidden)
1986
+ XCTAssertTrue(toggleHost.point(inside: CGPoint(x: 10, y: 10), with: nil))
1987
+ XCTAssertEqual(toggleHost.frame.minY, clip.endY + contentVisible, accuracy: 1)
1988
+ let inset = footerHost.frame.minY - toggleHost.frame.maxY
1989
+ XCTAssertGreaterThan(inset, 0)
1990
+ XCTAssertLessThan(inset, 20)
1991
+ XCTAssertTrue(settlements.isEmpty)
1992
+
1993
+ waitForStructuralFrames(0.75)
1994
+ list.layoutIfNeeded()
1995
+ XCTAssertNil(flow.tailClip)
1996
+ XCTAssertEqual(toggleHost.frame.minY, 360, accuracy: 1)
1997
+ XCTAssertEqual(footerHost.frame.minY, 400, accuracy: 1)
1998
+ XCTAssertTrue(contentHost.isHidden)
1999
+ XCTAssertEqual(settlements.count, 1)
2000
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "disclosure-collapse")
2001
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
2002
+ XCTAssertEqual(settlements.first?["settledExpanded"] as? Bool, false)
2003
+
2004
+ let roots = (0..<6).map { $0 == 5 ? toggle : slots[$0] }
2005
+ let hosts = roots.map(\.superview)
2006
+ XCTAssertTrue(hosts.allSatisfy { $0 != nil })
2007
+ let toggleWindowOrigin = toggleHost.convert(CGPoint.zero, to: window)
2008
+ let footerWindowOrigin = footerHost.convert(CGPoint.zero, to: window)
2009
+ let settledOffset = list.contentOffset
2010
+ let settledSize = list.contentSize
2011
+ expandedChild.removeFromSuperview()
2012
+ view.setContainerSlotHeightsJson("[0,0,140,0,0,40]")
2013
+ view.layoutIfNeeded()
2014
+ list.layoutIfNeeded()
2015
+ drainMainQueue()
2016
+ view.layoutIfNeeded()
2017
+ list.layoutIfNeeded()
2018
+ for (root, host) in zip(roots, hosts) {
2019
+ XCTAssertTrue(root.superview === host)
2020
+ XCTAssertTrue(root.window === window)
2021
+ }
2022
+ XCTAssertEqual(toggleHost.convert(CGPoint.zero, to: window).x, toggleWindowOrigin.x, accuracy: 1)
2023
+ XCTAssertEqual(toggleHost.convert(CGPoint.zero, to: window).y, toggleWindowOrigin.y, accuracy: 1)
2024
+ XCTAssertEqual(footerHost.convert(CGPoint.zero, to: window).x, footerWindowOrigin.x, accuracy: 1)
2025
+ XCTAssertEqual(footerHost.convert(CGPoint.zero, to: window).y, footerWindowOrigin.y, accuracy: 1)
2026
+ XCTAssertEqual(list.contentOffset.x, settledOffset.x, accuracy: 1)
2027
+ XCTAssertEqual(list.contentOffset.y, settledOffset.y, accuracy: 1)
2028
+ XCTAssertEqual(list.contentSize.width, settledSize.width, accuracy: 1)
2029
+ XCTAssertEqual(list.contentSize.height, settledSize.height, accuracy: 1)
2030
+ XCTAssertEqual(settlements.count, 1)
2031
+ }
2032
+
2033
+ func testDisclosureAckLatest() throws {
2034
+ try requireStructuralAnimation()
2035
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2036
+ let controller = UIViewController()
2037
+ window.rootViewController = controller
2038
+ let view = NativeListView(frame: window.bounds)
2039
+ controller.view.addSubview(view)
2040
+ window.isHidden = false
2041
+ defer {
2042
+ view.dispose()
2043
+ view.removeFromSuperview()
2044
+ window.isHidden = true
2045
+ window.rootViewController = nil
2046
+ }
2047
+ let slots = (0..<6).map { _ in UIView() }
2048
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
2049
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
2050
+ var settlements: [(String, String, Bool)] = []
2051
+ let latestSettled = expectation(description: "Latest disclosure transition settled")
2052
+ view.onStructuralTransitionSettled = { payload in
2053
+ guard let data = payload.data(using: .utf8),
2054
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
2055
+ let id = object["transitionId"] as? String,
2056
+ let status = object["status"] as? String,
2057
+ let expanded = object["settledExpanded"] as? Bool else { return }
2058
+ settlements.append((id, status, expanded))
2059
+ if id == "collapse-latest" { latestSettled.fulfill() }
2060
+ }
2061
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
2062
+ disclosureExpanded: false))
2063
+ view.layoutIfNeeded()
2064
+ drainMainQueue()
2065
+ XCTAssertTrue(settlements.isEmpty)
2066
+
2067
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2068
+ transitionID: "same-rows", durationMs: 400, disclosureExpanded: false))
2069
+ drainMainQueue()
2070
+ XCTAssertEqual(settlements.map(\.0), ["same-rows"])
2071
+ XCTAssertEqual(settlements.first?.1, "completed")
2072
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2073
+ transitionID: "same-rows", durationMs: 400, disclosureExpanded: false))
2074
+ drainMainQueue()
2075
+ XCTAssertEqual(settlements.count, 1)
2076
+
2077
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 4,
2078
+ transitionID: "expand-superseded", durationMs: 400,
2079
+ disclosureExpanded: true))
2080
+ // Supersede on the same main-thread turn: a timed wait can outlast the
2081
+ // expansion on a busy simulator and legitimately deliver its settlement.
2082
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink")
2083
+ as? CADisplayLink)
2084
+ XCTAssertEqual(settlements.map(\.0), ["same-rows"])
2085
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 5,
2086
+ transitionID: "collapse-latest", durationMs: 400,
2087
+ disclosureExpanded: false))
2088
+ wait(for: [latestSettled], timeout: 2)
2089
+ XCTAssertEqual(settlements.map(\.0), ["same-rows", "collapse-latest"])
2090
+ XCTAssertEqual(settlements.last?.1, "completed")
2091
+ XCTAssertEqual(settlements.last?.2, false)
2092
+ XCTAssertTrue(slots[4].superview?.isHidden ?? false)
2093
+
2094
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 0, generation: 6,
2095
+ transitionID: "empty-immediate", durationMs: 0,
2096
+ disclosureExpanded: false))
2097
+ drainMainQueue()
2098
+ XCTAssertEqual(settlements.map(\.0),
2099
+ ["same-rows", "collapse-latest", "empty-immediate"])
2100
+ XCTAssertEqual(settlements.last?.1, "completed")
2101
+ }
2102
+
2103
+ func testDisclosureGeometryFallbackUsesLatestSnapshot() throws {
2104
+ try requireStructuralAnimation()
2105
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2106
+ let controller = UIViewController()
2107
+ window.rootViewController = controller
2108
+ let view = NativeListView(frame: window.bounds)
2109
+ controller.view.addSubview(view)
2110
+ window.isHidden = false
2111
+ defer {
2112
+ view.dispose()
2113
+ view.removeFromSuperview()
2114
+ window.isHidden = true
2115
+ window.rootViewController = nil
2116
+ }
2117
+ let slots = (0..<6).map { _ in UIView() }
2118
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
2119
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
2120
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2121
+ list.contentInsetAdjustmentBehavior = .never
2122
+ var settlements: [(String, String)] = []
2123
+ view.onStructuralTransitionSettled = { payload in
2124
+ guard let data = payload.data(using: .utf8),
2125
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
2126
+ let id = object["transitionId"] as? String,
2127
+ let status = object["status"] as? String else { return }
2128
+ settlements.append((id, status))
2129
+ }
2130
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
2131
+ disclosureExpanded: false))
2132
+ view.layoutIfNeeded()
2133
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2134
+ transitionID: "expand", durationMs: 800, disclosureExpanded: true))
2135
+ waitForStructuralFrames(0.08)
2136
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2137
+
2138
+ view.setContainerSlotHeightsJson("[0,0,160,0,100,40]", followedBySnapshot: true)
2139
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
2140
+ transitionID: "expand", durationMs: 800, disclosureExpanded: true))
2141
+ drainMainQueue()
2142
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2143
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
2144
+ let contentHost = try XCTUnwrap(slots[4].superview)
2145
+ let toggleHost = try XCTUnwrap(slots[5].superview)
2146
+ let footerHost = try XCTUnwrap(slots[2].superview)
2147
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
2148
+ XCTAssertEqual(toggleHost.frame.minY, 3_100, accuracy: 1)
2149
+ XCTAssertEqual(footerHost.frame.minY, 3_160, accuracy: 1)
2150
+ XCTAssertEqual(footerHost.bounds.height, 160, accuracy: 1)
2151
+ XCTAssertEqual(settlements.map(\.0), ["expand"])
2152
+ XCTAssertEqual(settlements.last?.1, "interrupted")
2153
+
2154
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 4,
2155
+ transitionID: "collapse", durationMs: 800, disclosureExpanded: false))
2156
+ waitForStructuralFrames(0.08)
2157
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 5,
2158
+ transitionID: "collapse", durationMs: 800))
2159
+ drainMainQueue()
2160
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2161
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
2162
+ XCTAssertEqual(settlements.map(\.0), ["expand"],
2163
+ "Removing disclosure without a new command cannot acknowledge the old target")
2164
+ }
2165
+
2166
+ func testDisclosureLateCompletionCannotSettleNewCommand() throws {
2167
+ try requireStructuralAnimation()
2168
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2169
+ let controller = UIViewController()
2170
+ window.rootViewController = controller
2171
+ let view = NativeListView(frame: window.bounds)
2172
+ controller.view.addSubview(view)
2173
+ window.isHidden = false
2174
+ defer {
2175
+ view.dispose()
2176
+ view.removeFromSuperview()
2177
+ window.isHidden = true
2178
+ window.rootViewController = nil
2179
+ }
2180
+ for index in 0..<6 { view.mountContainerSlot(UIView(), atIndex: index) }
2181
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
2182
+ var settled: [String] = []
2183
+ view.onStructuralTransitionSettled = { payload in
2184
+ guard let data = payload.data(using: .utf8),
2185
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
2186
+ let id = object["transitionId"] as? String else { return }
2187
+ settled.append(id)
2188
+ }
2189
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
2190
+ disclosureExpanded: false))
2191
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2192
+ transitionID: "old-direct", disclosureExpanded: false))
2193
+ let oldCompletedBeforeReplacement = settled.contains("old-direct")
2194
+ XCTAssertFalse(oldCompletedBeforeReplacement,
2195
+ "The older diffable completion must remain pending when its replacement starts")
2196
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
2197
+ transitionID: "latest-expand", durationMs: 800, disclosureExpanded: true))
2198
+ drainMainQueue()
2199
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2200
+ XCTAssertTrue(settled.isEmpty,
2201
+ "An older diffable completion must not settle the active newer transition")
2202
+ waitForStructuralFrames(0.9)
2203
+ XCTAssertEqual(settled, ["latest-expand"])
2204
+ }
2205
+
2206
+ func testDisclosureContentGrowthAndDragSettlement() throws {
2207
+ try requireStructuralAnimation()
2208
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2209
+ let controller = UIViewController()
2210
+ window.rootViewController = controller
2211
+ let view = NativeListView(frame: window.bounds)
2212
+ controller.view.addSubview(view)
2213
+ window.isHidden = false
2214
+ defer {
2215
+ view.dispose()
2216
+ view.removeFromSuperview()
2217
+ window.isHidden = true
2218
+ window.rootViewController = nil
2219
+ }
2220
+ let slots = (0..<6).map { _ in UIView() }
2221
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
2222
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
2223
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2224
+ list.contentInsetAdjustmentBehavior = .never
2225
+ let contentHost = try XCTUnwrap(slots[4].superview)
2226
+ var settlements: [(String, String)] = []
2227
+ let growSettled = expectation(description: "Disclosure growth settles")
2228
+ view.onStructuralTransitionSettled = { payload in
2229
+ guard let data = payload.data(using: .utf8),
2230
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
2231
+ let id = object["transitionId"] as? String,
2232
+ let status = object["status"] as? String else { return }
2233
+ settlements.append((id, status))
2234
+ if id == "grow" && status == "completed" { growSettled.fulfill() }
2235
+ }
2236
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
2237
+ disclosureExpanded: false))
2238
+ view.layoutIfNeeded()
2239
+ list.layoutIfNeeded()
2240
+ drainMainQueue()
2241
+ XCTAssertTrue(contentHost.isHidden, "Initial collapsed content must be hidden")
2242
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2243
+
2244
+ let growthPhase = expectation(description: "Disclosure growth presents a partial content mask")
2245
+ var growthObserved = false
2246
+ var growthLast = "no frame sampled"
2247
+ let growthStartedAt = CACurrentMediaTime()
2248
+ let growthProbe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in
2249
+ let clock = Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink
2250
+ let tail = Mirror(reflecting: view).descendant("structuralTail")
2251
+ let tailActive = tail.map { !Mirror(reflecting: $0).children.isEmpty } ?? false
2252
+ let maskHeight = contentHost.layer.mask?.frame.height
2253
+ growthLast = "clock=\(clock != nil) tail=\(tailActive) "
2254
+ + "mask=\(String(describing: maskHeight)) bounds=\(contentHost.bounds.height) "
2255
+ + "elapsed=\(CACurrentMediaTime() - growthStartedAt) settlements=\(settlements)"
2256
+ guard !growthObserved, let clock, tailActive, let maskHeight,
2257
+ maskHeight > 0, maskHeight < 100 else { return }
2258
+ growthObserved = true
2259
+ let animationStart = Mirror(reflecting: view).descendant("structuralAnimationStart")
2260
+ as? CFTimeInterval
2261
+ let animationDuration = Mirror(reflecting: view).descendant("structuralAnimationDuration")
2262
+ as? CFTimeInterval
2263
+ XCTAssertNotNil(animationStart, "The active disclosure clock must have a start time")
2264
+ XCTAssertNotNil(animationDuration, "The active disclosure clock must have a duration")
2265
+ view.setContainerSlotHeightsJson("[0,0,140,0,140,40]")
2266
+ XCTAssertTrue(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink
2267
+ === clock, "Content growth must retain the active display link")
2268
+ XCTAssertEqual(Mirror(reflecting: view).descendant("structuralAnimationStart")
2269
+ as? CFTimeInterval, animationStart, "Content growth must keep the original deadline")
2270
+ XCTAssertEqual(Mirror(reflecting: view).descendant("structuralAnimationDuration")
2271
+ as? CFTimeInterval, animationDuration, "Content growth must keep the original duration")
2272
+ XCTAssertEqual(contentHost.layer.mask?.frame.height ?? -1, maskHeight, accuracy: 1,
2273
+ "Content growth must not jump the visible mask")
2274
+ growthPhase.fulfill()
2275
+ }
2276
+ RunLoop.main.add(growthProbe, forMode: .common)
2277
+ defer { growthProbe.invalidate() }
2278
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2279
+ transitionID: "grow", durationMs: 800, disclosureExpanded: true))
2280
+ wait(for: [growthPhase], timeout: 1.5)
2281
+ guard growthObserved else {
2282
+ XCTFail("No partial disclosure growth frame observed: \(growthLast)")
2283
+ return
2284
+ }
2285
+ growthProbe.invalidate()
2286
+ wait(for: [growSettled], timeout: 1.5)
2287
+ XCTAssertEqual(contentHost.bounds.height, 140, accuracy: 1)
2288
+ XCTAssertNil(contentHost.layer.mask)
2289
+ XCTAssertTrue(contentHost.isUserInteractionEnabled)
2290
+ XCTAssertEqual(settlements.map(\.0), ["grow"], "Growth must settle exactly once")
2291
+ XCTAssertEqual(settlements.last?.1, "completed")
2292
+
2293
+ let collapsePhase = expectation(description: "Disclosure collapse presents a partial content mask")
2294
+ var collapseObserved = false
2295
+ var collapseLast = "no frame sampled"
2296
+ let collapseStartedAt = CACurrentMediaTime()
2297
+ let collapseProbe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in
2298
+ let clock = Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink
2299
+ let tail = Mirror(reflecting: view).descendant("structuralTail")
2300
+ let tailActive = tail.map { !Mirror(reflecting: $0).children.isEmpty } ?? false
2301
+ let maskHeight = contentHost.layer.mask?.frame.height
2302
+ collapseLast = "clock=\(clock != nil) tail=\(tailActive) "
2303
+ + "mask=\(String(describing: maskHeight)) bounds=\(contentHost.bounds.height) "
2304
+ + "elapsed=\(CACurrentMediaTime() - collapseStartedAt) settlements=\(settlements)"
2305
+ guard !collapseObserved, clock != nil, tailActive, let maskHeight,
2306
+ maskHeight > 0, maskHeight < 140 else { return }
2307
+ collapseObserved = true
2308
+ view.scrollViewWillBeginDragging(list)
2309
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink,
2310
+ "Dragging must stop the active disclosure display link")
2311
+ let remainingTail = Mirror(reflecting: view).descendant("structuralTail")
2312
+ XCTAssertNotNil(remainingTail, "The structural tail field must remain observable")
2313
+ XCTAssertFalse(remainingTail.map { !Mirror(reflecting: $0).children.isEmpty } ?? true,
2314
+ "Dragging must clear the temporary structural tail")
2315
+ XCTAssertTrue(contentHost.isHidden, "Dragging a collapse must hide content")
2316
+ XCTAssertEqual(settlements.map(\.0), ["grow", "drag"],
2317
+ "Dragging must settle the collapse exactly once")
2318
+ XCTAssertEqual(settlements.last?.1, "interrupted")
2319
+ collapsePhase.fulfill()
2320
+ }
2321
+ RunLoop.main.add(collapseProbe, forMode: .common)
2322
+ defer { collapseProbe.invalidate() }
2323
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2324
+ transitionID: "drag", durationMs: 800, disclosureExpanded: false))
2325
+ wait(for: [collapsePhase], timeout: 1.5)
2326
+ guard collapseObserved else {
2327
+ XCTFail("No partial disclosure collapse frame observed: \(collapseLast)")
2328
+ return
2329
+ }
2330
+ collapseProbe.invalidate()
2331
+ }
2332
+
2333
+ func testDisclosureDirectCollapseKeepsToggleVisible() throws {
2334
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 600))
2335
+ let controller = UIViewController()
2336
+ window.rootViewController = controller
2337
+ let view = NativeListView(frame: window.bounds)
2338
+ controller.view.addSubview(view)
2339
+ window.isHidden = false
2340
+ defer {
2341
+ view.dispose()
2342
+ view.removeFromSuperview()
2343
+ window.isHidden = true
2344
+ window.rootViewController = nil
2345
+ }
2346
+ let slots = (0..<6).map { _ in UIView() }
2347
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
2348
+ view.setSidecarLayoutJson("{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}")
2349
+ view.setContainerSlotHeightsJson("[0,0,900,2200,100,40]")
2350
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2351
+ list.contentInsetAdjustmentBehavior = .never
2352
+ list.contentInset = .zero
2353
+ var settlements: [[String: Any]] = []
2354
+ view.onStructuralTransitionSettled = { payload in
2355
+ guard let data = payload.data(using: .utf8),
2356
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
2357
+ return
2358
+ }
2359
+ settlements.append(object)
2360
+ }
2361
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1,
2362
+ disclosureExpanded: true))
2363
+ view.layoutIfNeeded()
2364
+ list.layoutIfNeeded()
2365
+ list.contentOffset.y = 2_600
2366
+ list.layoutIfNeeded()
2367
+ XCTAssertEqual(list.contentOffset.y, 2_600, accuracy: 1)
2368
+
2369
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2370
+ transitionID: "direct-collapse", durationMs: 0, disclosureExpanded: false))
2371
+ drainMainQueue()
2372
+ list.layoutIfNeeded()
2373
+ let toggle = try XCTUnwrap(slots[5].superview)
2374
+ XCTAssertEqual(toggle.frame.minY, 360, accuracy: 1)
2375
+ XCTAssertEqual(list.contentSize.height, 2_200, accuracy: 1)
2376
+ XCTAssertEqual(list.contentOffset.y, 360, accuracy: 1,
2377
+ "A direct collapsed endpoint must expose the stable toggle despite a taller sidecar")
2378
+ XCTAssertEqual(settlements.count, 1)
2379
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "direct-collapse")
2380
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
2381
+
2382
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
2383
+ disclosureExpanded: true))
2384
+ drainMainQueue()
2385
+ view.frame.size.height = 0
2386
+ view.layoutIfNeeded()
2387
+ XCTAssertEqual(list.bounds.height, 0)
2388
+ view.scrollToOffset(500, animated: false)
2389
+ let pending = try XCTUnwrap(Mirror(reflecting: view).descendant("pendingScrollRequest"))
2390
+ XCTAssertEqual(Mirror(reflecting: pending).children.count, 1,
2391
+ "The explicit command must still be queued when the direct collapse is accepted")
2392
+ view.frame.size.height = 600
2393
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 4,
2394
+ transitionID: "direct-collapse-after-pending-scroll", durationMs: 0,
2395
+ disclosureExpanded: false))
2396
+ drainMainQueue()
2397
+ view.layoutIfNeeded()
2398
+ list.layoutIfNeeded()
2399
+ drainMainQueue()
2400
+ XCTAssertEqual(list.contentOffset.y, 500, accuracy: 1,
2401
+ "A direct collapse must not replace an already pending explicit scroll")
2402
+ XCTAssertEqual(settlements.count, 2)
2403
+ XCTAssertEqual(settlements.last?["transitionId"] as? String,
2404
+ "direct-collapse-after-pending-scroll")
2405
+ }
2406
+
2407
+ func testStructuralTailKeepsMiddleRowsNaturalAndFooterAttachedDuringCollapse() throws {
2408
+ try requireStructuralAnimation()
2409
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2410
+ let controller = UIViewController()
2411
+ window.rootViewController = controller
2412
+ let view = NativeListView(frame: window.bounds)
2413
+ var retiredActions = 0
2414
+ view.onRowAction = { _ in retiredActions += 1 }
2415
+ controller.view.addSubview(view)
2416
+ window.isHidden = false
2417
+ defer {
2418
+ view.dispose()
2419
+ view.removeFromSuperview()
2420
+ window.isHidden = true
2421
+ window.rootViewController = nil
2422
+ }
2423
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2424
+ let footer = UIView()
2425
+ view.mountContainerSlot(footer, atIndex: 2)
2426
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2427
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2428
+ list.contentInsetAdjustmentBehavior = .never
2429
+ list.contentInset = .zero
2430
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2431
+ view.layoutIfNeeded()
2432
+ list.layoutIfNeeded()
2433
+ drainMainQueue()
2434
+ list.contentOffset.y = 2400
2435
+ list.layoutIfNeeded()
2436
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2437
+ transitionID: "tail-50-to-6", durationMs: 800))
2438
+ waitForStructuralFrames(0.16)
2439
+ list.layoutIfNeeded()
2440
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2441
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2442
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2443
+ let clip = try XCTUnwrap(flow.tailClip)
2444
+ XCTAssertEqual(clip.firstIndex, 6)
2445
+ XCTAssertGreaterThan(clip.endY, 360)
2446
+ XCTAssertLessThan(clip.endY, 3000)
2447
+ let tailCells = list.visibleCells.compactMap { cell -> NativeListRowHost? in
2448
+ guard let path = list.indexPath(for: cell), path.item >= 6 else { return nil }
2449
+ return cell as? NativeListRowHost
2450
+ }
2451
+ XCTAssertFalse(tailCells.isEmpty)
2452
+ XCTAssertTrue(tailCells.allSatisfy { abs($0.bounds.height - 60) <= 1 && $0.alpha == 1 })
2453
+ XCTAssertTrue(tailCells.allSatisfy { !$0.isUserInteractionEnabled && $0.accessibilityElementsHidden })
2454
+ XCTAssertFalse(view.collectionView(list, shouldSelectItemAt: IndexPath(item: 25, section: 0)))
2455
+ view.collectionView(list, didSelectItemAt: IndexPath(item: 25, section: 0))
2456
+ XCTAssertEqual(retiredActions, 0)
2457
+ XCTAssertEqual(footer.convert(.zero, to: list).y, clip.endY, accuracy: 1)
2458
+ let footerBottomBeforeResize = footer.convert(.zero, to: list).y + 60
2459
+ view.setContainerSlotHeightsJson("[0,0,80,0]")
2460
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 80,
2461
+ footerBottomBeforeResize, accuracy: 1)
2462
+ let footerHost = try XCTUnwrap(footer.superview)
2463
+ let hiddenTop = try XCTUnwrap(flow.tailClip).endY - footerHost.frame.minY
2464
+ if hiddenTop > 1 {
2465
+ XCTAssertFalse(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop / 2), with: nil))
2466
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop + 1), with: nil))
2467
+ }
2468
+ waitForStructuralFrames(0.06)
2469
+ list.layoutIfNeeded()
2470
+ XCTAssertEqual(footer.convert(.zero, to: list).y, try XCTUnwrap(flow.tailClip).endY,
2471
+ accuracy: 1)
2472
+ let footerBottomBeforeSecondResize = footer.convert(.zero, to: list).y + 80
2473
+ view.setContainerSlotHeightsJson("[0,0,100,0]")
2474
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 100,
2475
+ footerBottomBeforeSecondResize, accuracy: 1)
2476
+ waitForStructuralFrames(0.7)
2477
+ list.layoutIfNeeded()
2478
+ XCTAssertNil(flow.tailClip)
2479
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2480
+ XCTAssertEqual(list.contentSize.height, 460, accuracy: 1)
2481
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 360, accuracy: 1)
2482
+ XCTAssertEqual(list.contentOffset.y, 0, accuracy: 1)
2483
+ }
2484
+
2485
+ func testStructuralTailCollapsePaintsEveryExpectedViewportRow() throws {
2486
+ try requireStructuralAnimation()
2487
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2488
+ let controller = UIViewController()
2489
+ window.rootViewController = controller
2490
+ let view = NativeListView(frame: window.bounds)
2491
+ controller.view.addSubview(view)
2492
+ window.isHidden = false
2493
+ defer {
2494
+ view.dispose()
2495
+ view.removeFromSuperview()
2496
+ window.isHidden = true
2497
+ window.rootViewController = nil
2498
+ }
2499
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2500
+ view.mountContainerSlot(UIView(), atIndex: 2)
2501
+ view.mountContainerSlot(UIView(), atIndex: 3)
2502
+ view.setContainerSlotHeightsJson("[0,0,60,3000]")
2503
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2504
+ list.contentInsetAdjustmentBehavior = .never
2505
+ list.contentInset = .zero
2506
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2507
+ view.layoutIfNeeded()
2508
+ list.layoutIfNeeded()
2509
+ drainMainQueue()
2510
+ list.contentOffset.y = 2400
2511
+ list.layoutIfNeeded()
2512
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2513
+ var checkedFrames = 0
2514
+ var failures: [String] = []
2515
+ let probe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in
2516
+ guard let clip = flow.tailClip else { return }
2517
+ list.layoutIfNeeded()
2518
+ let viewportTop = list.contentOffset.y
2519
+ let viewportBottom = viewportTop + list.bounds.height
2520
+ var expectedCount = 0
2521
+ var attributesCount = 0
2522
+ var attachedCount = 0
2523
+ var visibleCellsCount = 0
2524
+ var firstFailure: String?
2525
+ let attachedCells = list.subviews.compactMap { $0 as? NativeListRowHost }
2526
+ let visibleCells = list.visibleCells
2527
+ for index in 6..<50 {
2528
+ let rowTop = CGFloat(index * 60)
2529
+ let rowBottom = rowTop + 60
2530
+ let expectedTop = max(rowTop, viewportTop)
2531
+ let expectedBottom = min(rowBottom, viewportBottom, clip.endY)
2532
+ guard expectedBottom - expectedTop >= 8 else { continue }
2533
+ expectedCount += 1
2534
+ let path = IndexPath(item: index, section: 0)
2535
+ let attributes = flow.layoutAttributesForItem(at: path)
2536
+ if attributes != nil { attributesCount += 1 }
2537
+ let cell = attachedCells.first { list.indexPath(for: $0) == path }
2538
+ if cell != nil { attachedCount += 1 }
2539
+ let inVisibleCells = cell.map { visibleCells.contains($0) } ?? false
2540
+ if inVisibleCells { visibleCellsCount += 1 }
2541
+ let maskEnd = cell?.layer.mask?.frame.maxY ?? 60
2542
+ let neededMaskEnd = expectedBottom - rowTop
2543
+ if cell == nil || cell?.isHidden == true || cell?.alpha != 1
2544
+ || maskEnd + 1 < neededMaskEnd {
2545
+ if firstFailure == nil {
2546
+ let hidden = cell.map { String($0.isHidden) } ?? "nil"
2547
+ let frame = cell.map { String(describing: $0.frame) } ?? "nil"
2548
+ firstFailure = "row=\(index) offset=\(Int(viewportTop)) clip=\(Int(clip.endY)) "
2549
+ + "attached=\(cell != nil) visibleCells=\(inVisibleCells) hidden=\(hidden) "
2550
+ + "frame=\(frame) attributes=\(String(describing: attributes?.frame)) "
2551
+ + "maskEnd=\(Int(maskEnd)) alpha=\(cell?.alpha ?? -1)"
2552
+ }
2553
+ }
2554
+ }
2555
+ if expectedCount > 0 { checkedFrames += 1 }
2556
+ if let firstFailure, failures.count < 8 {
2557
+ failures.append("expected=\(expectedCount) attrs=\(attributesCount) "
2558
+ + "attached=\(attachedCount) visibleCells=\(visibleCellsCount) " + firstFailure)
2559
+ }
2560
+ }
2561
+ RunLoop.main.add(probe, forMode: .common)
2562
+ defer { probe.invalidate() }
2563
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2564
+ transitionID: "tail-viewport-paint", durationMs: 800))
2565
+ waitForStructuralFrames(0.82)
2566
+ XCTAssertGreaterThanOrEqual(checkedFrames, 5)
2567
+ XCTAssertTrue(failures.isEmpty, failures.joined(separator: "\n"))
2568
+ }
2569
+
2570
+ func testStructuralTailGeometryChangeWithSameIDCommitsFinalLayout() throws {
2571
+ try requireStructuralAnimation()
2572
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2573
+ let controller = UIViewController()
2574
+ window.rootViewController = controller
2575
+ let view = NativeListView(frame: window.bounds)
2576
+ controller.view.addSubview(view)
2577
+ window.isHidden = false
2578
+ defer {
2579
+ view.dispose()
2580
+ view.removeFromSuperview()
2581
+ window.isHidden = true
2582
+ window.rootViewController = nil
2583
+ }
2584
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2585
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2586
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2587
+ list.contentInsetAdjustmentBehavior = .never
2588
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2589
+ view.layoutIfNeeded()
2590
+ list.layoutIfNeeded()
2591
+ drainMainQueue()
2592
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2593
+ transitionID: "same-id-geometry", durationMs: 400))
2594
+ waitForStructuralFrames(0.08)
2595
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2596
+ transitionID: "same-id-geometry", durationMs: 400, firstRowHeight: 70))
2597
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2598
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2599
+ list.layoutIfNeeded()
2600
+ XCTAssertNil(flow.tailClip)
2601
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2602
+ XCTAssertEqual(list.contentSize.height, 430, accuracy: 1)
2603
+ waitForStructuralFrames(0.42)
2604
+ XCTAssertEqual(list.contentSize.height, 430, accuracy: 1)
2605
+ }
2606
+
2607
+ func testStructuralTailSameIDOrientationChangeStopsVerticalTimeline() throws {
2608
+ try requireStructuralAnimation()
2609
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2610
+ let controller = UIViewController()
2611
+ window.rootViewController = controller
2612
+ let view = NativeListView(frame: window.bounds)
2613
+ controller.view.addSubview(view)
2614
+ window.isHidden = false
2615
+ defer {
2616
+ view.dispose()
2617
+ view.removeFromSuperview()
2618
+ window.isHidden = true
2619
+ window.rootViewController = nil
2620
+ }
2621
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2622
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2623
+ view.layoutIfNeeded()
2624
+ list.layoutIfNeeded()
2625
+ drainMainQueue()
2626
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2627
+ transitionID: "same-id-orientation", durationMs: 400))
2628
+ waitForStructuralFrames(0.08)
2629
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2630
+ transitionID: "same-id-orientation", durationMs: 400, orientation: "horizontal"))
2631
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2632
+ XCTAssertNil(flow.tailClip)
2633
+ XCTAssertEqual(flow.scrollDirection, .horizontal)
2634
+ waitForStructuralFrames(0.42)
2635
+ XCTAssertEqual(flow.scrollDirection, .horizontal)
2636
+ XCTAssertNil(flow.tailClip)
2637
+ }
2638
+
2639
+ func testStructuralTailHostLimitFallsBackToAtomicSnapshot() throws {
2640
+ try requireStructuralAnimation()
2641
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2642
+ let controller = UIViewController()
2643
+ window.rootViewController = controller
2644
+ let view = NativeListView(frame: window.bounds)
2645
+ controller.view.addSubview(view)
2646
+ window.isHidden = false
2647
+ defer {
2648
+ view.dispose()
2649
+ view.removeFromSuperview()
2650
+ window.isHidden = true
2651
+ window.rootViewController = nil
2652
+ }
2653
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2654
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2655
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2656
+ list.contentInsetAdjustmentBehavior = .never
2657
+ // Six retained rows plus 129 retiring rows still exceed the 128-host limit
2658
+ // inside three viewports, without materializing hundreds of 1-point cells.
2659
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 135, generation: 1,
2660
+ uniformHeight: 10))
2661
+ view.layoutIfNeeded()
2662
+ list.layoutIfNeeded()
2663
+ drainMainQueue()
2664
+ var phases: [Int] = []
2665
+ let observer = NotificationCenter.default.addObserver(
2666
+ forName: Notification.Name("OneKeyNativeListScrollCommandAccepted"),
2667
+ object: list, queue: nil
2668
+ ) { notification in
2669
+ if let phase = notification.userInfo?["phase"] as? Int { phases.append(phase) }
2670
+ }
2671
+ defer { NotificationCenter.default.removeObserver(observer) }
2672
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2673
+ transitionID: "tail-host-limit", durationMs: 400, uniformHeight: 10))
2674
+ list.layoutIfNeeded()
2675
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2676
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2677
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2678
+ XCTAssertNil(flow.tailClip)
2679
+ XCTAssertTrue(phases.isEmpty)
2680
+ }
2681
+
2682
+ func testStructuralTailExpansionKeepsOffsetWithTallerInitialSidecar() throws {
2683
+ try requireStructuralAnimation()
2684
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2685
+ let controller = UIViewController()
2686
+ window.rootViewController = controller
2687
+ let view = NativeListView(frame: window.bounds)
2688
+ controller.view.addSubview(view)
2689
+ window.isHidden = false
2690
+ defer {
2691
+ view.dispose()
2692
+ view.removeFromSuperview()
2693
+ window.isHidden = true
2694
+ window.rootViewController = nil
2695
+ }
2696
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
2697
+ view.setContainerSlotHeightsJson("[0,0,60,2200]")
2698
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2699
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2700
+ list.contentInsetAdjustmentBehavior = .never
2701
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2702
+ view.layoutIfNeeded()
2703
+ list.layoutIfNeeded()
2704
+ drainMainQueue()
2705
+ XCTAssertEqual(list.contentSize.height, 2200, accuracy: 1)
2706
+ list.contentOffset.y = 1000
2707
+ list.layoutIfNeeded()
2708
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2709
+ transitionID: "tail-6-to-50", durationMs: 400))
2710
+ list.layoutIfNeeded()
2711
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2712
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2713
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2714
+ var checkedActiveTail = false
2715
+ func checkActiveTail() {
2716
+ guard let clip = flow.tailClip else { return }
2717
+ checkedActiveTail = true
2718
+ list.layoutIfNeeded()
2719
+ XCTAssertGreaterThanOrEqual(clip.endY, 360)
2720
+ XCTAssertLessThanOrEqual(clip.endY, 3000)
2721
+ let suffixCells = list.visibleCells.filter {
2722
+ (list.indexPath(for: $0)?.item ?? -1) >= 6
2723
+ }
2724
+ if clip.endY > list.contentOffset.y + 60 {
2725
+ XCTAssertFalse(suffixCells.isEmpty)
2726
+ }
2727
+ XCTAssertTrue(suffixCells.allSatisfy {
2728
+ !$0.isUserInteractionEnabled && $0.accessibilityElementsHidden
2729
+ })
2730
+ XCTAssertEqual(list.contentOffset.y, 1000, accuracy: 1)
2731
+ }
2732
+ // Inspect actual active frames instead of assuming a delayed callback lands
2733
+ // inside a 400 ms animation on a busy CI runner.
2734
+ checkActiveTail()
2735
+ let probe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in checkActiveTail() }
2736
+ RunLoop.main.add(probe, forMode: .common)
2737
+ defer { probe.invalidate() }
2738
+ let finished = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
2739
+ flow.tailClip == nil &&
2740
+ Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink == nil
2741
+ }, object: nil)
2742
+ wait(for: [finished], timeout: 5)
2743
+ probe.invalidate()
2744
+ XCTAssertTrue(checkedActiveTail)
2745
+ list.layoutIfNeeded()
2746
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2747
+ XCTAssertEqual(list.contentSize.height, 3060, accuracy: 1)
2748
+ XCTAssertEqual(list.contentOffset.y, 1000, accuracy: 1)
2749
+ XCTAssertNil(flow.tailClip)
2750
+ }
2751
+
2752
+ func testStructuralTailDifferentPrefixDuringExpansionCommitsAtomicSnapshot() throws {
2753
+ try requireStructuralAnimation()
2754
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2755
+ let controller = UIViewController()
2756
+ window.rootViewController = controller
2757
+ let view = NativeListView(frame: window.bounds)
2758
+ controller.view.addSubview(view)
2759
+ window.isHidden = false
2760
+ defer {
2761
+ view.dispose()
2762
+ view.removeFromSuperview()
2763
+ window.isHidden = true
2764
+ window.rootViewController = nil
2765
+ }
2766
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
2767
+ view.setContainerSlotHeightsJson("[0,0,60,1600]")
2768
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2769
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2770
+ list.contentInsetAdjustmentBehavior = .never
2771
+ list.contentInset = .zero
2772
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2773
+ view.layoutIfNeeded()
2774
+ list.layoutIfNeeded()
2775
+ drainMainQueue()
2776
+ XCTAssertEqual(list.adjustedContentInset.top, 0, accuracy: 0.01)
2777
+ XCTAssertEqual(list.adjustedContentInset.bottom, 0, accuracy: 0.01)
2778
+ list.contentOffset.y = 900
2779
+ list.layoutIfNeeded()
2780
+
2781
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2782
+ transitionID: "tail-first-six", durationMs: 1200))
2783
+ waitForStructuralFrames(0.12)
2784
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2785
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2786
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2787
+ XCTAssertGreaterThan(try XCTUnwrap(flow.tailClip).endY, 360)
2788
+
2789
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 10, generation: 3,
2790
+ transitionID: "tail-next-ten", durationMs: 1200))
2791
+ list.layoutIfNeeded()
2792
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<10).map { "row-\($0)" })
2793
+ XCTAssertNil(flow.tailClip)
2794
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2795
+ XCTAssertEqual(Mirror(reflecting: view).descendant("structuralSpacerHeight") as? CGFloat ?? -1,
2796
+ 0, accuracy: 1)
2797
+ XCTAssertEqual(list.contentSize.height, 1600, accuracy: 1)
2798
+ XCTAssertEqual(list.contentOffset.y, 900, accuracy: 1)
2799
+ waitForStructuralFrames(1.25)
2800
+ list.layoutIfNeeded()
2801
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<10).map { "row-\($0)" })
2802
+ XCTAssertEqual(list.contentSize.height, 1600, accuracy: 1)
2803
+ XCTAssertEqual(list.contentOffset.y, 900, accuracy: 1)
2804
+ }
2805
+
2806
+ func testStructuralTailInterruptedExpansionRestoresBoundaryCellInteraction() throws {
2807
+ try requireStructuralAnimation()
2808
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2809
+ let controller = UIViewController()
2810
+ window.rootViewController = controller
2811
+ let view = NativeListView(frame: window.bounds)
2812
+ controller.view.addSubview(view)
2813
+ window.isHidden = false
2814
+ defer {
2815
+ view.dispose()
2816
+ view.removeFromSuperview()
2817
+ window.isHidden = true
2818
+ window.rootViewController = nil
2819
+ }
2820
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2821
+ let footer = UIView()
2822
+ view.mountContainerSlot(footer, atIndex: 2)
2823
+ view.mountContainerSlot(UIView(), atIndex: 3)
2824
+ view.setContainerSlotHeightsJson("[0,0,60,2200]")
2825
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2826
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2827
+ list.contentInsetAdjustmentBehavior = .never
2828
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2829
+ view.layoutIfNeeded()
2830
+ list.layoutIfNeeded()
2831
+ drainMainQueue()
2832
+ list.contentOffset.y = 300
2833
+ list.layoutIfNeeded()
2834
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2835
+ transitionID: "interrupt-boundary", durationMs: 1200))
2836
+ let footerBottomBeforeResize = footer.convert(.zero, to: list).y + 60
2837
+ view.setContainerSlotHeightsJson("[0,0,80,2200]")
2838
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 80,
2839
+ footerBottomBeforeResize, accuracy: 1)
2840
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2841
+ let prefixBottom = try XCTUnwrap(flow.layoutAttributesForItem(
2842
+ at: IndexPath(item: 5, section: 0))).frame.maxY
2843
+ let footerHost = try XCTUnwrap(footer.superview)
2844
+ let hiddenTop = prefixBottom - footerHost.frame.minY
2845
+ XCTAssertGreaterThan(hiddenTop, 0)
2846
+ XCTAssertFalse(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop / 2), with: nil))
2847
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop + 1), with: nil))
2848
+ var boundaryCell: NativeListRowHost?
2849
+ let deadline = Date().addingTimeInterval(1)
2850
+ while boundaryCell == nil && Date() < deadline {
2851
+ if let clip = flow.tailClip {
2852
+ for case let cell as NativeListRowHost in list.visibleCells {
2853
+ guard let path = list.indexPath(for: cell), path.item >= 6,
2854
+ let mask = cell.layer.mask else { continue }
2855
+ let visibleHeight = clip.endY - cell.frame.minY
2856
+ if clip.endY > cell.frame.minY + 2 &&
2857
+ clip.endY < cell.frame.maxY - 2 &&
2858
+ mask.frame.height > 2 &&
2859
+ mask.frame.height < cell.bounds.height - 2 &&
2860
+ abs(mask.frame.height - visibleHeight) <= 1 {
2861
+ boundaryCell = cell
2862
+ break
2863
+ }
2864
+ }
2865
+ }
2866
+ if boundaryCell == nil { RunLoop.main.run(until: Date().addingTimeInterval(0.01)) }
2867
+ }
2868
+ let boundary = try XCTUnwrap(boundaryCell)
2869
+ let displayLink = try XCTUnwrap(
2870
+ Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2871
+ displayLink.isPaused = true
2872
+ defer { displayLink.isPaused = false }
2873
+ let mask = try XCTUnwrap(boundary.layer.mask)
2874
+ XCTAssertGreaterThan(mask.frame.height, 2)
2875
+ XCTAssertLessThan(mask.frame.height, boundary.bounds.height - 2)
2876
+ XCTAssertFalse(boundary.isUserInteractionEnabled)
2877
+ XCTAssertTrue(boundary.accessibilityElementsHidden)
2878
+ let offsetBeforeInterruption = list.contentOffset.y
2879
+ view.scrollViewWillBeginDragging(list)
2880
+ list.layoutIfNeeded()
2881
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2882
+ XCTAssertNil(boundary.layer.mask)
2883
+ XCTAssertFalse(boundary.isHidden)
2884
+ XCTAssertTrue(boundary.isUserInteractionEnabled)
2885
+ XCTAssertFalse(boundary.accessibilityElementsHidden)
2886
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: 1), with: nil))
2887
+ XCTAssertEqual(list.contentOffset.y, offsetBeforeInterruption, accuracy: 1)
2888
+ XCTAssertEqual(list.contentOffset.y, 300, accuracy: 1)
2889
+ }
2890
+
2891
+ func testStructuralTailExplicitScrollTakesOwnershipFromExpansion() throws {
2892
+ try requireStructuralAnimation()
2893
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2894
+ let controller = UIViewController()
2895
+ window.rootViewController = controller
2896
+ let view = NativeListView(frame: window.bounds)
2897
+ controller.view.addSubview(view)
2898
+ window.isHidden = false
2899
+ defer {
2900
+ view.dispose()
2901
+ view.removeFromSuperview()
2902
+ window.isHidden = true
2903
+ window.rootViewController = nil
2904
+ }
2905
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2906
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2907
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2908
+ list.contentInsetAdjustmentBehavior = .never
2909
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2910
+ view.layoutIfNeeded()
2911
+ list.layoutIfNeeded()
2912
+ drainMainQueue()
2913
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2914
+ transitionID: "explicit-scroll-over-expansion", durationMs: 400))
2915
+ waitForStructuralFrames(0.08)
2916
+ view.scrollToIndex(40, animated: false, alignment: "start")
2917
+ drainMainQueue()
2918
+ list.layoutIfNeeded()
2919
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2920
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2921
+ XCTAssertEqual(list.contentOffset.y, 2400, accuracy: 1)
2922
+ waitForStructuralFrames(0.4)
2923
+ XCTAssertEqual(list.contentOffset.y, 2400, accuracy: 1)
2924
+ XCTAssertTrue(list.visibleCells.allSatisfy {
2925
+ $0.isUserInteractionEnabled && !$0.accessibilityElementsHidden && $0.layer.mask == nil
2926
+ })
2927
+ }
2928
+
2929
+ func testStructuralTransitionSurvivesVisibleDataRowPatch() throws {
2930
+ try requireStructuralAnimation()
2931
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2932
+ let controller = UIViewController()
2933
+ window.rootViewController = controller
2934
+ let view = NativeListView(frame: window.bounds)
2935
+ controller.view.addSubview(view)
2936
+ window.isHidden = false
2937
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
2938
+ let footer = UIView()
2939
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2940
+ view.mountContainerSlot(footer, atIndex: 2)
2941
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2942
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1, dataRows: true))
2943
+ view.layoutIfNeeded()
2944
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2945
+ list.layoutIfNeeded()
2946
+ drainMainQueue()
2947
+ list.contentOffset.y = 1100
2948
+ list.layoutIfNeeded()
2949
+
2950
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
2951
+ transitionID: "collapse-with-patch", durationMs: 800, dataRows: true))
2952
+ waitForStructuralFrames(0.3)
2953
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2954
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2955
+ let heightBeforePatch = try XCTUnwrap(flow.tailClip).endY
2956
+ XCTAssertGreaterThan(heightBeforePatch, 1500)
2957
+ let retiring = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 25, section: 0)) as? NativeListRowHost)
2958
+ XCTAssertEqual(retiring.bounds.height, 60, accuracy: 1)
2959
+ func storedContent(_ key: String) throws -> String {
2960
+ let items = try XCTUnwrap(Mirror(reflecting: view).descendant("itemsByKey")
2961
+ as? [String: NativeListItem])
2962
+ return try XCTUnwrap(items[key]).content
2963
+ }
2964
+ let oldAcceptedContent = try storedContent("row-20")
2965
+ let retiredContent = try storedContent("row-25")
2966
+ let patch: [[String: Any]] = [[
2967
+ "key": "row-20", "type": "dataRow", "changes": [
2968
+ "revision": 2,
2969
+ "columns": [["key": "asset", "text": "Asset"],
2970
+ ["key": "price", "text": "$123.45"]],
2971
+ ],
2972
+ ]]
2973
+ let invalidRetiredPatch: [String: Any] = ["key": "row-25", "type": "dataRow",
2974
+ "changes": ["revision": 2]]
2975
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(
2976
+ withJSONObject: patch + [invalidRetiredPatch]), as: UTF8.self))
2977
+ XCTAssertEqual(try storedContent("row-20"), oldAcceptedContent)
2978
+ XCTAssertEqual(try storedContent("row-25"), retiredContent)
2979
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patch),
2980
+ as: UTF8.self))
2981
+ XCTAssertNotEqual(try storedContent("row-20"), oldAcceptedContent)
2982
+ XCTAssertEqual(try storedContent("row-25"), retiredContent)
2983
+ list.layoutIfNeeded()
2984
+ let patched = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0)))
2985
+ XCTAssertTrue(labels(in: patched).contains { $0.text == "$123.45" })
2986
+ waitForStructuralFrames(0.05)
2987
+ list.layoutIfNeeded()
2988
+ XCTAssertLessThan(try XCTUnwrap(flow.tailClip).endY, heightBeforePatch)
2989
+ waitForStructuralFrames(0.55)
2990
+ list.layoutIfNeeded()
2991
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<25).map { "row-\($0)" })
2992
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
2993
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1500, accuracy: 1)
2994
+ let finalPatched = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0)))
2995
+ XCTAssertTrue(labels(in: finalPatched).contains { $0.text == "$123.45" })
2996
+ }
2997
+
2998
+ func testStructuralTransitionDoesNotOverrideUserDrag() throws {
2999
+ try requireStructuralAnimation()
3000
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
3001
+ let controller = UIViewController()
3002
+ window.rootViewController = controller
3003
+ let view = NativeListView(frame: window.bounds)
3004
+ controller.view.addSubview(view)
3005
+ window.isHidden = false
3006
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
3007
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
3008
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
3009
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1))
3010
+ view.layoutIfNeeded()
3011
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
3012
+ list.layoutIfNeeded()
3013
+ drainMainQueue()
3014
+ list.contentOffset.y = 1100
3015
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
3016
+ transitionID: "collapse-drag", durationMs: 400))
3017
+ waitForStructuralFrames(0.08)
3018
+ view.scrollViewWillBeginDragging(list)
3019
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
3020
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
3021
+ list.contentOffset.y = 600
3022
+ list.layoutIfNeeded()
3023
+ waitForStructuralFrames(0.15)
3024
+ XCTAssertEqual(list.contentOffset.y, 600, accuracy: 1)
3025
+ waitForStructuralFrames(0.35)
3026
+ list.layoutIfNeeded()
3027
+ XCTAssertEqual(list.contentOffset.y, 600, accuracy: 1)
3028
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
3029
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<25).map { "row-\($0)" })
3030
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
3031
+ XCTAssertTrue(list.visibleCells.allSatisfy { abs($0.alpha - 1) < 0.01 })
3032
+ }
3033
+
3034
+ func testStructuralTransitionDetachAndDisposeReleaseView() throws {
3035
+ try requireStructuralAnimation()
3036
+ for dispose in [false, true] {
3037
+ var callbacks = 0
3038
+ let reference = try detachStructuralTransition(dispose: dispose) { callbacks += 1 }
3039
+ if dispose {
3040
+ drainMainQueue()
3041
+ XCTAssertNil(reference.view)
3042
+ let countAtDispose = callbacks
3043
+ waitForStructuralFrames(0.5)
3044
+ XCTAssertEqual(callbacks, countAtDispose)
3045
+ } else {
3046
+ waitForStructuralFrames(0.5)
3047
+ XCTAssertNil(reference.view)
3048
+ }
3049
+ }
3050
+ }
3051
+
3052
+ private final class WeakListReference {
3053
+ weak var view: NativeListView?
3054
+ }
3055
+
3056
+ private func detachStructuralTransition(
3057
+ dispose: Bool, onCallback: @escaping () -> Void
3058
+ ) throws -> WeakListReference {
3059
+ try autoreleasepool {
3060
+ let reference = WeakListReference()
3061
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
3062
+ let controller = UIViewController()
3063
+ window.rootViewController = controller
3064
+ let view = NativeListView(frame: window.bounds)
3065
+ controller.view.addSubview(view)
3066
+ window.isHidden = false
3067
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
3068
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
3069
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1))
3070
+ view.layoutIfNeeded()
3071
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
3072
+ view.onVisibleRangeChanged = { _ in onCallback() }
3073
+ view.onEndReached = { _ in onCallback() }
3074
+ list.layoutIfNeeded()
3075
+ drainMainQueue()
3076
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
3077
+ transitionID: dispose ? "dispose-mid-transition" : "detach-mid-transition",
3078
+ durationMs: 400))
3079
+ // Interrupt an active transition without racing a wall-clock delay on a busy runner.
3080
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
3081
+ reference.view = view
3082
+ if dispose {
3083
+ view.dispose()
3084
+ XCTAssertNil(list.delegate)
3085
+ XCTAssertNil(list.dataSource)
3086
+ }
3087
+ view.removeFromSuperview()
3088
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
3089
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
3090
+ window.isHidden = true
3091
+ window.rootViewController = nil
3092
+ return reference
3093
+ }
3094
+ }
3095
+
3096
+ private func dispatchAccessoryTouchUpInside(
3097
+ _ control: UIButton, on stack: NativeListAccessoryStack,
3098
+ file: StaticString = #filePath, line: UInt = #line
3099
+ ) throws {
3100
+ guard control.allTargets.contains(stack) else {
3101
+ XCTFail("Accessory control is not attached to its stack", file: file, line: line)
3102
+ return
3103
+ }
3104
+ let actions = try XCTUnwrap(
3105
+ control.actions(forTarget: stack, forControlEvent: .touchUpInside),
3106
+ file: file, line: line)
3107
+ guard !actions.isEmpty else {
3108
+ XCTFail("Accessory control has no touch-up action", file: file, line: line)
3109
+ return
3110
+ }
3111
+ // This pod XCTest has no UIApplication to dispatch UIControl.sendActions.
3112
+ guard control.isEnabled else { return }
3113
+ for action in actions {
3114
+ let selector = NSSelectorFromString(action)
3115
+ guard stack.responds(to: selector) else {
3116
+ XCTFail("Accessory action selector is missing: \(action)", file: file, line: line)
3117
+ continue
3118
+ }
3119
+ if action.hasSuffix(":") { _ = stack.perform(selector, with: control) }
3120
+ else { _ = stack.perform(selector) }
3121
+ }
3122
+ }
3123
+
3124
+ private func requireStructuralAnimation() throws {
3125
+ if UIAccessibility.isReduceMotionEnabled {
3126
+ throw XCTSkip("Structural animation is disabled by Reduce Motion")
3127
+ }
3128
+ }
3129
+
3130
+ private func waitForStructuralFrames(_ seconds: TimeInterval) {
3131
+ let completed = expectation(description: "Native structural display link ran for \(seconds)s")
3132
+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { completed.fulfill() }
3133
+ wait(for: [completed], timeout: seconds + 1)
3134
+ }
3135
+
3136
+ private func labels(in view: UIView) -> [UILabel] {
3137
+ let current = (view as? UILabel).map { [$0] } ?? []
3138
+ return current + view.subviews.flatMap(labels(in:))
3139
+ }
3140
+
3141
+ private func structuralRowsSnapshot(
3142
+ count: Int, generation: Int? = nil, transitionID: String? = nil,
3143
+ durationMs: Int = 80, dataRows: Bool = false, firstRowHeight: Int? = nil,
3144
+ uniformHeight: Int = 60, orientation: String = "vertical", layoutKind: String = "linear",
3145
+ disclosureExpanded: Bool? = nil, disclosureInset: Int = 20
3146
+ ) throws -> String {
3147
+ let rows: [[String: Any]] = (0..<count).map {
3148
+ let height = $0 == 0 ? firstRowHeight ?? uniformHeight : uniformHeight
3149
+ if dataRows {
3150
+ return ["key": "row-\($0)", "type": "dataRow", "height": height,
3151
+ "columns": [["key": "asset", "text": "Asset"],
3152
+ ["key": "price", "text": "$1.00"]]]
3153
+ }
3154
+ return ["key": "row-\($0)", "type": "action", "title": "Row", "height": height]
3155
+ }
3156
+ var layout: [String: Any] = ["kind": layoutKind, "orientation": orientation]
3157
+ if layoutKind == "grid" { layout["gridColumns"] = 2 }
3158
+ var value: [String: Any] = [
3159
+ "schemaVersion": 1, "generation": generation ?? count + 1,
3160
+ "layout": layout, "rows": rows,
3161
+ ]
3162
+ if let transitionID {
3163
+ value["structuralTransition"] = [
3164
+ "id": transitionID, "durationMs": durationMs, "anchorKey": "row-24",
3165
+ ]
3166
+ }
3167
+ if let disclosureExpanded {
3168
+ value["disclosure"] = ["expanded": disclosureExpanded,
3169
+ "expandedTrailingInset": disclosureInset]
3170
+ }
3171
+ return String(decoding: try JSONSerialization.data(withJSONObject: value), as: UTF8.self)
3172
+ }
3173
+
3174
+ private func assertHomeSidecarGeometry(sidecarBeforeFirstLayout: Bool) throws {
3175
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 900))
3176
+ let controller = UIViewController()
3177
+ window.rootViewController = controller
3178
+ let view = NativeListView(frame: window.bounds)
3179
+ controller.view.addSubview(view)
3180
+ window.isHidden = false
3181
+ defer {
3182
+ view.dispose()
3183
+ view.removeFromSuperview()
3184
+ window.isHidden = true
3185
+ window.rootViewController = nil
3186
+ }
3187
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
3188
+ view.setContainerSlotHeightsJson("[0,0,0,1200]")
3189
+ let sidecar = "{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}"
3190
+ if sidecarBeforeFirstLayout { view.setSidecarLayoutJson(sidecar) }
3191
+ view.applySnapshotJson(try homeSidecarSnapshot())
3192
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
3193
+ list.contentInsetAdjustmentBehavior = .never
3194
+ func layout() {
3195
+ window.layoutIfNeeded()
3196
+ view.layoutIfNeeded()
3197
+ list.layoutIfNeeded()
3198
+ }
3199
+ func assertRows(x: CGFloat, width: CGFloat) {
3200
+ let cells = list.visibleCells.compactMap { $0 as? NativeListDataRowCell }
3201
+ XCTAssertFalse(cells.isEmpty)
3202
+ for cell in cells {
3203
+ let frame = cell.convert(cell.bounds, to: list)
3204
+ XCTAssertEqual(frame.minX, x, accuracy: 1)
3205
+ XCTAssertEqual(frame.width, width, accuracy: 1)
3206
+ if let path = list.indexPath(for: cell),
3207
+ let attributes = list.layoutAttributesForItem(at: path)
3208
+ {
3209
+ XCTAssertEqual(attributes.frame.minX, x, accuracy: 1)
3210
+ XCTAssertEqual(attributes.frame.width, width, accuracy: 1)
3211
+ }
3212
+ let root = cell.root.convert(cell.root.bounds, to: list)
3213
+ XCTAssertGreaterThanOrEqual(root.minX, frame.minX - 1)
3214
+ XCTAssertLessThanOrEqual(root.maxX, frame.maxX + 1)
3215
+ }
3216
+ }
3217
+ layout()
3218
+ if !sidecarBeforeFirstLayout {
3219
+ assertRows(x: 8, width: 1360)
3220
+ view.setSidecarLayoutJson(sidecar)
3221
+ layout()
3222
+ }
3223
+ assertRows(x: 126, width: 700)
3224
+ list.contentOffset.y = 18 * 60
3225
+ layout()
3226
+ assertRows(x: 126, width: 700)
3227
+ let patch: [[String: Any]] = [[
3228
+ "key": "row-20", "type": "dataRow",
3229
+ "changes": ["columns": homeSidecarColumns(20, updated: true),
3230
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]]],
3231
+ ]]
3232
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patch),
3233
+ as: UTF8.self))
3234
+ layout()
3235
+ assertRows(x: 126, width: 700)
3236
+ window.frame.size.width = 1024
3237
+ controller.view.frame = window.bounds
3238
+ view.frame = window.bounds
3239
+ layout()
3240
+ assertRows(x: 8, width: 584)
3241
+ window.frame.size.width = 1376
3242
+ controller.view.frame = window.bounds
3243
+ view.frame = window.bounds
3244
+ layout()
3245
+ assertRows(x: 126, width: 700)
3246
+ view.setSidecarLayoutJson("")
3247
+ layout()
3248
+ assertRows(x: 8, width: 1360)
3249
+ }
3250
+
3251
+ private func homeSidecarSnapshot() throws -> String {
3252
+ let rows: [[String: Any]] = (0..<30).map { index in
3253
+ ["key": "row-\(index)", "type": "dataRow", "height": 60,
3254
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
3255
+ "columns": homeSidecarColumns(index, updated: false),
3256
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]],
3257
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
3258
+ "image": ["width": 32, "height": 32]]]
3259
+ }
3260
+ let snapshot: [String: Any] = [
3261
+ "schemaVersion": 1, "generation": 1,
3262
+ "layout": ["kind": "linear", "contentPaddingHorizontal": 8], "rows": rows,
3263
+ ]
3264
+ return String(decoding: try JSONSerialization.data(withJSONObject: snapshot), as: UTF8.self)
3265
+ }
3266
+
3267
+ private func homeSidecarColumns(_ index: Int, updated: Bool) -> [[String: Any]] {
3268
+ [
3269
+ ["key": "asset", "text": "Asset \(index)", "secondaryText": "Public fixture", "weight": 1],
3270
+ ["key": "balance", "text": updated ? "0.2966" : "0.000175",
3271
+ "secondaryText": "$0.13", "alignment": "end", "weight": 1],
3272
+ ["key": "price", "text": updated ? "$739.22" : "$0.9989",
3273
+ "secondaryText": "-0.04%", "alignment": "end", "weight": 1],
3274
+ ]
3275
+ }
3276
+
366
3277
  private func makeScrollingList() throws -> NativeListView {
367
3278
  let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
368
3279
  for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
369
- view.setContainerSlotHeightsJson("[44,44,44]")
3280
+ view.setContainerSlotHeightsJson("[44,44,44,0]")
370
3281
  view.applySnapshotJson(try scrollingSnapshot(count: 40))
371
3282
  view.layoutIfNeeded()
372
3283
  let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)