@onekeyfe/react-native-native-list 6.7.0-2 → 6.7.0-21

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