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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/android/src/main/java/com/onekey/nativelist/HybridNativeList.kt +14 -1
  2. package/android/src/main/java/com/onekey/nativelist/NativeListAccessoryStack.kt +240 -11
  3. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +7 -4
  4. package/android/src/main/java/com/onekey/nativelist/NativeListActivityRenderer.kt +6 -3
  5. package/android/src/main/java/com/onekey/nativelist/NativeListButtonGroupRenderer.kt +102 -0
  6. package/android/src/main/java/com/onekey/nativelist/NativeListContainerSlotAdapter.kt +12 -0
  7. package/android/src/main/java/com/onekey/nativelist/NativeListDataRowRenderer.kt +87 -7
  8. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +187 -1
  9. package/android/src/main/java/com/onekey/nativelist/NativeListLeadingVisual.kt +59 -14
  10. package/android/src/main/java/com/onekey/nativelist/NativeListMessageRenderer.kt +25 -0
  11. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +47 -2
  12. package/android/src/main/java/com/onekey/nativelist/NativeListPrimitives.kt +22 -0
  13. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRegistry.kt +2 -0
  14. package/android/src/main/java/com/onekey/nativelist/NativeListRendererRowView.kt +2 -0
  15. package/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +3 -2
  16. package/android/src/main/java/com/onekey/nativelist/NativeListSectionHeaderRenderer.kt +69 -0
  17. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +55 -1
  18. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +1877 -41
  19. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListLeadingVisualClipPolicyTest.kt +44 -0
  20. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListPressPolicyTest.kt +1 -0
  21. package/docs/ROW_TEMPLATES.md +60 -9
  22. package/docs/SPEC.md +434 -5
  23. package/docs/STYLE_SPEC.md +6 -0
  24. package/ios/HybridNativeList.swift +17 -2
  25. package/ios/NativeListAccessoryStack.swift +227 -39
  26. package/ios/NativeListActivityDetailsView.swift +18 -8
  27. package/ios/NativeListActivityRenderer.swift +8 -2
  28. package/ios/NativeListButtonGroupRenderer.swift +89 -0
  29. package/ios/NativeListDataRowRenderer.swift +155 -27
  30. package/ios/NativeListDesignAssets.swift +3 -0
  31. package/ios/NativeListIdentityRenderer.swift +166 -30
  32. package/ios/NativeListLeadingVisual.swift +49 -14
  33. package/ios/NativeListMessageRenderer.swift +34 -1
  34. package/ios/NativeListModels.swift +42 -2
  35. package/ios/NativeListRendererRegistry.swift +1 -0
  36. package/ios/NativeListResolvedText.swift +2 -1
  37. package/ios/NativeListRowHost.swift +14 -0
  38. package/ios/NativeListSectionHeaderRenderer.swift +88 -0
  39. package/ios/RNCNativeListView.swift +1002 -53
  40. package/ios/Resources/NativeListIcons.xcassets/onekey_crypto_coin_outline.imageset/Contents.json +15 -0
  41. package/ios/Resources/NativeListIcons.xcassets/onekey_crypto_coin_outline.imageset/icon.svg +4 -0
  42. package/ios/Resources/NativeListIcons.xcassets/onekey_gas_solid.imageset/Contents.json +15 -0
  43. package/ios/Resources/NativeListIcons.xcassets/onekey_gas_solid.imageset/icon.svg +3 -0
  44. package/ios/Resources/NativeListIcons.xcassets/onekey_refresh_ccw_outline.imageset/Contents.json +15 -0
  45. package/ios/Resources/NativeListIcons.xcassets/onekey_refresh_ccw_outline.imageset/icon.svg +3 -0
  46. package/ios/tests/NativeListActivityPresentationTests.swift +56 -0
  47. package/ios/tests/NativeListLifecycleTests.swift +2494 -3
  48. package/lib/module/NativeList.js +171 -28
  49. package/lib/module/NativeList.web.js +54 -4
  50. package/lib/module/models.js +1 -0
  51. package/lib/module/selection.js +1 -1
  52. package/lib/module/validation.js +331 -8
  53. package/lib/module/web/NativeListWebEngine.js +503 -18
  54. package/lib/module/web/templates/ActivityRowRenderer.js +8 -7
  55. package/lib/module/web/templates/ButtonGroupRowRenderer.js +47 -0
  56. package/lib/module/web/templates/DataRowRenderer.js +40 -5
  57. package/lib/module/web/templates/IdentityRowRenderer.js +90 -4
  58. package/lib/module/web/templates/MessageRowRenderer.js +18 -2
  59. package/lib/module/web/templates/RowContainerStyle.js +1 -0
  60. package/lib/module/web/templates/RowRendererRegistry.js +3 -0
  61. package/lib/module/web/templates/SectionHeaderRowRenderer.js +36 -2
  62. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  63. package/lib/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  64. package/lib/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  65. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  66. package/lib/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  67. package/lib/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  68. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  69. package/lib/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  70. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  71. package/lib/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  72. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  73. package/lib/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  74. package/lib/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  75. package/lib/typescript/src/NativeList.d.ts +1 -1
  76. package/lib/typescript/src/NativeList.nitro.d.ts +2 -0
  77. package/lib/typescript/src/NativeList.types.d.ts +18 -0
  78. package/lib/typescript/src/index.d.ts +1 -1
  79. package/lib/typescript/src/models.d.ts +105 -9
  80. package/lib/typescript/src/validation.d.ts +10 -0
  81. package/lib/typescript/src/web/NativeListWebEngine.d.ts +31 -0
  82. package/lib/typescript/src/web/templates/ButtonGroupRowRenderer.d.ts +14 -0
  83. package/lib/typescript/src/web/templates/IdentityRowRenderer.d.ts +1 -1
  84. package/lib/typescript/src/web/templates/MessageRowRenderer.d.ts +9 -3
  85. package/nitrogen/generated/android/c++/JHybridNativeListSpec.cpp +26 -0
  86. package/nitrogen/generated/android/c++/JHybridNativeListSpec.hpp +4 -0
  87. package/nitrogen/generated/android/c++/views/JHybridNativeListStateUpdater.cpp +10 -0
  88. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nativelist/HybridNativeListSpec.kt +20 -0
  89. package/nitrogen/generated/ios/c++/HybridNativeListSpecSwift.hpp +14 -0
  90. package/nitrogen/generated/ios/c++/views/HybridNativeListComponent.mm +12 -0
  91. package/nitrogen/generated/ios/swift/HybridNativeListSpec.swift +2 -0
  92. package/nitrogen/generated/ios/swift/HybridNativeListSpec_cxx.swift +43 -0
  93. package/nitrogen/generated/shared/c++/HybridNativeListSpec.cpp +4 -0
  94. package/nitrogen/generated/shared/c++/HybridNativeListSpec.hpp +4 -0
  95. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.cpp +4 -0
  96. package/nitrogen/generated/shared/c++/views/HybridNativeListComponent.hpp +6 -0
  97. package/nitrogen/generated/shared/json/NativeListConfig.json +2 -0
  98. package/package.json +3 -3
  99. package/react-native-native-list.podspec +1 -0
  100. package/src/NativeList.nitro.ts +2 -0
  101. package/src/NativeList.tsx +307 -44
  102. package/src/NativeList.types.ts +22 -0
  103. package/src/NativeList.web.tsx +75 -8
  104. package/src/index.ts +1 -0
  105. package/src/models.ts +117 -3
  106. package/src/selection.ts +1 -0
  107. package/src/validation.ts +742 -6
  108. package/src/web/NativeListWebEngine.ts +798 -19
  109. package/src/web/templates/ActivityRowRenderer.ts +14 -6
  110. package/src/web/templates/ButtonGroupRowRenderer.ts +58 -0
  111. package/src/web/templates/DataRowRenderer.ts +93 -20
  112. package/src/web/templates/IdentityRowRenderer.ts +150 -5
  113. package/src/web/templates/MessageRowRenderer.ts +23 -7
  114. package/src/web/templates/RowContainerStyle.ts +2 -0
  115. package/src/web/templates/RowRendererRegistry.ts +11 -1
  116. package/src/web/templates/SectionHeaderRowRenderer.ts +47 -4
@@ -15,7 +15,8 @@ final class NativeListLifecycleTests: XCTestCase {
15
15
  let originalStyle = list.topEdgeEffect.style
16
16
  let originalInset = list.contentInset.top
17
17
  let overlay = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 64))
18
- view.mountContainerSlot(overlay, atIndex: 3)
18
+ for index in 0..<6 { view.mountContainerSlot(UIView(), atIndex: index) }
19
+ view.mountContainerSlot(overlay, atIndex: 6)
19
20
  view.setTopScrollEdge(effect: .hard, overlayHeight: 64)
20
21
  XCTAssertEqual(list.topEdgeEffect.style, .hard)
21
22
  XCTAssertEqual(list.contentInset.top, originalInset + 64, accuracy: 0.01)
@@ -153,6 +154,723 @@ final class NativeListLifecycleTests: XCTestCase {
153
154
  XCTAssertNotEqual(cell.bindingEpoch, changedEpoch)
154
155
  }
155
156
 
157
+ func testRiskIdentityTitleIconAndButtonResetOnProductionCellBind() throws {
158
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 320, height: 56))
159
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 200))
160
+ window.addSubview(cell)
161
+ let titleIcon = try XCTUnwrap(
162
+ Mirror(reflecting: cell).children.first { $0.label == "titleIconView" }?.value as? UIImageView)
163
+ let titleStack = try XCTUnwrap(
164
+ Mirror(reflecting: cell).children.first { $0.label == "titleRowStack" }?.value as? UIStackView)
165
+ let titleLabel = try XCTUnwrap(
166
+ Mirror(reflecting: cell).children.first { $0.label == "titleLabel" }?.value as? UILabel)
167
+ let trailing = try XCTUnwrap(
168
+ Mirror(reflecting: cell).children.first { $0.label == "trailingStack" }?.value
169
+ as? NativeListAccessoryStack)
170
+ func bind(_ data: [String: Any]) throws {
171
+ let item = try NativeListItem(data: data)
172
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
173
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
174
+ cell.layoutIfNeeded()
175
+ }
176
+ let base: [String: Any] = ["key": "risk", "type": "identity", "title": "Risk",
177
+ "height": 56, "leading": ["kind": "token",
178
+ "fallbackIcon": ["name": "CryptoCoinOutline"]]]
179
+ try bind(base)
180
+ XCTAssertTrue(titleIcon.isHidden)
181
+ XCTAssertLessThanOrEqual(titleIcon.bounds.width, 0.5)
182
+ try bind(base.merging(["titleIcon": ["name": "GasSolid"],
183
+ "trailing": [["kind": "button", "label": "Show", "actionKey": "show",
184
+ "backgroundColor": "#DDDDDD", "pressedBackgroundColor": "#AAAAAA"]]]) { _, newer in newer })
185
+ XCTAssertFalse(titleIcon.isHidden)
186
+ XCTAssertNotNil(titleIcon.image)
187
+ XCTAssertEqual(titleIcon.bounds.width, 20, accuracy: 0.5)
188
+ XCTAssertEqual(titleStack.customSpacing(after: titleLabel), 4, accuracy: 0.1)
189
+ let button = try XCTUnwrap(trailing.arrangedSubviews.compactMap { $0 as? NativeListAccessoryButton }
190
+ .first { !$0.isHidden })
191
+ XCTAssertEqual(button.intrinsicContentSize.height, 30, accuracy: 0.5)
192
+ let normal = button.backgroundColor
193
+ button.isHighlighted = true
194
+ XCTAssertNotEqual(button.backgroundColor, normal)
195
+ button.isHighlighted = false
196
+ XCTAssertEqual(button.backgroundColor, normal)
197
+ try bind(base)
198
+ XCTAssertTrue(titleIcon.isHidden)
199
+ XCTAssertLessThanOrEqual(titleIcon.bounds.width, 0.5)
200
+ XCTAssertTrue(trailing.arrangedSubviews.compactMap { $0 as? NativeListAccessoryButton }
201
+ .allSatisfy { $0.isHidden })
202
+ }
203
+
204
+ func testIdentityTitleSuffixesUsePlainLabelsAndClearOnRebind() throws {
205
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 320, height: 60))
206
+ let titleStack = try XCTUnwrap(
207
+ Mirror(reflecting: cell).children.first { $0.label == "titleRowStack" }?.value as? UIStackView)
208
+ func bind(_ suffixes: [[String: Any]]?) throws {
209
+ var data: [String: Any] = [
210
+ "key": "recent", "type": "identity", "title": "Alice",
211
+ "leading": ["kind": "account", "fallbackText": "A"],
212
+ ]
213
+ if let suffixes { data["titleSuffixes"] = suffixes }
214
+ let item = try NativeListItem(data: data)
215
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
216
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
217
+ cell.layoutIfNeeded()
218
+ }
219
+ try bind([
220
+ ["text": "EVM", "tone": "secondary", "maxWidth": 128],
221
+ ["text": "2 days ago", "tone": "disabled"],
222
+ ])
223
+ let suffixes = titleStack.arrangedSubviews.compactMap { $0 as? UILabel }
224
+ .filter { ["EVM", "2 days ago"].contains($0.text ?? "") }
225
+ XCTAssertEqual(suffixes.map(\.text), ["EVM", "2 days ago"])
226
+ XCTAssertTrue(suffixes.allSatisfy { $0.font.pointSize == 12 && $0.numberOfLines == 1 })
227
+ XCTAssertFalse(suffixes.contains { $0 is NativeListInsetLabel })
228
+ try bind(nil)
229
+ XCTAssertFalse(titleStack.arrangedSubviews.compactMap { $0 as? UILabel }
230
+ .contains { ["EVM", "2 days ago"].contains($0.text ?? "") })
231
+ }
232
+
233
+ func testDataRowTitleIconsClearWhenCellIsRebound() throws {
234
+ let cell = NativeListDataRowCell(frame: CGRect(x: 0, y: 0, width: 380, height: 60))
235
+ func bind(_ column: [String: Any]) throws {
236
+ let item = try NativeListItem(data: [
237
+ "key": "asset", "type": "dataRow", "columns": [column],
238
+ ])
239
+ cell.bind(item: item, theme: nil, layout: "table", selected: false,
240
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
241
+ cell.layoutIfNeeded()
242
+ }
243
+ func titleIcons(in view: UIView) -> [UIImageView] {
244
+ let current = (view as? UIImageView).map { [$0] } ?? []
245
+ return current + view.subviews.flatMap(titleIcons)
246
+ }
247
+ try bind([
248
+ "key": "asset", "text": "ETH",
249
+ "titleIcon": ["name": "GasSolid", "accessibilityLabel": "Gas help"],
250
+ "secondaryTitleIcon": ["name": "InfoCircleOutline", "accessibilityLabel": "Info help"],
251
+ ])
252
+ let visible = titleIcons(in: cell).filter { !$0.isHidden && $0.accessibilityLabel != nil }
253
+ XCTAssertEqual(visible.compactMap(\.accessibilityLabel), ["Gas help", "Info help"])
254
+ XCTAssertTrue(visible.allSatisfy { $0.image != nil })
255
+
256
+ try bind(["key": "asset", "text": "USDC"])
257
+ XCTAssertTrue(titleIcons(in: cell).allSatisfy {
258
+ $0.accessibilityLabel != "Gas help" && $0.accessibilityLabel != "Info help"
259
+ })
260
+ }
261
+
262
+ func testDataRowLinearRebindKeepsSizeConstraintsAndClearsOldContent() throws {
263
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 700, height: 100))
264
+ let cell = NativeListDataRowCell(frame: CGRect(x: 0, y: 0, width: 700, height: 60))
265
+ window.addSubview(cell)
266
+ window.isHidden = false
267
+ defer { window.isHidden = true }
268
+ func bind(_ title: String, secondary: String, layout: String = "linear",
269
+ visualWidth: Int, trailing: String?, icon: Bool = false, badge: Bool = false,
270
+ key: String = "asset") throws {
271
+ var column: [String: Any] = ["key": "asset", "text": title, "secondaryText": secondary]
272
+ if icon { column["titleIcon"] = ["name": "GasSolid", "accessibilityLabel": "Gas help"] }
273
+ let item = try NativeListItem(data: [
274
+ "key": key, "type": "dataRow", "height": 60,
275
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
276
+ "columns": [column], "badges": badge ? [["text": "Badge"]] : [],
277
+ "trailing": trailing.map { [["kind": "button", "label": $0, "actionKey": "swap"]] } ?? [],
278
+ "style": ["image": ["width": visualWidth, "height": visualWidth]],
279
+ ])
280
+ cell.bind(item: item, theme: nil, layout: layout, selected: false,
281
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
282
+ window.layoutIfNeeded()
283
+ cell.layoutIfNeeded()
284
+ }
285
+ func property<T>(_ name: String, in object: Any, as type: T.Type) throws -> T {
286
+ try XCTUnwrap(Mirror(reflecting: object).children.first { $0.label == name }?.value as? T)
287
+ }
288
+ let columns = try XCTUnwrap(cell.root.arrangedSubviews[3] as? UIStackView)
289
+ let firstColumn = columns.arrangedSubviews[0]
290
+ let primary: UILabel = try property("primaryLabel", in: firstColumn, as: UILabel.self)
291
+ let secondary: UILabel = try property("secondaryLabel", in: firstColumn, as: UILabel.self)
292
+ let secondaryLine: UIStackView = try property("secondaryLine", in: firstColumn,
293
+ as: UIStackView.self)
294
+ let titleIcon: UIImageView = try property("titleIconView", in: firstColumn,
295
+ as: UIImageView.self)
296
+ let badges: UIStackView = try property("badgesStack", in: firstColumn,
297
+ as: UIStackView.self)
298
+
299
+ try bind("ETH", secondary: "Ethereum", visualWidth: 32, trailing: "Swap",
300
+ icon: true, badge: true)
301
+ let sizeConstraints: [NSLayoutConstraint] = try property("rowConstraints", in: cell,
302
+ as: [NSLayoutConstraint].self)
303
+ XCTAssertEqual(sizeConstraints.count, 4)
304
+ let trailingStack = cell.root.arrangedSubviews[4]
305
+ let trailingWidth = try XCTUnwrap(trailingStack.constraints.first {
306
+ $0.firstAttribute == .width && ($0.firstItem as? UIView) === trailingStack
307
+ })
308
+ XCTAssertTrue(trailingWidth.isActive)
309
+ let shortTrailingWidth = trailingWidth.constant
310
+ XCTAssertEqual(sizeConstraints[2].constant, 32, accuracy: 0.1)
311
+ XCTAssertTrue(primary.attributedText?.string.contains("Badge") ?? false)
312
+ XCTAssertFalse(titleIcon.isHidden)
313
+ XCTAssertEqual(badges.arrangedSubviews.count, 0)
314
+
315
+ try bind("ETH", secondary: "Ethereum", visualWidth: 32, trailing: "Manage asset")
316
+ XCTAssertGreaterThan(trailingWidth.constant, shortTrailingWidth + 1)
317
+ let columnsFrame = columns.convert(columns.bounds, to: cell)
318
+ let trailingFrame = trailingStack.convert(trailingStack.bounds, to: cell)
319
+ XCTAssertGreaterThanOrEqual(trailingFrame.minX, columnsFrame.maxX - 0.5)
320
+ try bind("ETH", secondary: "Ethereum", visualWidth: 32, trailing: "Swap")
321
+ XCTAssertEqual(trailingWidth.constant, shortTrailingWidth, accuracy: 1)
322
+
323
+ try bind("", secondary: "", visualWidth: 48, trailing: nil)
324
+ let reboundConstraints: [NSLayoutConstraint] = try property("rowConstraints", in: cell,
325
+ as: [NSLayoutConstraint].self)
326
+ XCTAssertEqual(reboundConstraints.count, sizeConstraints.count)
327
+ XCTAssertTrue(zip(sizeConstraints, reboundConstraints).allSatisfy { $0 === $1 })
328
+ XCTAssertEqual(sizeConstraints[2].constant, 48, accuracy: 0.1)
329
+ XCTAssertFalse(trailingWidth.isActive)
330
+ XCTAssertEqual(primary.attributedText?.string, "")
331
+ XCTAssertNil(secondary.attributedText)
332
+ XCTAssertTrue(secondaryLine.isHidden)
333
+ XCTAssertTrue(titleIcon.isHidden)
334
+ XCTAssertNil(titleIcon.accessibilityLabel)
335
+ XCTAssertTrue(badges.arrangedSubviews.isEmpty)
336
+
337
+ try bind("Table", secondary: "New", layout: "table", visualWidth: 40, trailing: "Swap")
338
+ XCTAssertTrue(trailingWidth.isActive)
339
+ XCTAssertEqual(sizeConstraints[2].constant, 40, accuracy: 0.1)
340
+ XCTAssertEqual(primary.attributedText?.string, "Table")
341
+ XCTAssertEqual(secondary.attributedText?.string, "New")
342
+ try bind("Linear", secondary: "", visualWidth: 40, trailing: nil)
343
+ XCTAssertEqual(primary.attributedText?.string, "Linear")
344
+ XCTAssertNil(secondary.attributedText)
345
+ cell.prepareForReuse()
346
+ XCTAssertNil(primary.attributedText)
347
+ XCTAssertTrue(titleIcon.isHidden)
348
+ try bind("Replacement", secondary: "", visualWidth: 40, trailing: nil, key: "next")
349
+ XCTAssertEqual(primary.attributedText?.string, "Replacement")
350
+ }
351
+
352
+ func testIdentityTrailingActionUsesDescriptorSlotAfterCheckboxAndRebind() throws {
353
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 200))
354
+ let controller = UIViewController()
355
+ window.rootViewController = controller
356
+ window.isHidden = false
357
+ defer { window.isHidden = true }
358
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 56))
359
+ controller.view.addSubview(cell)
360
+ let trailing = try XCTUnwrap(
361
+ Mirror(reflecting: cell).children.first { $0.label == "trailingStack" }?.value
362
+ as? NativeListAccessoryStack)
363
+ var actions: [(rowKey: String, key: String, source: String, slot: Int?)] = []
364
+ cell.onAction = { item, key, _, origin in
365
+ actions.append((item.key, key, origin?.source ?? "", origin?.slot))
366
+ }
367
+ func bind(_ trailingData: [[String: Any]], key: String = "row") throws {
368
+ let item = try NativeListItem(data: [
369
+ "key": key, "type": "identity", "title": "Row", "trailing": trailingData,
370
+ ])
371
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
372
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
373
+ window.layoutIfNeeded()
374
+ cell.layoutIfNeeded()
375
+ }
376
+ func visibleButtons() -> [NativeListAccessoryButton] {
377
+ trailing.arrangedSubviews.compactMap { $0 as? NativeListAccessoryButton }
378
+ .filter { !$0.isHidden }
379
+ }
380
+ let checkbox: [String: Any] = [
381
+ "kind": "checkbox", "state": "unchecked", "actionKey": "selection",
382
+ ]
383
+ let first: [String: Any] = ["kind": "button", "label": "First", "actionKey": "first"]
384
+ let second: [String: Any] = ["kind": "button", "label": "Second", "actionKey": "second"]
385
+
386
+ try bind([checkbox, second])
387
+ XCTAssertEqual(visibleButtons().count, 1)
388
+ XCTAssertTrue(visibleButtons()[0].isEnabled)
389
+ XCTAssertTrue(visibleButtons()[0].isUserInteractionEnabled)
390
+ XCTAssertTrue(visibleButtons()[0].allTargets.contains(trailing))
391
+ XCTAssertNotNil(trailing.onAction)
392
+ try dispatchAccessoryTouchUpInside(visibleButtons()[0], on: trailing)
393
+ XCTAssertEqual(actions.last?.rowKey, "row")
394
+ XCTAssertEqual(actions.last?.key, "second")
395
+ XCTAssertEqual(actions.last?.source, "trailingAccessory")
396
+ XCTAssertEqual(actions.last?.slot, 1)
397
+ let selection = try XCTUnwrap(trailing.arrangedSubviews.compactMap { $0 as? UIButton }
398
+ .first { !($0 is NativeListAccessoryButton) && !$0.isHidden })
399
+ try dispatchAccessoryTouchUpInside(selection, on: trailing)
400
+ XCTAssertEqual(actions.last?.key, "selection")
401
+ XCTAssertNil(actions.last?.slot)
402
+
403
+ try bind([first, second])
404
+ XCTAssertEqual(visibleButtons().count, 2)
405
+ try dispatchAccessoryTouchUpInside(visibleButtons()[0], on: trailing)
406
+ XCTAssertEqual(actions.last?.key, "first")
407
+ XCTAssertEqual(actions.last?.slot, 0)
408
+ try dispatchAccessoryTouchUpInside(visibleButtons()[1], on: trailing)
409
+ XCTAssertEqual(actions.last?.key, "second")
410
+ XCTAssertEqual(actions.last?.slot, 1)
411
+
412
+ try bind([second], key: "replacement")
413
+ XCTAssertEqual(visibleButtons().count, 1)
414
+ try dispatchAccessoryTouchUpInside(visibleButtons()[0], on: trailing)
415
+ XCTAssertEqual(actions.last?.rowKey, "replacement")
416
+ XCTAssertEqual(actions.last?.key, "second")
417
+ XCTAssertEqual(actions.last?.slot, 0)
418
+ XCTAssertEqual(actions.count, 5)
419
+ }
420
+
421
+ func testIdentityTertiaryIconAnchorInsetSurvivesAccessoryRebind() throws {
422
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 200))
423
+ let controller = UIViewController()
424
+ window.rootViewController = controller
425
+ window.isHidden = false
426
+ defer { window.isHidden = true }
427
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 88))
428
+ controller.view.addSubview(cell)
429
+ let trailing = try XCTUnwrap(
430
+ Mirror(reflecting: cell).children.first { $0.label == "trailingStack" }?.value
431
+ as? NativeListAccessoryStack)
432
+ var actions: [(rowKey: String, source: String, slot: Int?, inset: CGFloat,
433
+ width: CGFloat)] = []
434
+ cell.onAction = { item, _, _, origin in
435
+ actions.append((item.key, origin?.source ?? "", origin?.slot, origin?.anchorInset ?? -1,
436
+ origin?.sourceView?.bounds.width ?? -1))
437
+ }
438
+ func bind(_ descriptors: [[String: Any]], key: String,
439
+ presentation: String? = nil) throws -> NativeListAccessoryButton {
440
+ var data: [String: Any] = [
441
+ "key": key, "type": "identity", "title": "Row", "height": 88,
442
+ "trailing": descriptors,
443
+ ]
444
+ if let presentation { data["presentation"] = presentation }
445
+ cell.bind(item: try NativeListItem(data: data), theme: nil, layout: "linear",
446
+ selected: false, checkboxState: { _, _, fallback in fallback },
447
+ fonts: NativeListFontFamilies())
448
+ window.layoutIfNeeded()
449
+ cell.layoutIfNeeded()
450
+ return try XCTUnwrap(trailing.firstVisibleControl as? NativeListAccessoryButton)
451
+ }
452
+ let tertiary: [String: Any] = [
453
+ "kind": "icon", "name": "CryptoCoinOutline", "buttonStyle": "tertiary",
454
+ "actionKey": "menu",
455
+ ]
456
+ let ordinary: [String: Any] = [
457
+ "kind": "icon", "name": "CryptoCoinOutline", "actionKey": "menu",
458
+ ]
459
+
460
+ let first = try bind([
461
+ ["kind": "checkbox", "state": "unchecked", "actionKey": "selection"], tertiary,
462
+ ], key: "tertiary-first")
463
+ XCTAssertEqual(first.bounds.width, 38, accuracy: 0.5)
464
+ try dispatchAccessoryTouchUpInside(first, on: trailing)
465
+ XCTAssertEqual(actions.last?.rowKey, "tertiary-first")
466
+ XCTAssertEqual(actions.last?.source, "trailingAccessory")
467
+ XCTAssertEqual(actions.last?.slot, 1)
468
+ XCTAssertEqual(actions.last?.inset, 7)
469
+ let firstOrigin = try XCTUnwrap(actions.last)
470
+ XCTAssertEqual(firstOrigin.width - 2 * firstOrigin.inset, 24, accuracy: 0.5)
471
+
472
+ let normal = try bind([ordinary], key: "ordinary")
473
+ XCTAssertEqual(normal.bounds.width, 36, accuracy: 0.5)
474
+ try dispatchAccessoryTouchUpInside(normal, on: trailing)
475
+ XCTAssertEqual(actions.last?.rowKey, "ordinary")
476
+ XCTAssertEqual(actions.last?.slot, 0)
477
+ XCTAssertEqual(actions.last?.inset, 0)
478
+ XCTAssertEqual(actions.last?.width, 36)
479
+
480
+ let value = try bind([["kind": "value", "text": "Value"]], key: "value")
481
+ value.bounds.size.width = 38
482
+ XCTAssertEqual(trailing.anchorInset(for: value), 0)
483
+
484
+ let rebound = try bind([tertiary], key: "tertiary-again")
485
+ try dispatchAccessoryTouchUpInside(rebound, on: trailing)
486
+ XCTAssertEqual(actions.last?.rowKey, "tertiary-again")
487
+ XCTAssertEqual(actions.last?.slot, 0)
488
+ XCTAssertEqual(actions.last?.inset, 7)
489
+ let reboundOrigin = try XCTUnwrap(actions.last)
490
+ XCTAssertEqual(reboundOrigin.width - 2 * reboundOrigin.inset, 24, accuracy: 0.5)
491
+
492
+ let account = try bind([ordinary], key: "account", presentation: "accountSelector")
493
+ XCTAssertEqual(account.bounds.width, 38, accuracy: 0.5)
494
+ try dispatchAccessoryTouchUpInside(account, on: trailing)
495
+ XCTAssertEqual(actions.last?.rowKey, "account")
496
+ XCTAssertEqual(actions.last?.slot, 0)
497
+ XCTAssertEqual(actions.last?.inset, 7)
498
+ let accountOrigin = try XCTUnwrap(actions.last)
499
+ XCTAssertEqual(accountOrigin.width - 2 * accountOrigin.inset, 24, accuracy: 0.5)
500
+
501
+ let finalOrdinary = try bind([ordinary], key: "ordinary-again")
502
+ try dispatchAccessoryTouchUpInside(finalOrdinary, on: trailing)
503
+ XCTAssertEqual(actions.last?.rowKey, "ordinary-again")
504
+ XCTAssertEqual(actions.last?.inset, 0)
505
+ XCTAssertEqual(actions.count, 5)
506
+ }
507
+
508
+ func testValuePairSegmentsStyleAndPlainRebindOnProductionAccessoryStack() throws {
509
+ let stack = NativeListAccessoryStack(frame: CGRect(x: 0, y: 0, width: 180, height: 48))
510
+ let item = try NativeListItem(data: [
511
+ "key": "pair", "type": "identity", "title": "Pair",
512
+ "leading": ["kind": "icon", "name": "coin"],
513
+ ])
514
+ let pair: [String: Any] = [
515
+ "kind": "valuePair", "primary": "0.001", "secondary": "$0.01",
516
+ "primaryTextSegments": [["text": "0.00"], ["text": "1", "style": "subscript"]],
517
+ "secondaryTextSegments": [["text": "$0.0"], ["text": "1", "style": "subscript"]],
518
+ ]
519
+ func bind(_ descriptor: [String: Any], size: Int? = nil) {
520
+ let style: [String: Any] = size.map { ["value": ["fontSize": $0]] } ?? [:]
521
+ stack.bind(item, descriptors: [descriptor], theme: nil, style: style,
522
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
523
+ }
524
+ func fontSize(_ title: NSAttributedString, at index: Int) throws -> CGFloat {
525
+ try XCTUnwrap(title.attribute(.font, at: index, effectiveRange: nil) as? UIFont).pointSize
526
+ }
527
+ bind(pair)
528
+ let button = try XCTUnwrap(stack.arrangedSubviews.compactMap { $0 as? UIButton }
529
+ .first { !$0.isHidden })
530
+ let rich = try XCTUnwrap(button.attributedTitle(for: .normal))
531
+ XCTAssertEqual(rich.string, "0.001\n$0.01")
532
+ XCTAssertEqual(try fontSize(rich, at: 0), 16)
533
+ XCTAssertEqual(try fontSize(rich, at: 4), 10)
534
+ XCTAssertEqual(try fontSize(rich, at: 6), 14)
535
+ XCTAssertEqual(try fontSize(rich, at: 10), 9)
536
+ bind(pair, size: 20)
537
+ let styled = try XCTUnwrap(button.attributedTitle(for: .normal))
538
+ XCTAssertEqual(try fontSize(styled, at: 0), 20)
539
+ XCTAssertEqual(try fontSize(styled, at: 4), 12)
540
+ XCTAssertEqual(try fontSize(styled, at: 10), 12)
541
+ bind(["kind": "valuePair", "primary": "10", "secondary": "$2"])
542
+ let plain = try XCTUnwrap(button.attributedTitle(for: .normal))
543
+ XCTAssertEqual(plain.string, "10\n$2")
544
+ XCTAssertEqual(try fontSize(plain, at: 0), 16)
545
+ XCTAssertEqual(try fontSize(plain, at: 3), 14)
546
+ bind(["kind": "valuePair", "primary": "10", "secondary": "$2",
547
+ "primaryTextSegments": [], "secondaryTextSegments": []])
548
+ XCTAssertEqual(button.attributedTitle(for: .normal)?.string, "10\n$2")
549
+ stack.reset()
550
+ XCTAssertNil(button.title(for: .normal))
551
+ XCTAssertNil(button.attributedTitle(for: .normal))
552
+ XCTAssertTrue(button.isHidden)
553
+ bind(["kind": "value", "text": "Updated"])
554
+ XCTAssertEqual(button.title(for: .normal), "Updated")
555
+ XCTAssertEqual(button.titleLabel?.text, "Updated")
556
+ XCTAssertNil(button.attributedTitle(for: .normal))
557
+ }
558
+
559
+ func testDecorativeRefreshKeepsSixteenPointFrameAcrossActionRebind() throws {
560
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 56))
561
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 80))
562
+ window.addSubview(cell)
563
+ let stack = try XCTUnwrap(Mirror(reflecting: cell).children.first {
564
+ $0.label == "trailingStack"
565
+ }?.value as? NativeListAccessoryStack)
566
+ func bind(actionKey: String? = nil) throws {
567
+ var icon: [String: Any] = ["kind": "icon", "name": "RefreshCcwOutline"]
568
+ if let actionKey { icon["actionKey"] = actionKey }
569
+ let item = try NativeListItem(data: [
570
+ "key": "refresh", "type": "identity", "title": "Network", "height": 56,
571
+ "leading": ["kind": "icon", "name": "coin"], "trailing": [icon],
572
+ ])
573
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
574
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
575
+ window.layoutIfNeeded()
576
+ cell.layoutIfNeeded()
577
+ }
578
+ try bind()
579
+ let button = try XCTUnwrap(stack.firstVisibleControl as? UIButton)
580
+ XCTAssertEqual(button.bounds.width, 16, accuracy: 0.5)
581
+ XCTAssertEqual(button.bounds.height, 16, accuracy: 0.5)
582
+ XCTAssertNotNil(button.image(for: .normal))
583
+ XCTAssertEqual(button.image(for: .normal)?.size.width, 16)
584
+ XCTAssertEqual(button.image(for: .normal)?.size.height, 16)
585
+ XCTAssertFalse(button.isUserInteractionEnabled)
586
+ try bind(actionKey: "refresh")
587
+ XCTAssertEqual(button.bounds.width, 36, accuracy: 0.5)
588
+ XCTAssertEqual(button.bounds.height, 36, accuracy: 0.5)
589
+ XCTAssertTrue(button.isUserInteractionEnabled)
590
+ try bind()
591
+ XCTAssertEqual(button.bounds.width, 16, accuracy: 0.5)
592
+ XCTAssertEqual(button.bounds.height, 16, accuracy: 0.5)
593
+ XCTAssertEqual(button.image(for: .normal)?.size.width, 16)
594
+ XCTAssertEqual(button.image(for: .normal)?.size.height, 16)
595
+ XCTAssertFalse(button.isUserInteractionEnabled)
596
+ }
597
+
598
+ func testLowValueAndOverviewAccessoryLayoutsOnProductionIdentityCell() throws {
599
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 60))
600
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 180))
601
+ window.addSubview(cell)
602
+ let main = try XCTUnwrap(Mirror(reflecting: cell).children.first { $0.label == "mainStack" }?
603
+ .value as? UIStackView)
604
+ let trailing = try XCTUnwrap(Mirror(reflecting: cell).children.first {
605
+ $0.label == "trailingStack"
606
+ }?.value as? NativeListAccessoryStack)
607
+ func bind(_ data: [String: Any], height: CGFloat) throws {
608
+ cell.frame.size.height = height
609
+ cell.bind(item: try NativeListItem(data: data), theme: nil, layout: "linear",
610
+ selected: false, checkboxState: { _, _, fallback in fallback },
611
+ fonts: NativeListFontFamilies())
612
+ window.layoutIfNeeded()
613
+ cell.layoutIfNeeded()
614
+ }
615
+ let pair: [String: Any] = ["kind": "valuePair", "primary": "1.0193B",
616
+ "secondary": "$1,018,849,363.70"]
617
+ let lowValue: [String: Any] = ["key": "low", "type": "identity", "height": 60,
618
+ "title": "FRAX", "subtitleSegments": [
619
+ ["text": "$0.9918", "tone": "secondary", "textSegments": [
620
+ ["text": "$0.99"], ["text": "18", "style": "subscript"]]],
621
+ ["text": "\u{00a0}+0.05%", "tone": "positive"]],
622
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
623
+ "trailing": [pair], "style": ["horizontalPadding": 12, "verticalPadding": 8,
624
+ "leadingGap": 12, "image": ["width": 40, "height": 40]]]
625
+ try bind(lowValue, height: 60)
626
+ let priceLabels = try XCTUnwrap(Mirror(reflecting: cell).children.first {
627
+ $0.label == "semanticSubtitleLabels"
628
+ }?.value as? [UILabel])
629
+ XCTAssertEqual(priceLabels.count, 2)
630
+ XCTAssertGreaterThan(main.bounds.width, 150)
631
+ XCTAssertTrue(priceLabels.allSatisfy { $0.bounds.width > 0 && !$0.isHidden })
632
+ XCTAssertLessThanOrEqual(priceLabels.last?.frame.maxX ?? .infinity, main.bounds.width + 0.5)
633
+ XCTAssertEqual(trailing.bounds.width, trailing.firstVisibleControl?.bounds.width ?? -1,
634
+ accuracy: 0.5)
635
+ let detail: [String: Any] = ["key": "detail", "type": "identity", "height": 60,
636
+ "title": "Ethereum", "subtitle": "100.0%",
637
+ "leading": ["kind": "network", "fallbackIcon": ["name": "GlobusOutline"]],
638
+ "trailing": [pair, ["kind": "chevron"]],
639
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
640
+ "trailingGap": 12, "image": ["width": 32, "height": 32]]]
641
+ try bind(detail, height: 60)
642
+ XCTAssertEqual(trailing.axis, .horizontal)
643
+ let detailControls = trailing.arrangedSubviews.filter { !$0.isHidden }
644
+ XCTAssertEqual(detailControls.count, 2)
645
+ let detailRects = detailControls.map { $0.convert($0.bounds, to: cell) }
646
+ XCTAssertTrue(detailRects.allSatisfy { $0.minY >= 0 && $0.maxY <= 60 })
647
+ XCTAssertEqual(detailRects[0].midY, detailRects[1].midY, accuracy: 1)
648
+ XCTAssertEqual(detailRects[1].minX - detailRects[0].maxX, 12, accuracy: 0.5)
649
+ XCTAssertEqual(detailRects[1].maxX, cell.bounds.maxX - 12, accuracy: 0.5)
650
+ let missing: [String: Any] = ["key": "missing", "type": "identity", "height": 48,
651
+ "title": "Ethereum", "leading": ["kind": "network",
652
+ "fallbackIcon": ["name": "GlobusOutline"]],
653
+ "trailing": [["kind": "icon", "name": "RefreshCcwOutline"], ["kind": "chevron"]],
654
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
655
+ "trailingGap": 12, "image": ["width": 32, "height": 32]]]
656
+ try bind(missing, height: 48)
657
+ XCTAssertEqual(trailing.axis, .horizontal)
658
+ let missingControls = trailing.arrangedSubviews.filter { !$0.isHidden }
659
+ XCTAssertEqual(missingControls.count, 2)
660
+ XCTAssertEqual(missingControls[0].bounds.width, 16, accuracy: 0.5)
661
+ XCTAssertEqual(missingControls[1].bounds.width, 24, accuracy: 0.5)
662
+ let missingRects = missingControls.map { $0.convert($0.bounds, to: cell) }
663
+ XCTAssertTrue(missingRects.allSatisfy { $0.minY >= 0 && $0.maxY <= 48 })
664
+ XCTAssertEqual(missingRects[0].midY, missingRects[1].midY, accuracy: 1)
665
+ XCTAssertEqual(missingRects[1].minX - missingRects[0].maxX, 12, accuracy: 0.5)
666
+ XCTAssertEqual(missingRects[1].maxX, cell.bounds.maxX - 12, accuracy: 0.5)
667
+ try bind(detail, height: 60)
668
+ XCTAssertEqual(trailing.axis, .horizontal)
669
+ try bind(["key": "plain", "type": "identity", "title": "Plain", "height": 56,
670
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]]],
671
+ height: 56)
672
+ let remainingConstraints = try XCTUnwrap(Mirror(reflecting: cell).children.first {
673
+ $0.label == "selectorConstraints"
674
+ }?.value as? [NSLayoutConstraint])
675
+ XCTAssertTrue(remainingConstraints.isEmpty)
676
+ }
677
+
678
+ func testSwapValuePairAndTertiaryMenuIconFitAndKeepActionState() throws {
679
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 60))
680
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 120))
681
+ window.addSubview(cell)
682
+ defer { cell.removeFromSuperview() }
683
+ let trailing = try XCTUnwrap(Mirror(reflecting: cell).children.first {
684
+ $0.label == "trailingStack"
685
+ }?.value as? NativeListAccessoryStack)
686
+ var actions: [(String, Int?)] = []
687
+ cell.onAction = { _, action, _, origin in actions.append((action, origin?.slot)) }
688
+ func bind(disabled: Bool) throws {
689
+ let item = try NativeListItem(data: [
690
+ "key": "swap-token", "type": "identity", "height": 60,
691
+ "title": "ETH", "subtitle": "Ethereum",
692
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
693
+ "trailing": [
694
+ ["kind": "valuePair", "primary": "0.001328", "secondary": "$3.08"],
695
+ ["kind": "icon", "name": "DotVerSolid", "buttonStyle": "tertiary",
696
+ "actionKey": "menu", "disabled": disabled],
697
+ ],
698
+ "style": ["horizontalPadding": 20, "verticalPadding": 8,
699
+ "leadingGap": 12, "trailingGap": 8,
700
+ "image": ["width": 40, "height": 40]],
701
+ ])
702
+ cell.bind(item: item, theme: nil, layout: "linear", selected: false,
703
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
704
+ window.layoutIfNeeded()
705
+ cell.layoutIfNeeded()
706
+ }
707
+ try bind(disabled: false)
708
+ XCTAssertEqual(trailing.axis, .horizontal)
709
+ let controls = trailing.arrangedSubviews.compactMap { !$0.isHidden ? $0 as? UIButton : nil }
710
+ XCTAssertEqual(controls.count, 2)
711
+ let rects = controls.map { $0.convert($0.bounds, to: cell) }
712
+ XCTAssertTrue(rects.allSatisfy { $0.minY >= 0 && $0.maxY <= cell.bounds.height })
713
+ let amountLabel = try XCTUnwrap(controls[0].titleLabel)
714
+ let amountRect = amountLabel.convert(amountLabel.bounds, to: cell)
715
+ XCTAssertEqual(amountLabel.numberOfLines, 2)
716
+ XCTAssertGreaterThan(amountRect.height, 30)
717
+ XCTAssertGreaterThanOrEqual(amountRect.minY, 0)
718
+ XCTAssertLessThanOrEqual(amountRect.maxY, cell.bounds.height)
719
+ XCTAssertEqual(rects[0].midY, rects[1].midY, accuracy: 1)
720
+ XCTAssertEqual(rects[1].minX - rects[0].maxX, 8, accuracy: 0.5)
721
+ XCTAssertEqual(controls[1].bounds.height, 38, accuracy: 0.5)
722
+ XCTAssertTrue(controls[1].isEnabled)
723
+ try dispatchAccessoryTouchUpInside(controls[1], on: trailing)
724
+ XCTAssertEqual(actions.count, 1)
725
+ let action = try XCTUnwrap(actions.first)
726
+ XCTAssertEqual(action.0, "menu")
727
+ XCTAssertEqual(action.1, 1)
728
+
729
+ try bind(disabled: true)
730
+ let disabledIcon = try XCTUnwrap(trailing.arrangedSubviews.filter { !$0.isHidden }.last as? UIButton)
731
+ XCTAssertFalse(disabledIcon.isEnabled)
732
+ try dispatchAccessoryTouchUpInside(disabledIcon, on: trailing)
733
+ XCTAssertEqual(actions.count, 1)
734
+ }
735
+
736
+ func testRiskIdentityRatioKeepsTitleVisibleWithAndWithoutButton() throws {
737
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 386, height: 56))
738
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 386, height: 200))
739
+ window.addSubview(cell)
740
+ let titleLabel = try XCTUnwrap(
741
+ Mirror(reflecting: cell).children.first { $0.label == "titleLabel" }?.value as? UILabel)
742
+ let mainStack = try XCTUnwrap(
743
+ Mirror(reflecting: cell).children.first { $0.label == "mainStack" }?.value as? UIStackView)
744
+ let trailing = try XCTUnwrap(
745
+ Mirror(reflecting: cell).children.first { $0.label == "trailingStack" }?.value
746
+ as? NativeListAccessoryStack)
747
+ let base: [String: Any] = [
748
+ "key": "risk", "type": "identity", "title": "XSR", "height": 56,
749
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
750
+ "style": [
751
+ "horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
752
+ "leadingContentMaxWidthRatio": 0.6,
753
+ "image": ["width": 40, "height": 40, "shape": "circle"],
754
+ "title": ["fontSize": 16, "lineHeight": 24, "fontWeight": "medium", "lines": 1],
755
+ ],
756
+ ]
757
+
758
+ func bind(_ data: [String: Any], capped: Bool = true) throws {
759
+ cell.bind(item: try NativeListItem(data: data), theme: nil, layout: "linear",
760
+ selected: false, checkboxState: { _, _, fallback in fallback },
761
+ fonts: NativeListFontFamilies())
762
+ window.layoutIfNeeded()
763
+ cell.layoutIfNeeded()
764
+ XCTAssertFalse(titleLabel.isHidden)
765
+ XCTAssertGreaterThan(titleLabel.bounds.width, 0.5,
766
+ "A visible token title must not collapse when the row reserves trailing space")
767
+ XCTAssertEqual(titleLabel.bounds.height, 24, accuracy: 0.5)
768
+ let intrinsicWidth = titleLabel.intrinsicContentSize.width
769
+ let capWidth = cell.root.bounds.width * 0.6 - 52
770
+ let requiredTitleWidth = capped ? min(intrinsicWidth, capWidth) : intrinsicWidth
771
+ XCTAssertGreaterThanOrEqual(titleLabel.bounds.width, requiredTitleWidth - 0.5,
772
+ "title=\(data["title"] ?? "") intrinsic=\(intrinsicWidth) "
773
+ + "rendered=\(titleLabel.bounds.width) root=\(cell.root.bounds.width) "
774
+ + "trailing=\(trailing.bounds.width)")
775
+ XCTAssertGreaterThanOrEqual(mainStack.bounds.width, titleLabel.bounds.width - 0.5)
776
+ XCTAssertEqual(trailing.frame.maxX, cell.root.bounds.maxX, accuracy: 0.5)
777
+ if capped {
778
+ XCTAssertLessThanOrEqual(mainStack.bounds.width, cell.root.bounds.width * 0.6 - 52 + 0.5)
779
+ }
780
+ }
781
+
782
+ try bind(base)
783
+ XCTAssertNil(trailing.firstVisibleControl)
784
+ try bind(base.merging(["trailing": [[
785
+ "kind": "button", "label": "Show on home", "actionKey": "show",
786
+ ]]]) { _, newer in newer })
787
+ let button = try XCTUnwrap(trailing.firstVisibleControl)
788
+ XCTAssertGreaterThan(button.bounds.width, 100)
789
+ XCTAssertEqual(trailing.frame.minX + button.frame.maxX, cell.root.bounds.maxX, accuracy: 0.5)
790
+ cell.frame.size.height = 88
791
+ try bind(base.merging(["trailing": [
792
+ ["kind": "button", "label": "A", "actionKey": "first"],
793
+ ["kind": "button", "label": "Longer action", "actionKey": "second"],
794
+ ], "height": 88]) { _, newer in newer })
795
+ let visibleButtons = trailing.arrangedSubviews.compactMap { $0 as? NativeListAccessoryButton }
796
+ .filter { !$0.isHidden }
797
+ XCTAssertEqual(visibleButtons.count, 2)
798
+ XCTAssertGreaterThan(visibleButtons[1].bounds.width, visibleButtons[0].bounds.width)
799
+ XCTAssertEqual(trailing.frame.minX + visibleButtons[1].frame.maxX,
800
+ cell.root.bounds.maxX, accuracy: 0.5)
801
+ cell.frame.size.height = 56
802
+ try bind(base.merging(["title": "A very long token symbol that must truncate within the cap"])
803
+ { _, newer in newer })
804
+ XCTAssertLessThan(titleLabel.bounds.width, titleLabel.intrinsicContentSize.width)
805
+ try bind(base)
806
+ XCTAssertNil(trailing.firstVisibleControl)
807
+ try bind(base.merging(["key": "searched-risk", "title": "rkl"]) { _, newer in newer })
808
+ XCTAssertNil(trailing.firstVisibleControl)
809
+ try bind(base)
810
+ var unrestricted = base
811
+ var unrestrictedStyle = try XCTUnwrap(base["style"] as? [String: Any])
812
+ unrestrictedStyle.removeValue(forKey: "leadingContentMaxWidthRatio")
813
+ unrestricted["style"] = unrestrictedStyle
814
+ try bind(unrestricted, capped: false)
815
+ XCTAssertEqual(cell.root.arrangedSubviews.count, 3)
816
+ XCTAssertEqual(mainStack.contentHuggingPriority(for: .horizontal).rawValue, 1, accuracy: 0.1)
817
+ let spacing = cell.root.customSpacing(after: mainStack)
818
+ XCTAssertTrue(spacing == UIStackView.spacingUseDefault || spacing == cell.root.spacing)
819
+ }
820
+
821
+ func testAutoHeightIdentityReservesMeasuredTrailingWidth() throws {
822
+ let subtitle = "A long recipient address that must wrap within the space left beside its values and controls"
823
+ func item(
824
+ trailing: [[String: Any]], horizontalPadding: Double? = nil,
825
+ presentation: String = ""
826
+ ) throws -> NativeListItem {
827
+ var style: [String: Any] = ["image": ["width": 40, "height": 40]]
828
+ if let horizontalPadding { style["horizontalPadding"] = horizontalPadding }
829
+ return try NativeListItem(data: [
830
+ "key": "recipient", "type": "identity", "title": "Recipient", "subtitle": subtitle,
831
+ "subtitleLines": 0, "contentHeight": "auto", "style": style,
832
+ "presentation": presentation,
833
+ "trailing": trailing,
834
+ ])
835
+ }
836
+ func height(width: CGFloat, item: NativeListItem) throws -> CGFloat {
837
+ return try XCTUnwrap(NativeListIdentityCell.measure(
838
+ item, width: width, theme: nil, layout: "linear", fonts: NativeListFontFamilies()))
839
+ }
840
+
841
+ let pair: [[String: Any]] = [[
842
+ "kind": "valuePair", "primary": "$123,456.78", "secondary": "12345 TOKEN",
843
+ ]]
844
+ let pairAndMenu = pair + [["kind": "menu", "actionKey": "menu"]]
845
+ let pairItem = try item(trailing: pair)
846
+ let pairHeight = try height(width: 240, item: pairItem)
847
+ XCTAssertGreaterThan(pairHeight, try height(width: 240, item: item(trailing: [])))
848
+ XCTAssertGreaterThanOrEqual(try height(width: 240, item: item(trailing: pairAndMenu)),
849
+ pairHeight)
850
+ let cell = NativeListIdentityCell(frame: CGRect(x: 0, y: 0, width: 240, height: pairHeight))
851
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 240, height: pairHeight))
852
+ window.addSubview(cell)
853
+ cell.bind(item: pairItem, theme: nil, layout: "linear", selected: false,
854
+ checkboxState: { _, _, fallback in fallback }, fonts: NativeListFontFamilies())
855
+ window.layoutIfNeeded()
856
+ cell.layoutIfNeeded()
857
+ let subtitleLabel = try XCTUnwrap(Mirror(reflecting: cell).children.first {
858
+ $0.label == "subtitleLabel"
859
+ }?.value as? UILabel)
860
+ XCTAssertGreaterThan(subtitleLabel.bounds.width, 0.5)
861
+ XCTAssertGreaterThanOrEqual(subtitleLabel.bounds.height + 0.5,
862
+ subtitleLabel.sizeThatFits(CGSize(
863
+ width: subtitleLabel.bounds.width, height: .greatestFiniteMagnitude)).height)
864
+ let accountIcon: [[String: Any]] = [[
865
+ "kind": "icon", "name": "DotHorOutline", "actionKey": "menu",
866
+ ]]
867
+ XCTAssertGreaterThanOrEqual(
868
+ try height(width: 220, item: item(trailing: accountIcon,
869
+ horizontalPadding: 28, presentation: "accountSelector")),
870
+ try height(width: 220, item: item(trailing: accountIcon,
871
+ presentation: "accountSelector")))
872
+ }
873
+
156
874
  func testFixedFooterReplacesRendererAndKeepsActionRouting() throws {
157
875
  let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
158
876
  var actions: [[String: Any]] = []
@@ -246,6 +964,35 @@ final class NativeListLifecycleTests: XCTestCase {
246
964
  XCTAssertEqual(footer.accessibilityLabel, "Continue")
247
965
  }
248
966
 
967
+ func testPaddedSquareNetworkOverlayRoundsInnerImageAndResetsOnRebind() throws {
968
+ let visual = NativeListLeadingVisual(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
969
+ func bind(_ overlay: [String: Any]) {
970
+ visual.bind(["kind": "token", "overlays": [overlay]], style: [:], key: "overlay",
971
+ theme: nil, isUnread: false, fonts: NativeListFontFamilies())
972
+ visual.layoutIfNeeded()
973
+ }
974
+ let image: [String: Any] = ["uri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9xvY0AAAAASUVORK5CYII="]
975
+ bind(["position": "bottomRight", "size": 20, "width": 20, "height": 20,
976
+ "padding": 2, "image": image, "fallbackIcon": ["name": "GlobusOutline"]])
977
+ let slots = try XCTUnwrap(Mirror(reflecting: visual).children.first {
978
+ $0.label == "overlaySlots"
979
+ }?.value as? [NativeListImageSlot])
980
+ let slot = try XCTUnwrap(slots.first?.view)
981
+ XCTAssertEqual(slot.bounds.size, CGSize(width: 16, height: 16))
982
+ XCTAssertEqual(slot.layer.cornerRadius, 8, accuracy: 0.5)
983
+ XCTAssertTrue(slot.clipsToBounds)
984
+ bind(["position": "bottomRight", "width": 20, "height": 14,
985
+ "padding": 2, "image": image])
986
+ XCTAssertEqual(slot.layer.cornerRadius, 0)
987
+ XCTAssertFalse(slot.clipsToBounds)
988
+ bind(["position": "bottomRight", "size": 20, "padding": 2, "text": "E"])
989
+ XCTAssertEqual(slot.layer.cornerRadius, 0)
990
+ XCTAssertFalse(slot.clipsToBounds)
991
+ bind(["position": "bottomRight", "size": 20, "padding": 2, "image": image])
992
+ XCTAssertEqual(slot.layer.cornerRadius, 8, accuracy: 0.5)
993
+ visual.recycle()
994
+ }
995
+
249
996
  func testNestedWalletMembersAndDragBadgeFollowEachBindMapping() throws {
250
997
  let group = NativeListWalletGroupCell(frame: CGRect(x: 0, y: 0, width: 320, height: 200))
251
998
  let item = try NativeListItem(data: [
@@ -348,7 +1095,7 @@ final class NativeListLifecycleTests: XCTestCase {
348
1095
  XCTAssertTrue(header.clipsToBounds)
349
1096
  XCTAssertEqual(header.bounds.height, 0, "An unmeasured header cannot draw over the first rows")
350
1097
 
351
- view.setContainerSlotHeightsJson("[44,44,60]")
1098
+ view.setContainerSlotHeightsJson("[44,44,60,0]")
352
1099
  view.layoutIfNeeded()
353
1100
  list.layoutIfNeeded()
354
1101
  XCTAssertEqual(slots[0].convert(CGPoint.zero, to: list), CGPoint(x: 16, y: 0))
@@ -363,10 +1110,1754 @@ final class NativeListLifecycleTests: XCTestCase {
363
1110
  XCTAssertNil(slots[2].superview)
364
1111
  }
365
1112
 
1113
+ func testSidecarCentersRowsWhenConfiguredBeforeFirstWidth() throws {
1114
+ try assertHomeSidecarGeometry(sidecarBeforeFirstLayout: true)
1115
+ }
1116
+
1117
+ func testSidecarCentersRowsWhenConfiguredAfterFirstWidth() throws {
1118
+ try assertHomeSidecarGeometry(sidecarBeforeFirstLayout: false)
1119
+ }
1120
+
1121
+ func testHomeLinearColumnsStayInsideTheirStackAcrossEmptyMiddleAndReuse() throws {
1122
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 900))
1123
+ let controller = UIViewController()
1124
+ window.rootViewController = controller
1125
+ let view = NativeListView(frame: window.bounds)
1126
+ controller.view.addSubview(view)
1127
+ window.isHidden = false
1128
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1129
+ defer {
1130
+ view.dispose()
1131
+ view.removeFromSuperview()
1132
+ window.isHidden = true
1133
+ window.rootViewController = nil
1134
+ }
1135
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
1136
+ view.setContainerSlotHeightsJson("[0,0,0,1200]")
1137
+ let sidecar = "{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}"
1138
+ view.setSidecarLayoutJson(sidecar)
1139
+
1140
+ func columns(middle: String?, two: Bool = false) -> [[String: Any]] {
1141
+ let first: [String: Any] = ["key": "asset", "text": "USD1",
1142
+ "secondaryText": "Public fixture", "weight": 1]
1143
+ let balance: [String: Any] = ["key": "balance", "text": middle ?? "",
1144
+ "secondaryText": middle == nil ? "" : "$0.01", "alignment": "end", "weight": 1]
1145
+ let price: [String: Any] = ["key": "price", "text": "$1.00",
1146
+ "secondaryText": "0.01%", "alignment": "end", "weight": 1]
1147
+ return two ? [first, price] : [first, balance, price]
1148
+ }
1149
+ let rows: [[String: Any]] = (0..<30).map { index in
1150
+ ["key": "row-\(index)", "type": "dataRow", "height": 60,
1151
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
1152
+ "columns": index == 20 ? columns(middle: "0.01") : homeSidecarColumns(index, updated: false),
1153
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]],
1154
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
1155
+ "columns": ["token": "$bodyLg", "fontWeight": "medium", "lines": 1],
1156
+ "columnSecondary": ["token": "$bodyMd", "lines": 1],
1157
+ "image": ["width": 32, "height": 32]]]
1158
+ }
1159
+ let snapshot: [String: Any] = ["schemaVersion": 1, "generation": 1,
1160
+ "layout": ["kind": "linear", "contentPaddingHorizontal": 8], "rows": rows]
1161
+ view.applySnapshotJson(String(decoding: try JSONSerialization.data(withJSONObject: snapshot),
1162
+ as: UTF8.self))
1163
+ list.contentInsetAdjustmentBehavior = .never
1164
+ func layout() {
1165
+ window.layoutIfNeeded()
1166
+ view.layoutIfNeeded()
1167
+ list.layoutIfNeeded()
1168
+ }
1169
+ func check(_ phase: String, count: Int, width: CGFloat, weights: [Int]? = nil) throws {
1170
+ layout()
1171
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1172
+ as? NativeListDataRowCell, phase)
1173
+ let stack = try XCTUnwrap(cell.root.arrangedSubviews[3] as? UIStackView, phase)
1174
+ let visible = stack.arrangedSubviews.filter { !$0.isHidden }
1175
+ XCTAssertEqual(stack.arrangedSubviews.count, 4, phase)
1176
+ XCTAssertEqual(stack.arrangedSubviews.map(\.isHidden),
1177
+ (0..<4).map { $0 >= count }, phase)
1178
+ XCTAssertEqual(visible.count, count, phase)
1179
+ let cellFrame = cell.convert(cell.bounds, to: list)
1180
+ let stackFrame = stack.convert(stack.bounds, to: list)
1181
+ let attributes = try XCTUnwrap(list.layoutAttributesForItem(
1182
+ at: IndexPath(item: 20, section: 0)), phase)
1183
+ XCTAssertEqual(attributes.frame.width, width, accuracy: 1, phase)
1184
+ XCTAssertEqual(cellFrame.width, width, accuracy: 1,
1185
+ "\(phase) window=\(window.frame) controller=\(controller.view.frame) view=\(view.frame) list=\(list.frame) bounds=\(list.bounds) attributes=\(attributes.frame)")
1186
+ let rowConstraints = Mirror(reflecting: cell).children.first {
1187
+ $0.label == "rowConstraints"
1188
+ }?.value as? [NSLayoutConstraint] ?? []
1189
+ let columnWidthConstraints = Mirror(reflecting: cell).children.first {
1190
+ $0.label == "columnWidthConstraints"
1191
+ }?.value as? [NSLayoutConstraint] ?? []
1192
+ let constraints = rowConstraints + columnWidthConstraints
1193
+ let constraintState = constraints.map { constraint in
1194
+ let first = stack.arrangedSubviews.firstIndex {
1195
+ $0 === constraint.firstItem as? UIView
1196
+ } ?? -1
1197
+ let second = stack.arrangedSubviews.firstIndex {
1198
+ $0 === constraint.secondItem as? UIView
1199
+ } ?? -1
1200
+ return "\(first):\(second):\(constraint.multiplier):\(constraint.isActive)"
1201
+ }.joined(separator: ",")
1202
+ let hidingState = stack.arrangedSubviews.enumerated().map { index, column in
1203
+ let hiding = (stack.constraints + column.constraints).filter {
1204
+ $0.isActive && $0.identifier == "UISV-hiding"
1205
+ }.map { "\($0.constant)" }.joined(separator: ",")
1206
+ return "\(index):\(column.isHidden):\(hiding)"
1207
+ }.joined(separator: ",")
1208
+ let geometry = "\(phase) model=\(count) cell=\(cellFrame) stack=\(stackFrame) "
1209
+ + "columns=\(stack.arrangedSubviews.map { "\($0.isHidden):\($0.convert($0.bounds, to: list))" }) "
1210
+ + "constraints=\(constraintState) hiding=\(hidingState)"
1211
+ XCTAssertGreaterThanOrEqual(stackFrame.minX, cellFrame.minX - 0.5, geometry)
1212
+ XCTAssertLessThanOrEqual(stackFrame.maxX, cellFrame.maxX + 0.5, geometry)
1213
+ for column in visible {
1214
+ let columnFrame = column.convert(column.bounds, to: list)
1215
+ XCTAssertGreaterThan(columnFrame.width, 0, geometry)
1216
+ XCTAssertGreaterThanOrEqual(columnFrame.minX, stackFrame.minX - 0.5, geometry)
1217
+ XCTAssertLessThanOrEqual(columnFrame.maxX, stackFrame.maxX + 0.5, geometry)
1218
+ let primaryLine = (column as? UIStackView)?.arrangedSubviews.first
1219
+ if let primaryLine {
1220
+ let lineFrame = primaryLine.convert(primaryLine.bounds, to: list)
1221
+ XCTAssertGreaterThanOrEqual(lineFrame.minX, columnFrame.minX - 0.5, geometry)
1222
+ XCTAssertLessThanOrEqual(lineFrame.maxX, columnFrame.maxX + 0.5, geometry)
1223
+ }
1224
+ for label in labels(in: column) where !label.isHidden {
1225
+ let labelFrame = label.convert(label.bounds, to: list)
1226
+ XCTAssertGreaterThanOrEqual(labelFrame.minX, columnFrame.minX - 0.5,
1227
+ "\(geometry) label=\(labelFrame)")
1228
+ XCTAssertLessThanOrEqual(labelFrame.maxX, columnFrame.maxX + 0.5,
1229
+ "\(geometry) label=\(labelFrame)")
1230
+ }
1231
+ }
1232
+ if count >= 2 {
1233
+ let expectedWeights = weights ?? Array(repeating: 1, count: count)
1234
+ XCTAssertEqual(expectedWeights.count, count, geometry)
1235
+ for index in 1..<count {
1236
+ XCTAssertEqual(visible[index].bounds.width,
1237
+ visible[0].bounds.width * CGFloat(expectedWeights[index])
1238
+ / CGFloat(expectedWeights[0]),
1239
+ accuracy: 1, geometry)
1240
+ let previous = visible[index - 1].convert(visible[index - 1].bounds, to: stack)
1241
+ let current = visible[index].convert(visible[index].bounds, to: stack)
1242
+ XCTAssertGreaterThanOrEqual(current.minX, previous.maxX - 0.5, geometry)
1243
+ XCTAssertEqual(current.minX - previous.maxX, stack.spacing,
1244
+ accuracy: 0.5, geometry)
1245
+ }
1246
+ }
1247
+ }
1248
+ func patch(_ next: [[String: Any]]) throws {
1249
+ let patches: [[String: Any]] = [["key": "row-20", "type": "dataRow",
1250
+ "changes": ["columns": next]]]
1251
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patches),
1252
+ as: UTF8.self))
1253
+ }
1254
+ func widthConstraints() throws -> [NSLayoutConstraint] {
1255
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1256
+ as? NativeListDataRowCell)
1257
+ return try XCTUnwrap(Mirror(reflecting: cell).children.first {
1258
+ $0.label == "columnWidthConstraints"
1259
+ }?.value as? [NSLayoutConstraint])
1260
+ }
1261
+ func sizeConstraints() throws -> [NSLayoutConstraint] {
1262
+ let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0))
1263
+ as? NativeListDataRowCell)
1264
+ return try XCTUnwrap(Mirror(reflecting: cell).children.first {
1265
+ $0.label == "rowConstraints"
1266
+ }?.value as? [NSLayoutConstraint])
1267
+ }
1268
+ layout()
1269
+ list.setContentOffset(CGPoint(x: 0, y: 18 * 60), animated: false)
1270
+ try check("three populated", count: 3, width: 700)
1271
+ try patch(columns(middle: nil))
1272
+ try check("three empty middle", count: 3, width: 700)
1273
+ try patch(columns(middle: "0.02"))
1274
+ try check("three restored", count: 3, width: 700)
1275
+ try patch(columns(middle: nil, two: true))
1276
+ try check("two columns", count: 2, width: 700)
1277
+ try patch(columns(middle: nil))
1278
+ try check("three after two", count: 3, width: 700)
1279
+ let stableConstraints = try widthConstraints()
1280
+ let stableSizeConstraints = try sizeConstraints()
1281
+ XCTAssertEqual(stableConstraints.count, 2)
1282
+ XCTAssertEqual(stableSizeConstraints.count, 4)
1283
+ for update in 0..<10 {
1284
+ var next = columns(middle: nil)
1285
+ next[2]["text"] = "$1.\(update)"
1286
+ try patch(next)
1287
+ try check("same-shape price \(update)", count: 3, width: 700)
1288
+ let retained = try widthConstraints()
1289
+ XCTAssertEqual(retained.count, stableConstraints.count)
1290
+ XCTAssertTrue(zip(stableConstraints, retained).allSatisfy { $0 === $1 })
1291
+ XCTAssertTrue(retained.allSatisfy(\.isActive))
1292
+ let size = try sizeConstraints()
1293
+ XCTAssertEqual(size.count, stableSizeConstraints.count)
1294
+ XCTAssertTrue(zip(stableSizeConstraints, size).allSatisfy { $0 === $1 })
1295
+ XCTAssertTrue(size.allSatisfy(\.isActive))
1296
+ }
1297
+ var equivalentWeights = columns(middle: nil)
1298
+ for index in equivalentWeights.indices { equivalentWeights[index]["weight"] = 2 }
1299
+ try patch(equivalentWeights)
1300
+ try check("equivalent weights", count: 3, width: 700, weights: [2, 2, 2])
1301
+ let equivalentConstraints = try widthConstraints()
1302
+ XCTAssertEqual(equivalentConstraints.count, stableConstraints.count)
1303
+ XCTAssertTrue(zip(stableConstraints, equivalentConstraints).allSatisfy { $0 === $1 })
1304
+ var unequalWeights = columns(middle: nil)
1305
+ unequalWeights[0]["weight"] = 2
1306
+ try patch(unequalWeights)
1307
+ try check("unequal weights", count: 3, width: 700, weights: [2, 1, 1])
1308
+ let unequalConstraints = try widthConstraints()
1309
+ XCTAssertEqual(unequalConstraints.count, 2)
1310
+ XCTAssertTrue(stableConstraints.allSatisfy { !$0.isActive })
1311
+ try patch(columns(middle: nil, two: true))
1312
+ try check("two after weights", count: 2, width: 700)
1313
+ let twoConstraints = try widthConstraints()
1314
+ XCTAssertEqual(twoConstraints.count, 1)
1315
+ XCTAssertTrue(unequalConstraints.allSatisfy { !$0.isActive })
1316
+ try patch([])
1317
+ try check("zero columns", count: 0, width: 700)
1318
+ XCTAssertTrue((try widthConstraints()).isEmpty)
1319
+ XCTAssertTrue(twoConstraints.allSatisfy { !$0.isActive })
1320
+ try patch(columns(middle: nil))
1321
+ try check("three after zero", count: 3, width: 700)
1322
+ list.setContentOffset(.zero, animated: false)
1323
+ layout()
1324
+ XCTAssertFalse(list.indexPathsForVisibleItems.contains(IndexPath(item: 20, section: 0)))
1325
+ list.setContentOffset(CGPoint(x: 0, y: 18 * 60), animated: false)
1326
+ try check("after scroll reuse", count: 3, width: 700)
1327
+ window.frame.size.width = 1032
1328
+ controller.view.frame = window.bounds
1329
+ view.frame = window.bounds
1330
+ view.setSidecarLayoutJson("")
1331
+ drainMainQueue()
1332
+ try check("narrow no sidecar", count: 3, width: 1016)
1333
+ window.frame.size.width = 1376
1334
+ controller.view.frame = window.bounds
1335
+ view.frame = window.bounds
1336
+ view.setSidecarLayoutJson(sidecar)
1337
+ drainMainQueue()
1338
+ try check("wide sidecar restored", count: 3, width: 700)
1339
+ func animatedPatch(_ next: [[String: Any]], phase: String, count: Int) throws {
1340
+ let patches: [[String: Any]] = [["key": "row-20", "type": "dataRow",
1341
+ "changes": ["columns": next]]]
1342
+ let json = String(decoding: try JSONSerialization.data(withJSONObject: patches), as: UTF8.self)
1343
+ let finished = expectation(description: "Home column animation: \(phase)")
1344
+ UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState) {
1345
+ view.applyPatchesJson(json)
1346
+ view.layoutIfNeeded()
1347
+ list.layoutIfNeeded()
1348
+ } completion: { _ in finished.fulfill() }
1349
+ wait(for: [finished], timeout: 1)
1350
+ try check(phase, count: count, width: 700)
1351
+ waitForStructuralFrames(0.1)
1352
+ try check("\(phase) stable", count: count, width: 700)
1353
+ }
1354
+ try animatedPatch(columns(middle: nil, two: true), phase: "animated two", count: 2)
1355
+ try animatedPatch(columns(middle: nil), phase: "animated three", count: 3)
1356
+ try animatedPatch(columns(middle: "0.06"), phase: "animated nonempty", count: 3)
1357
+ }
1358
+
1359
+ func testStructuralShrinkUsesTheTallerFinalColumnForOffsetClamping() throws {
1360
+ let cases: [(name: String, sidecar: Int, offset: CGFloat, height: CGFloat,
1361
+ zeroInset: Bool)] = [
1362
+ ("sidecar stays taller", 2200, 1450, 2200, false),
1363
+ ("left column stays taller", 1000, 1100, 1560, false),
1364
+ ("left column zero inset", 1000, 1100, 1560, true),
1365
+ ("sidecar becomes taller", 1700, 1050, 1700, false),
1366
+ ]
1367
+ for testCase in cases {
1368
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
1369
+ let controller = UIViewController()
1370
+ window.rootViewController = controller
1371
+ let view = NativeListView(frame: window.bounds)
1372
+ controller.view.addSubview(view)
1373
+ window.isHidden = false
1374
+ defer {
1375
+ view.dispose()
1376
+ view.removeFromSuperview()
1377
+ window.isHidden = true
1378
+ window.rootViewController = nil
1379
+ }
1380
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1381
+ // Keep the viewport insets fixed while testing structural offset clamping.
1382
+ let explicitInset = testCase.zeroInset ? UIEdgeInsets.zero :
1383
+ UIEdgeInsets(top: 62, left: 0, bottom: 34, right: 0)
1384
+ list.contentInsetAdjustmentBehavior = .never
1385
+ list.contentInset = explicitInset
1386
+ view.mountContainerSlot(UIView(), atIndex: 0)
1387
+ view.mountContainerSlot(UIView(), atIndex: 1)
1388
+ let footer = UIView()
1389
+ view.mountContainerSlot(footer, atIndex: 2)
1390
+ let sidecar = UIView()
1391
+ view.mountContainerSlot(sidecar, atIndex: 3)
1392
+ view.setContainerSlotHeightsJson("[0,0,60,\(testCase.sidecar)]")
1393
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
1394
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30))
1395
+ view.layoutIfNeeded()
1396
+ list.layoutIfNeeded()
1397
+ drainMainQueue()
1398
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1399
+ XCTAssertEqual(list.contentSize.height, max(1860, CGFloat(testCase.sidecar)),
1400
+ accuracy: 1, testCase.name)
1401
+ list.contentOffset.y = testCase.offset
1402
+ list.layoutIfNeeded()
1403
+ XCTAssertEqual(list.contentOffset.y, testCase.offset, accuracy: 1, testCase.name)
1404
+
1405
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, transitionID: testCase.name))
1406
+ let completed = expectation(description: "Native structural display link: \(testCase.name)")
1407
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { completed.fulfill() }
1408
+ wait(for: [completed], timeout: 1)
1409
+ list.layoutIfNeeded()
1410
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1411
+ XCTAssertEqual(list.contentSize.height, testCase.height, accuracy: 1, testCase.name)
1412
+ let inset = list.adjustedContentInset
1413
+ let finalMaximum = max(-inset.top, testCase.height - list.bounds.height + inset.bottom)
1414
+ let footerTop: CGFloat = 1500
1415
+ let footerBottom: CGFloat = footerTop + 60
1416
+ let footerVisibleMinimum = footerBottom - list.bounds.height + inset.bottom
1417
+ let footerVisibleMaximum = footerTop - inset.top
1418
+ let expectedOffset = min(max(testCase.offset, footerVisibleMinimum),
1419
+ min(footerVisibleMaximum, finalMaximum))
1420
+ XCTAssertEqual(list.contentOffset.y, expectedOffset, accuracy: 1, testCase.name)
1421
+ XCTAssertNotNil(sidecar.superview, testCase.name)
1422
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1500, accuracy: 1, testCase.name)
1423
+ waitForStructuralFrames(0.1)
1424
+ XCTAssertEqual(list.adjustedContentInset, explicitInset, testCase.name)
1425
+ XCTAssertEqual(list.contentSize.height, testCase.height, accuracy: 1, testCase.name)
1426
+ XCTAssertEqual(list.contentOffset.y, expectedOffset, accuracy: 1, testCase.name)
1427
+ }
1428
+ }
1429
+
1430
+ func testStructuralTransitionFromGridOrHorizontalCommitsAtomically() throws {
1431
+ try requireStructuralAnimation()
1432
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 600))
1433
+ let controller = UIViewController()
1434
+ window.rootViewController = controller
1435
+ let view = NativeListView(frame: window.bounds)
1436
+ controller.view.addSubview(view)
1437
+ window.isHidden = false
1438
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1439
+ defer {
1440
+ view.dispose()
1441
+ view.removeFromSuperview()
1442
+ window.isHidden = true
1443
+ window.rootViewController = nil
1444
+ }
1445
+ view.applySnapshotJson(try structuralRowsSnapshot(
1446
+ count: 6, generation: 1, layoutKind: "grid"))
1447
+ view.layoutIfNeeded()
1448
+ view.applySnapshotJson(try structuralRowsSnapshot(
1449
+ count: 8, generation: 2, transitionID: "from-grid", layoutKind: "linear"))
1450
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1451
+ XCTAssertEqual(list.numberOfItems(inSection: 0), 8)
1452
+
1453
+ view.applySnapshotJson(try structuralRowsSnapshot(
1454
+ count: 6, generation: 3, orientation: "horizontal"))
1455
+ view.layoutIfNeeded()
1456
+ view.applySnapshotJson(try structuralRowsSnapshot(
1457
+ count: 8, generation: 4, transitionID: "from-horizontal", layoutKind: "table"))
1458
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1459
+ XCTAssertEqual(list.numberOfItems(inSection: 0), 8)
1460
+ }
1461
+
1462
+ func testVisibleNativeCellsRemainBoundedAsRowsGrowTenfold() throws {
1463
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1464
+ let controller = UIViewController()
1465
+ window.rootViewController = controller
1466
+ let view = NativeListView(frame: window.bounds)
1467
+ controller.view.addSubview(view)
1468
+ window.isHidden = false
1469
+ defer { window.isHidden = true }
1470
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1471
+ func sampleCells(count: Int) throws -> [(visible: Int, attached: Int)] {
1472
+ view.applySnapshotJson(try structuralRowsSnapshot(count: count))
1473
+ view.layoutIfNeeded()
1474
+ list.layoutIfNeeded()
1475
+ let lastOffset = CGFloat(count * 60 - 600)
1476
+ return [CGFloat(0), lastOffset / 2, lastOffset].map { offset in
1477
+ list.setContentOffset(CGPoint(x: 0, y: offset), animated: false)
1478
+ list.layoutIfNeeded()
1479
+ return (list.visibleCells.count,
1480
+ list.subviews.compactMap { $0 as? NativeListRowHost }.count)
1481
+ }
1482
+ }
1483
+ let hundredCells = try sampleCells(count: 100)
1484
+ let thousandCells = try sampleCells(count: 1000)
1485
+ print("NativeList 100 visible/attached first/mid/tail: \(hundredCells)")
1486
+ print("NativeList 1000 visible/attached first/mid/tail: \(thousandCells)")
1487
+ XCTAssertTrue(hundredCells.allSatisfy {
1488
+ $0.visible > 0 && $0.visible <= 24 && $0.attached > 0 && $0.attached <= 24
1489
+ })
1490
+ XCTAssertTrue(thousandCells.allSatisfy {
1491
+ $0.visible > 0 && $0.visible <= 24 && $0.attached > 0 && $0.attached <= 24
1492
+ })
1493
+ XCTAssertLessThanOrEqual(thousandCells.map(\.attached).max() ?? 0,
1494
+ (hundredCells.map(\.attached).max() ?? 0) + 4)
1495
+ }
1496
+
1497
+ func testStructuralTransitionRapidReversalKeepsRetiringContentAtNaturalHeight() throws {
1498
+ try requireStructuralAnimation()
1499
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1500
+ let controller = UIViewController()
1501
+ window.rootViewController = controller
1502
+ let view = NativeListView(frame: window.bounds)
1503
+ controller.view.addSubview(view)
1504
+ window.isHidden = false
1505
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
1506
+ let footer = UIView()
1507
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
1508
+ view.mountContainerSlot(footer, atIndex: 2)
1509
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
1510
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 1))
1511
+ view.layoutIfNeeded()
1512
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1513
+ list.layoutIfNeeded()
1514
+ drainMainQueue()
1515
+ list.contentOffset.y = 900
1516
+ list.layoutIfNeeded()
1517
+
1518
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 2,
1519
+ transitionID: "expand-first", durationMs: 400))
1520
+ waitForStructuralFrames(0.08)
1521
+ list.contentOffset.y = 1100
1522
+ list.layoutIfNeeded()
1523
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 3,
1524
+ transitionID: "collapse-middle", durationMs: 400))
1525
+ waitForStructuralFrames(0.08)
1526
+ list.layoutIfNeeded()
1527
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
1528
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
1529
+ let clip = try XCTUnwrap(flow.tailClip)
1530
+ let retiring = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 25, section: 0)) as? NativeListRowHost)
1531
+ XCTAssertGreaterThan(clip.endY, 1500)
1532
+ XCTAssertLessThan(clip.endY, 1800)
1533
+ XCTAssertEqual(retiring.bounds.height, 60, accuracy: 1)
1534
+ XCTAssertEqual(retiring.contentView.bounds.height, 60, accuracy: 1)
1535
+ XCTAssertNil(retiring.structuralContentHeight)
1536
+ XCTAssertEqual(retiring.alpha, 1, accuracy: 0.01)
1537
+ XCTAssertFalse(retiring.isUserInteractionEnabled)
1538
+ XCTAssertTrue(retiring.accessibilityElementsHidden)
1539
+ XCTAssertEqual(footer.convert(.zero, to: list).y,
1540
+ clip.endY, accuracy: 1)
1541
+
1542
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 4,
1543
+ transitionID: "expand-last", durationMs: 400))
1544
+ waitForStructuralFrames(0.5)
1545
+ list.layoutIfNeeded()
1546
+ let keys = source.snapshot().itemIdentifiers
1547
+ XCTAssertEqual(keys, (0..<30).map { "row-\($0)" })
1548
+ XCTAssertEqual(Set(keys).count, 30)
1549
+ XCTAssertEqual(list.contentSize.height, 1860, accuracy: 1)
1550
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1800, accuracy: 1)
1551
+ XCTAssertGreaterThanOrEqual(list.contentOffset.y, -list.adjustedContentInset.top - 1)
1552
+ XCTAssertLessThanOrEqual(list.contentOffset.y,
1553
+ list.contentSize.height - list.bounds.height + list.adjustedContentInset.bottom + 1)
1554
+ for case let cell as NativeListRowHost in list.visibleCells {
1555
+ XCTAssertEqual(cell.alpha, 1, accuracy: 0.01)
1556
+ XCTAssertNil(cell.structuralContentHeight)
1557
+ }
1558
+ }
1559
+
1560
+ func testDisclosureInitialEndpoints() throws {
1561
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1562
+ let controller = UIViewController()
1563
+ window.rootViewController = controller
1564
+ let view = NativeListView(frame: window.bounds)
1565
+ controller.view.addSubview(view)
1566
+ window.isHidden = false
1567
+ defer {
1568
+ view.dispose()
1569
+ view.removeFromSuperview()
1570
+ window.isHidden = true
1571
+ window.rootViewController = nil
1572
+ }
1573
+ let slots = (0..<6).map { _ in UIView() }
1574
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
1575
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1576
+ var settlements: [String] = []
1577
+ view.onStructuralTransitionSettled = { settlements.append($0) }
1578
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1579
+ list.contentInsetAdjustmentBehavior = .never
1580
+ list.contentInset = .zero
1581
+
1582
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1583
+ disclosureExpanded: false))
1584
+ view.layoutIfNeeded()
1585
+ list.layoutIfNeeded()
1586
+ let footerHost = try XCTUnwrap(slots[2].superview)
1587
+ let contentHost = try XCTUnwrap(slots[4].superview)
1588
+ let toggleHost = try XCTUnwrap(slots[5].superview)
1589
+ XCTAssertEqual(contentHost.frame.minY, 360, accuracy: 1)
1590
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1591
+ XCTAssertTrue(contentHost.isHidden)
1592
+ XCTAssertFalse(contentHost.isUserInteractionEnabled)
1593
+ XCTAssertTrue(contentHost.accessibilityElementsHidden)
1594
+ XCTAssertEqual(toggleHost.frame.minY, 360, accuracy: 1)
1595
+ XCTAssertEqual(footerHost.frame.minY, 400, accuracy: 1)
1596
+ XCTAssertEqual(list.contentSize.height, 540, accuracy: 1)
1597
+ XCTAssertTrue(toggleHost.point(inside: CGPoint(x: 10, y: 10), with: nil))
1598
+ XCTAssertTrue(settlements.isEmpty)
1599
+
1600
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
1601
+ disclosureExpanded: true))
1602
+ view.layoutIfNeeded()
1603
+ list.layoutIfNeeded()
1604
+ XCTAssertEqual(contentHost.frame.minY, 360, accuracy: 1)
1605
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1606
+ XCTAssertFalse(contentHost.isHidden)
1607
+ XCTAssertTrue(contentHost.isUserInteractionEnabled)
1608
+ XCTAssertFalse(contentHost.accessibilityElementsHidden)
1609
+ XCTAssertEqual(toggleHost.frame.minY, 460, accuracy: 1)
1610
+ XCTAssertEqual(footerHost.frame.minY, 520, accuracy: 1)
1611
+ XCTAssertEqual(list.contentSize.height, 660, accuracy: 1)
1612
+ XCTAssertTrue(settlements.isEmpty)
1613
+ }
1614
+
1615
+ func testDisclosureCollapseClock() throws {
1616
+ try requireStructuralAnimation()
1617
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1618
+ let controller = UIViewController()
1619
+ window.rootViewController = controller
1620
+ let view = NativeListView(frame: window.bounds)
1621
+ controller.view.addSubview(view)
1622
+ window.isHidden = false
1623
+ defer {
1624
+ view.dispose()
1625
+ view.removeFromSuperview()
1626
+ window.isHidden = true
1627
+ window.rootViewController = nil
1628
+ }
1629
+ let slots = (0..<6).map { _ in UIView() }
1630
+ let expandedChild = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 100))
1631
+ slots[4].addSubview(expandedChild)
1632
+ let toggle = UIButton(frame: CGRect(x: 0, y: 0, width: 320, height: 40))
1633
+ for index in 0..<6 {
1634
+ view.mountContainerSlot(index == 5 ? toggle : slots[index], atIndex: index)
1635
+ }
1636
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1637
+ var settlements: [[String: Any]] = []
1638
+ view.onStructuralTransitionSettled = { payload in
1639
+ guard let data = payload.data(using: .utf8),
1640
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1641
+ return
1642
+ }
1643
+ settlements.append(object)
1644
+ }
1645
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1646
+ list.contentInsetAdjustmentBehavior = .never
1647
+ list.contentInset = .zero
1648
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1,
1649
+ disclosureExpanded: true))
1650
+ view.layoutIfNeeded()
1651
+ list.layoutIfNeeded()
1652
+ drainMainQueue()
1653
+ list.contentOffset.y = 2400
1654
+ list.layoutIfNeeded()
1655
+
1656
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
1657
+ transitionID: "disclosure-collapse", durationMs: 800,
1658
+ disclosureExpanded: false))
1659
+ waitForStructuralFrames(0.16)
1660
+ list.layoutIfNeeded()
1661
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
1662
+ let clip = try XCTUnwrap(flow.tailClip)
1663
+ let contentHost = try XCTUnwrap(slots[4].superview)
1664
+ let toggleHost = try XCTUnwrap(toggle.superview)
1665
+ let footerHost = try XCTUnwrap(slots[2].superview)
1666
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1667
+ XCTAssertEqual(contentHost.frame.minY, clip.endY, accuracy: 1)
1668
+ let contentVisible = toggleHost.frame.minY - contentHost.frame.minY
1669
+ XCTAssertGreaterThan(contentVisible, 0)
1670
+ XCTAssertLessThan(contentVisible, 100)
1671
+ XCTAssertEqual(try XCTUnwrap(contentHost.layer.mask).frame.height,
1672
+ contentVisible, accuracy: 1)
1673
+ XCTAssertFalse(contentHost.isUserInteractionEnabled)
1674
+ XCTAssertTrue(contentHost.accessibilityElementsHidden)
1675
+ XCTAssertTrue(toggleHost.isUserInteractionEnabled)
1676
+ XCTAssertFalse(toggleHost.accessibilityElementsHidden)
1677
+ XCTAssertTrue(toggleHost.point(inside: CGPoint(x: 10, y: 10), with: nil))
1678
+ XCTAssertEqual(toggleHost.frame.minY, clip.endY + contentVisible, accuracy: 1)
1679
+ let inset = footerHost.frame.minY - toggleHost.frame.maxY
1680
+ XCTAssertGreaterThan(inset, 0)
1681
+ XCTAssertLessThan(inset, 20)
1682
+ XCTAssertTrue(settlements.isEmpty)
1683
+
1684
+ waitForStructuralFrames(0.75)
1685
+ list.layoutIfNeeded()
1686
+ XCTAssertNil(flow.tailClip)
1687
+ XCTAssertEqual(toggleHost.frame.minY, 360, accuracy: 1)
1688
+ XCTAssertEqual(footerHost.frame.minY, 400, accuracy: 1)
1689
+ XCTAssertTrue(contentHost.isHidden)
1690
+ XCTAssertEqual(settlements.count, 1)
1691
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "disclosure-collapse")
1692
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
1693
+ XCTAssertEqual(settlements.first?["settledExpanded"] as? Bool, false)
1694
+
1695
+ let roots = (0..<6).map { $0 == 5 ? toggle : slots[$0] }
1696
+ let hosts = roots.map(\.superview)
1697
+ XCTAssertTrue(hosts.allSatisfy { $0 != nil })
1698
+ let toggleWindowOrigin = toggleHost.convert(CGPoint.zero, to: window)
1699
+ let footerWindowOrigin = footerHost.convert(CGPoint.zero, to: window)
1700
+ let settledOffset = list.contentOffset
1701
+ let settledSize = list.contentSize
1702
+ expandedChild.removeFromSuperview()
1703
+ view.setContainerSlotHeightsJson("[0,0,140,0,0,40]")
1704
+ view.layoutIfNeeded()
1705
+ list.layoutIfNeeded()
1706
+ drainMainQueue()
1707
+ view.layoutIfNeeded()
1708
+ list.layoutIfNeeded()
1709
+ for (root, host) in zip(roots, hosts) {
1710
+ XCTAssertTrue(root.superview === host)
1711
+ XCTAssertTrue(root.window === window)
1712
+ }
1713
+ XCTAssertEqual(toggleHost.convert(CGPoint.zero, to: window).x, toggleWindowOrigin.x, accuracy: 1)
1714
+ XCTAssertEqual(toggleHost.convert(CGPoint.zero, to: window).y, toggleWindowOrigin.y, accuracy: 1)
1715
+ XCTAssertEqual(footerHost.convert(CGPoint.zero, to: window).x, footerWindowOrigin.x, accuracy: 1)
1716
+ XCTAssertEqual(footerHost.convert(CGPoint.zero, to: window).y, footerWindowOrigin.y, accuracy: 1)
1717
+ XCTAssertEqual(list.contentOffset.x, settledOffset.x, accuracy: 1)
1718
+ XCTAssertEqual(list.contentOffset.y, settledOffset.y, accuracy: 1)
1719
+ XCTAssertEqual(list.contentSize.width, settledSize.width, accuracy: 1)
1720
+ XCTAssertEqual(list.contentSize.height, settledSize.height, accuracy: 1)
1721
+ XCTAssertEqual(settlements.count, 1)
1722
+ }
1723
+
1724
+ func testDisclosureAckLatest() throws {
1725
+ try requireStructuralAnimation()
1726
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1727
+ let controller = UIViewController()
1728
+ window.rootViewController = controller
1729
+ let view = NativeListView(frame: window.bounds)
1730
+ controller.view.addSubview(view)
1731
+ window.isHidden = false
1732
+ defer {
1733
+ view.dispose()
1734
+ view.removeFromSuperview()
1735
+ window.isHidden = true
1736
+ window.rootViewController = nil
1737
+ }
1738
+ let slots = (0..<6).map { _ in UIView() }
1739
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
1740
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1741
+ var settlements: [(String, String, Bool)] = []
1742
+ view.onStructuralTransitionSettled = { payload in
1743
+ guard let data = payload.data(using: .utf8),
1744
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
1745
+ let id = object["transitionId"] as? String,
1746
+ let status = object["status"] as? String,
1747
+ let expanded = object["settledExpanded"] as? Bool else { return }
1748
+ settlements.append((id, status, expanded))
1749
+ }
1750
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1751
+ disclosureExpanded: false))
1752
+ view.layoutIfNeeded()
1753
+ drainMainQueue()
1754
+ XCTAssertTrue(settlements.isEmpty)
1755
+
1756
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
1757
+ transitionID: "same-rows", durationMs: 400, disclosureExpanded: false))
1758
+ drainMainQueue()
1759
+ XCTAssertEqual(settlements.map(\.0), ["same-rows"])
1760
+ XCTAssertEqual(settlements.first?.1, "completed")
1761
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
1762
+ transitionID: "same-rows", durationMs: 400, disclosureExpanded: false))
1763
+ drainMainQueue()
1764
+ XCTAssertEqual(settlements.count, 1)
1765
+
1766
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 4,
1767
+ transitionID: "expand-superseded", durationMs: 400,
1768
+ disclosureExpanded: true))
1769
+ waitForStructuralFrames(0.08)
1770
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 5,
1771
+ transitionID: "collapse-latest", durationMs: 400,
1772
+ disclosureExpanded: false))
1773
+ waitForStructuralFrames(0.5)
1774
+ XCTAssertEqual(settlements.map(\.0), ["same-rows", "collapse-latest"])
1775
+ XCTAssertEqual(settlements.last?.1, "completed")
1776
+ XCTAssertEqual(settlements.last?.2, false)
1777
+ XCTAssertTrue(slots[4].superview?.isHidden ?? false)
1778
+
1779
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 0, generation: 6,
1780
+ transitionID: "empty-immediate", durationMs: 0,
1781
+ disclosureExpanded: false))
1782
+ drainMainQueue()
1783
+ XCTAssertEqual(settlements.map(\.0),
1784
+ ["same-rows", "collapse-latest", "empty-immediate"])
1785
+ XCTAssertEqual(settlements.last?.1, "completed")
1786
+ }
1787
+
1788
+ func testDisclosureGeometryFallbackUsesLatestSnapshot() throws {
1789
+ try requireStructuralAnimation()
1790
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1791
+ let controller = UIViewController()
1792
+ window.rootViewController = controller
1793
+ let view = NativeListView(frame: window.bounds)
1794
+ controller.view.addSubview(view)
1795
+ window.isHidden = false
1796
+ defer {
1797
+ view.dispose()
1798
+ view.removeFromSuperview()
1799
+ window.isHidden = true
1800
+ window.rootViewController = nil
1801
+ }
1802
+ let slots = (0..<6).map { _ in UIView() }
1803
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
1804
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1805
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1806
+ list.contentInsetAdjustmentBehavior = .never
1807
+ var settlements: [(String, String)] = []
1808
+ view.onStructuralTransitionSettled = { payload in
1809
+ guard let data = payload.data(using: .utf8),
1810
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
1811
+ let id = object["transitionId"] as? String,
1812
+ let status = object["status"] as? String else { return }
1813
+ settlements.append((id, status))
1814
+ }
1815
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1816
+ disclosureExpanded: false))
1817
+ view.layoutIfNeeded()
1818
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
1819
+ transitionID: "expand", durationMs: 800, disclosureExpanded: true))
1820
+ waitForStructuralFrames(0.08)
1821
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1822
+
1823
+ view.setContainerSlotHeightsJson("[0,0,160,0,100,40]", followedBySnapshot: true)
1824
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
1825
+ transitionID: "expand", durationMs: 800, disclosureExpanded: true))
1826
+ drainMainQueue()
1827
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1828
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
1829
+ let contentHost = try XCTUnwrap(slots[4].superview)
1830
+ let toggleHost = try XCTUnwrap(slots[5].superview)
1831
+ let footerHost = try XCTUnwrap(slots[2].superview)
1832
+ XCTAssertEqual(contentHost.bounds.height, 100, accuracy: 1)
1833
+ XCTAssertEqual(toggleHost.frame.minY, 3_100, accuracy: 1)
1834
+ XCTAssertEqual(footerHost.frame.minY, 3_160, accuracy: 1)
1835
+ XCTAssertEqual(footerHost.bounds.height, 160, accuracy: 1)
1836
+ XCTAssertEqual(settlements.map(\.0), ["expand"])
1837
+ XCTAssertEqual(settlements.last?.1, "interrupted")
1838
+
1839
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 4,
1840
+ transitionID: "collapse", durationMs: 800, disclosureExpanded: false))
1841
+ waitForStructuralFrames(0.08)
1842
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 5,
1843
+ transitionID: "collapse", durationMs: 800))
1844
+ drainMainQueue()
1845
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1846
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
1847
+ XCTAssertEqual(settlements.map(\.0), ["expand"],
1848
+ "Removing disclosure without a new command cannot acknowledge the old target")
1849
+ }
1850
+
1851
+ func testDisclosureLateCompletionCannotSettleNewCommand() throws {
1852
+ try requireStructuralAnimation()
1853
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1854
+ let controller = UIViewController()
1855
+ window.rootViewController = controller
1856
+ let view = NativeListView(frame: window.bounds)
1857
+ controller.view.addSubview(view)
1858
+ window.isHidden = false
1859
+ defer {
1860
+ view.dispose()
1861
+ view.removeFromSuperview()
1862
+ window.isHidden = true
1863
+ window.rootViewController = nil
1864
+ }
1865
+ for index in 0..<6 { view.mountContainerSlot(UIView(), atIndex: index) }
1866
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1867
+ var settled: [String] = []
1868
+ view.onStructuralTransitionSettled = { payload in
1869
+ guard let data = payload.data(using: .utf8),
1870
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
1871
+ let id = object["transitionId"] as? String else { return }
1872
+ settled.append(id)
1873
+ }
1874
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1875
+ disclosureExpanded: false))
1876
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
1877
+ transitionID: "old-direct", disclosureExpanded: false))
1878
+ let oldCompletedBeforeReplacement = settled.contains("old-direct")
1879
+ XCTAssertFalse(oldCompletedBeforeReplacement,
1880
+ "The older diffable completion must remain pending when its replacement starts")
1881
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
1882
+ transitionID: "latest-expand", durationMs: 800, disclosureExpanded: true))
1883
+ drainMainQueue()
1884
+ XCTAssertNotNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1885
+ XCTAssertTrue(settled.isEmpty,
1886
+ "An older diffable completion must not settle the active newer transition")
1887
+ waitForStructuralFrames(0.9)
1888
+ XCTAssertEqual(settled, ["latest-expand"])
1889
+ }
1890
+
1891
+ func testDisclosureContentGrowthAndDragSettlement() throws {
1892
+ try requireStructuralAnimation()
1893
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
1894
+ let controller = UIViewController()
1895
+ window.rootViewController = controller
1896
+ let view = NativeListView(frame: window.bounds)
1897
+ controller.view.addSubview(view)
1898
+ window.isHidden = false
1899
+ defer {
1900
+ view.dispose()
1901
+ view.removeFromSuperview()
1902
+ window.isHidden = true
1903
+ window.rootViewController = nil
1904
+ }
1905
+ let slots = (0..<6).map { _ in UIView() }
1906
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
1907
+ view.setContainerSlotHeightsJson("[0,0,140,0,100,40]")
1908
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1909
+ list.contentInsetAdjustmentBehavior = .never
1910
+ var settlements: [(String, String)] = []
1911
+ view.onStructuralTransitionSettled = { payload in
1912
+ guard let data = payload.data(using: .utf8),
1913
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
1914
+ let id = object["transitionId"] as? String,
1915
+ let status = object["status"] as? String else { return }
1916
+ settlements.append((id, status))
1917
+ }
1918
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1,
1919
+ disclosureExpanded: false))
1920
+ view.layoutIfNeeded()
1921
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
1922
+ transitionID: "grow", durationMs: 800, disclosureExpanded: true))
1923
+ waitForStructuralFrames(0.12)
1924
+ let contentHost = try XCTUnwrap(slots[4].superview)
1925
+ let beforeHeight = try XCTUnwrap(contentHost.layer.mask).frame.height
1926
+ let clock = try XCTUnwrap(Mirror(reflecting: view).descendant("structuralDisplayLink")
1927
+ as? CADisplayLink)
1928
+ view.setContainerSlotHeightsJson("[0,0,140,0,140,40]")
1929
+ XCTAssertTrue(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink
1930
+ === clock)
1931
+ XCTAssertEqual(try XCTUnwrap(contentHost.layer.mask).frame.height,
1932
+ beforeHeight, accuracy: 1)
1933
+ waitForStructuralFrames(0.75)
1934
+ XCTAssertEqual(contentHost.bounds.height, 140, accuracy: 1)
1935
+ XCTAssertNil(contentHost.layer.mask)
1936
+ XCTAssertTrue(contentHost.isUserInteractionEnabled)
1937
+ XCTAssertEqual(settlements.map(\.0), ["grow"])
1938
+ XCTAssertEqual(settlements.last?.1, "completed")
1939
+
1940
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
1941
+ transitionID: "drag", durationMs: 800, disclosureExpanded: false))
1942
+ waitForStructuralFrames(0.08)
1943
+ view.scrollViewWillBeginDragging(list)
1944
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
1945
+ XCTAssertTrue(contentHost.isHidden)
1946
+ XCTAssertEqual(settlements.map(\.0), ["grow", "drag"])
1947
+ XCTAssertEqual(settlements.last?.1, "interrupted")
1948
+ }
1949
+
1950
+ func testDisclosureDirectCollapseKeepsToggleVisible() throws {
1951
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 600))
1952
+ let controller = UIViewController()
1953
+ window.rootViewController = controller
1954
+ let view = NativeListView(frame: window.bounds)
1955
+ controller.view.addSubview(view)
1956
+ window.isHidden = false
1957
+ defer {
1958
+ view.dispose()
1959
+ view.removeFromSuperview()
1960
+ window.isHidden = true
1961
+ window.rootViewController = nil
1962
+ }
1963
+ let slots = (0..<6).map { _ in UIView() }
1964
+ for (index, slot) in slots.enumerated() { view.mountContainerSlot(slot, atIndex: index) }
1965
+ view.setSidecarLayoutJson("{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}")
1966
+ view.setContainerSlotHeightsJson("[0,0,900,2200,100,40]")
1967
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
1968
+ list.contentInsetAdjustmentBehavior = .never
1969
+ list.contentInset = .zero
1970
+ var settlements: [[String: Any]] = []
1971
+ view.onStructuralTransitionSettled = { payload in
1972
+ guard let data = payload.data(using: .utf8),
1973
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1974
+ return
1975
+ }
1976
+ settlements.append(object)
1977
+ }
1978
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1,
1979
+ disclosureExpanded: true))
1980
+ view.layoutIfNeeded()
1981
+ list.layoutIfNeeded()
1982
+ list.contentOffset.y = 2_600
1983
+ list.layoutIfNeeded()
1984
+ XCTAssertEqual(list.contentOffset.y, 2_600, accuracy: 1)
1985
+
1986
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
1987
+ transitionID: "direct-collapse", durationMs: 0, disclosureExpanded: false))
1988
+ drainMainQueue()
1989
+ list.layoutIfNeeded()
1990
+ let toggle = try XCTUnwrap(slots[5].superview)
1991
+ XCTAssertEqual(toggle.frame.minY, 360, accuracy: 1)
1992
+ XCTAssertEqual(list.contentSize.height, 2_200, accuracy: 1)
1993
+ XCTAssertEqual(list.contentOffset.y, 360, accuracy: 1,
1994
+ "A direct collapsed endpoint must expose the stable toggle despite a taller sidecar")
1995
+ XCTAssertEqual(settlements.count, 1)
1996
+ XCTAssertEqual(settlements.first?["transitionId"] as? String, "direct-collapse")
1997
+ XCTAssertEqual(settlements.first?["status"] as? String, "completed")
1998
+
1999
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 3,
2000
+ disclosureExpanded: true))
2001
+ drainMainQueue()
2002
+ view.frame.size.height = 0
2003
+ view.layoutIfNeeded()
2004
+ XCTAssertEqual(list.bounds.height, 0)
2005
+ view.scrollToOffset(500, animated: false)
2006
+ let pending = try XCTUnwrap(Mirror(reflecting: view).descendant("pendingScrollRequest"))
2007
+ XCTAssertEqual(Mirror(reflecting: pending).children.count, 1,
2008
+ "The explicit command must still be queued when the direct collapse is accepted")
2009
+ view.frame.size.height = 600
2010
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 4,
2011
+ transitionID: "direct-collapse-after-pending-scroll", durationMs: 0,
2012
+ disclosureExpanded: false))
2013
+ drainMainQueue()
2014
+ view.layoutIfNeeded()
2015
+ list.layoutIfNeeded()
2016
+ drainMainQueue()
2017
+ XCTAssertEqual(list.contentOffset.y, 500, accuracy: 1,
2018
+ "A direct collapse must not replace an already pending explicit scroll")
2019
+ XCTAssertEqual(settlements.count, 2)
2020
+ XCTAssertEqual(settlements.last?["transitionId"] as? String,
2021
+ "direct-collapse-after-pending-scroll")
2022
+ }
2023
+
2024
+ func testStructuralTailKeepsMiddleRowsNaturalAndFooterAttachedDuringCollapse() throws {
2025
+ try requireStructuralAnimation()
2026
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2027
+ let controller = UIViewController()
2028
+ window.rootViewController = controller
2029
+ let view = NativeListView(frame: window.bounds)
2030
+ var retiredActions = 0
2031
+ view.onRowAction = { _ in retiredActions += 1 }
2032
+ controller.view.addSubview(view)
2033
+ window.isHidden = false
2034
+ defer {
2035
+ view.dispose()
2036
+ view.removeFromSuperview()
2037
+ window.isHidden = true
2038
+ window.rootViewController = nil
2039
+ }
2040
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2041
+ let footer = UIView()
2042
+ view.mountContainerSlot(footer, atIndex: 2)
2043
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2044
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2045
+ list.contentInsetAdjustmentBehavior = .never
2046
+ list.contentInset = .zero
2047
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2048
+ view.layoutIfNeeded()
2049
+ list.layoutIfNeeded()
2050
+ drainMainQueue()
2051
+ list.contentOffset.y = 2400
2052
+ list.layoutIfNeeded()
2053
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2054
+ transitionID: "tail-50-to-6", durationMs: 800))
2055
+ waitForStructuralFrames(0.16)
2056
+ list.layoutIfNeeded()
2057
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2058
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2059
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2060
+ let clip = try XCTUnwrap(flow.tailClip)
2061
+ XCTAssertEqual(clip.firstIndex, 6)
2062
+ XCTAssertGreaterThan(clip.endY, 360)
2063
+ XCTAssertLessThan(clip.endY, 3000)
2064
+ let tailCells = list.visibleCells.compactMap { cell -> NativeListRowHost? in
2065
+ guard let path = list.indexPath(for: cell), path.item >= 6 else { return nil }
2066
+ return cell as? NativeListRowHost
2067
+ }
2068
+ XCTAssertFalse(tailCells.isEmpty)
2069
+ XCTAssertTrue(tailCells.allSatisfy { abs($0.bounds.height - 60) <= 1 && $0.alpha == 1 })
2070
+ XCTAssertTrue(tailCells.allSatisfy { !$0.isUserInteractionEnabled && $0.accessibilityElementsHidden })
2071
+ XCTAssertFalse(view.collectionView(list, shouldSelectItemAt: IndexPath(item: 25, section: 0)))
2072
+ view.collectionView(list, didSelectItemAt: IndexPath(item: 25, section: 0))
2073
+ XCTAssertEqual(retiredActions, 0)
2074
+ XCTAssertEqual(footer.convert(.zero, to: list).y, clip.endY, accuracy: 1)
2075
+ let footerBottomBeforeResize = footer.convert(.zero, to: list).y + 60
2076
+ view.setContainerSlotHeightsJson("[0,0,80,0]")
2077
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 80,
2078
+ footerBottomBeforeResize, accuracy: 1)
2079
+ let footerHost = try XCTUnwrap(footer.superview)
2080
+ let hiddenTop = try XCTUnwrap(flow.tailClip).endY - footerHost.frame.minY
2081
+ if hiddenTop > 1 {
2082
+ XCTAssertFalse(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop / 2), with: nil))
2083
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop + 1), with: nil))
2084
+ }
2085
+ waitForStructuralFrames(0.06)
2086
+ list.layoutIfNeeded()
2087
+ XCTAssertEqual(footer.convert(.zero, to: list).y, try XCTUnwrap(flow.tailClip).endY,
2088
+ accuracy: 1)
2089
+ let footerBottomBeforeSecondResize = footer.convert(.zero, to: list).y + 80
2090
+ view.setContainerSlotHeightsJson("[0,0,100,0]")
2091
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 100,
2092
+ footerBottomBeforeSecondResize, accuracy: 1)
2093
+ waitForStructuralFrames(0.7)
2094
+ list.layoutIfNeeded()
2095
+ XCTAssertNil(flow.tailClip)
2096
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2097
+ XCTAssertEqual(list.contentSize.height, 460, accuracy: 1)
2098
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 360, accuracy: 1)
2099
+ XCTAssertEqual(list.contentOffset.y, 0, accuracy: 1)
2100
+ }
2101
+
2102
+ func testStructuralTailCollapsePaintsEveryExpectedViewportRow() throws {
2103
+ try requireStructuralAnimation()
2104
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, 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
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2117
+ view.mountContainerSlot(UIView(), atIndex: 2)
2118
+ view.mountContainerSlot(UIView(), atIndex: 3)
2119
+ view.setContainerSlotHeightsJson("[0,0,60,3000]")
2120
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2121
+ list.contentInsetAdjustmentBehavior = .never
2122
+ list.contentInset = .zero
2123
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2124
+ view.layoutIfNeeded()
2125
+ list.layoutIfNeeded()
2126
+ drainMainQueue()
2127
+ list.contentOffset.y = 2400
2128
+ list.layoutIfNeeded()
2129
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2130
+ var checkedFrames = 0
2131
+ var failures: [String] = []
2132
+ let probe = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in
2133
+ guard let clip = flow.tailClip else { return }
2134
+ list.layoutIfNeeded()
2135
+ let viewportTop = list.contentOffset.y
2136
+ let viewportBottom = viewportTop + list.bounds.height
2137
+ var expectedCount = 0
2138
+ var attributesCount = 0
2139
+ var attachedCount = 0
2140
+ var visibleCellsCount = 0
2141
+ var firstFailure: String?
2142
+ let attachedCells = list.subviews.compactMap { $0 as? NativeListRowHost }
2143
+ let visibleCells = list.visibleCells
2144
+ for index in 6..<50 {
2145
+ let rowTop = CGFloat(index * 60)
2146
+ let rowBottom = rowTop + 60
2147
+ let expectedTop = max(rowTop, viewportTop)
2148
+ let expectedBottom = min(rowBottom, viewportBottom, clip.endY)
2149
+ guard expectedBottom - expectedTop >= 8 else { continue }
2150
+ expectedCount += 1
2151
+ let path = IndexPath(item: index, section: 0)
2152
+ let attributes = flow.layoutAttributesForItem(at: path)
2153
+ if attributes != nil { attributesCount += 1 }
2154
+ let cell = attachedCells.first { list.indexPath(for: $0) == path }
2155
+ if cell != nil { attachedCount += 1 }
2156
+ let inVisibleCells = cell.map { visibleCells.contains($0) } ?? false
2157
+ if inVisibleCells { visibleCellsCount += 1 }
2158
+ let maskEnd = cell?.layer.mask?.frame.maxY ?? 60
2159
+ let neededMaskEnd = expectedBottom - rowTop
2160
+ if cell == nil || cell?.isHidden == true || cell?.alpha != 1
2161
+ || maskEnd + 1 < neededMaskEnd {
2162
+ if firstFailure == nil {
2163
+ let hidden = cell.map { String($0.isHidden) } ?? "nil"
2164
+ let frame = cell.map { String(describing: $0.frame) } ?? "nil"
2165
+ firstFailure = "row=\(index) offset=\(Int(viewportTop)) clip=\(Int(clip.endY)) "
2166
+ + "attached=\(cell != nil) visibleCells=\(inVisibleCells) hidden=\(hidden) "
2167
+ + "frame=\(frame) attributes=\(String(describing: attributes?.frame)) "
2168
+ + "maskEnd=\(Int(maskEnd)) alpha=\(cell?.alpha ?? -1)"
2169
+ }
2170
+ }
2171
+ }
2172
+ if expectedCount > 0 { checkedFrames += 1 }
2173
+ if let firstFailure, failures.count < 8 {
2174
+ failures.append("expected=\(expectedCount) attrs=\(attributesCount) "
2175
+ + "attached=\(attachedCount) visibleCells=\(visibleCellsCount) " + firstFailure)
2176
+ }
2177
+ }
2178
+ RunLoop.main.add(probe, forMode: .common)
2179
+ defer { probe.invalidate() }
2180
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2181
+ transitionID: "tail-viewport-paint", durationMs: 800))
2182
+ waitForStructuralFrames(0.82)
2183
+ XCTAssertGreaterThanOrEqual(checkedFrames, 5)
2184
+ XCTAssertTrue(failures.isEmpty, failures.joined(separator: "\n"))
2185
+ }
2186
+
2187
+ func testStructuralTailGeometryChangeWithSameIDCommitsFinalLayout() throws {
2188
+ try requireStructuralAnimation()
2189
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2190
+ let controller = UIViewController()
2191
+ window.rootViewController = controller
2192
+ let view = NativeListView(frame: window.bounds)
2193
+ controller.view.addSubview(view)
2194
+ window.isHidden = false
2195
+ defer {
2196
+ view.dispose()
2197
+ view.removeFromSuperview()
2198
+ window.isHidden = true
2199
+ window.rootViewController = nil
2200
+ }
2201
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2202
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2203
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2204
+ list.contentInsetAdjustmentBehavior = .never
2205
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2206
+ view.layoutIfNeeded()
2207
+ list.layoutIfNeeded()
2208
+ drainMainQueue()
2209
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2210
+ transitionID: "same-id-geometry", durationMs: 400))
2211
+ waitForStructuralFrames(0.08)
2212
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2213
+ transitionID: "same-id-geometry", durationMs: 400, firstRowHeight: 70))
2214
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2215
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2216
+ list.layoutIfNeeded()
2217
+ XCTAssertNil(flow.tailClip)
2218
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2219
+ XCTAssertEqual(list.contentSize.height, 430, accuracy: 1)
2220
+ waitForStructuralFrames(0.42)
2221
+ XCTAssertEqual(list.contentSize.height, 430, accuracy: 1)
2222
+ }
2223
+
2224
+ func testStructuralTailSameIDOrientationChangeStopsVerticalTimeline() throws {
2225
+ try requireStructuralAnimation()
2226
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2227
+ let controller = UIViewController()
2228
+ window.rootViewController = controller
2229
+ let view = NativeListView(frame: window.bounds)
2230
+ controller.view.addSubview(view)
2231
+ window.isHidden = false
2232
+ defer {
2233
+ view.dispose()
2234
+ view.removeFromSuperview()
2235
+ window.isHidden = true
2236
+ window.rootViewController = nil
2237
+ }
2238
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 1))
2239
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2240
+ view.layoutIfNeeded()
2241
+ list.layoutIfNeeded()
2242
+ drainMainQueue()
2243
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2244
+ transitionID: "same-id-orientation", durationMs: 400))
2245
+ waitForStructuralFrames(0.08)
2246
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 3,
2247
+ transitionID: "same-id-orientation", durationMs: 400, orientation: "horizontal"))
2248
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2249
+ XCTAssertNil(flow.tailClip)
2250
+ XCTAssertEqual(flow.scrollDirection, .horizontal)
2251
+ waitForStructuralFrames(0.42)
2252
+ XCTAssertEqual(flow.scrollDirection, .horizontal)
2253
+ XCTAssertNil(flow.tailClip)
2254
+ }
2255
+
2256
+ func testStructuralTailHostLimitFallsBackToAtomicSnapshot() throws {
2257
+ try requireStructuralAnimation()
2258
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2259
+ let controller = UIViewController()
2260
+ window.rootViewController = controller
2261
+ let view = NativeListView(frame: window.bounds)
2262
+ controller.view.addSubview(view)
2263
+ window.isHidden = false
2264
+ defer {
2265
+ view.dispose()
2266
+ view.removeFromSuperview()
2267
+ window.isHidden = true
2268
+ window.rootViewController = nil
2269
+ }
2270
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2271
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2272
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2273
+ list.contentInsetAdjustmentBehavior = .never
2274
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 1000, generation: 1,
2275
+ uniformHeight: 1))
2276
+ view.layoutIfNeeded()
2277
+ list.layoutIfNeeded()
2278
+ drainMainQueue()
2279
+ var phases: [Int] = []
2280
+ let observer = NotificationCenter.default.addObserver(
2281
+ forName: Notification.Name("OneKeyNativeListScrollCommandAccepted"),
2282
+ object: list, queue: nil
2283
+ ) { notification in
2284
+ if let phase = notification.userInfo?["phase"] as? Int { phases.append(phase) }
2285
+ }
2286
+ defer { NotificationCenter.default.removeObserver(observer) }
2287
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 2,
2288
+ transitionID: "tail-host-limit", durationMs: 400, uniformHeight: 1))
2289
+ list.layoutIfNeeded()
2290
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2291
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2292
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<6).map { "row-\($0)" })
2293
+ XCTAssertNil(flow.tailClip)
2294
+ XCTAssertTrue(phases.isEmpty)
2295
+ }
2296
+
2297
+ func testStructuralTailExpansionKeepsOffsetWithTallerInitialSidecar() throws {
2298
+ try requireStructuralAnimation()
2299
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2300
+ let controller = UIViewController()
2301
+ window.rootViewController = controller
2302
+ let view = NativeListView(frame: window.bounds)
2303
+ controller.view.addSubview(view)
2304
+ window.isHidden = false
2305
+ defer {
2306
+ view.dispose()
2307
+ view.removeFromSuperview()
2308
+ window.isHidden = true
2309
+ window.rootViewController = nil
2310
+ }
2311
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
2312
+ view.setContainerSlotHeightsJson("[0,0,60,2200]")
2313
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2314
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2315
+ list.contentInsetAdjustmentBehavior = .never
2316
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2317
+ view.layoutIfNeeded()
2318
+ list.layoutIfNeeded()
2319
+ drainMainQueue()
2320
+ XCTAssertEqual(list.contentSize.height, 2200, accuracy: 1)
2321
+ list.contentOffset.y = 1000
2322
+ list.layoutIfNeeded()
2323
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2324
+ transitionID: "tail-6-to-50", durationMs: 400))
2325
+ waitForStructuralFrames(0.16)
2326
+ list.layoutIfNeeded()
2327
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2328
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2329
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2330
+ XCTAssertGreaterThan(try XCTUnwrap(flow.tailClip).endY, 360)
2331
+ XCTAssertLessThan(try XCTUnwrap(flow.tailClip).endY, 3000)
2332
+ let suffixCells = list.visibleCells.filter {
2333
+ (list.indexPath(for: $0)?.item ?? -1) >= 6
2334
+ }
2335
+ XCTAssertFalse(suffixCells.isEmpty)
2336
+ XCTAssertTrue(suffixCells.allSatisfy {
2337
+ !$0.isUserInteractionEnabled && $0.accessibilityElementsHidden
2338
+ })
2339
+ XCTAssertEqual(list.contentOffset.y, 1000, accuracy: 1)
2340
+ waitForStructuralFrames(0.3)
2341
+ list.layoutIfNeeded()
2342
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2343
+ XCTAssertEqual(list.contentSize.height, 3060, accuracy: 1)
2344
+ XCTAssertEqual(list.contentOffset.y, 1000, accuracy: 1)
2345
+ XCTAssertNil(flow.tailClip)
2346
+ }
2347
+
2348
+ func testStructuralTailDifferentPrefixDuringExpansionCommitsAtomicSnapshot() throws {
2349
+ try requireStructuralAnimation()
2350
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2351
+ let controller = UIViewController()
2352
+ window.rootViewController = controller
2353
+ let view = NativeListView(frame: window.bounds)
2354
+ controller.view.addSubview(view)
2355
+ window.isHidden = false
2356
+ defer {
2357
+ view.dispose()
2358
+ view.removeFromSuperview()
2359
+ window.isHidden = true
2360
+ window.rootViewController = nil
2361
+ }
2362
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
2363
+ view.setContainerSlotHeightsJson("[0,0,60,1600]")
2364
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2365
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2366
+ list.contentInsetAdjustmentBehavior = .never
2367
+ list.contentInset = .zero
2368
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2369
+ view.layoutIfNeeded()
2370
+ list.layoutIfNeeded()
2371
+ drainMainQueue()
2372
+ XCTAssertEqual(list.adjustedContentInset.top, 0, accuracy: 0.01)
2373
+ XCTAssertEqual(list.adjustedContentInset.bottom, 0, accuracy: 0.01)
2374
+ list.contentOffset.y = 900
2375
+ list.layoutIfNeeded()
2376
+
2377
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2378
+ transitionID: "tail-first-six", durationMs: 1200))
2379
+ waitForStructuralFrames(0.12)
2380
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2381
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2382
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2383
+ XCTAssertGreaterThan(try XCTUnwrap(flow.tailClip).endY, 360)
2384
+
2385
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 10, generation: 3,
2386
+ transitionID: "tail-next-ten", durationMs: 1200))
2387
+ list.layoutIfNeeded()
2388
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<10).map { "row-\($0)" })
2389
+ XCTAssertNil(flow.tailClip)
2390
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2391
+ XCTAssertEqual(Mirror(reflecting: view).descendant("structuralSpacerHeight") as? CGFloat ?? -1,
2392
+ 0, accuracy: 1)
2393
+ XCTAssertEqual(list.contentSize.height, 1600, accuracy: 1)
2394
+ XCTAssertEqual(list.contentOffset.y, 900, accuracy: 1)
2395
+ waitForStructuralFrames(1.25)
2396
+ list.layoutIfNeeded()
2397
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<10).map { "row-\($0)" })
2398
+ XCTAssertEqual(list.contentSize.height, 1600, accuracy: 1)
2399
+ XCTAssertEqual(list.contentOffset.y, 900, accuracy: 1)
2400
+ }
2401
+
2402
+ func testStructuralTailInterruptedExpansionRestoresBoundaryCellInteraction() throws {
2403
+ try requireStructuralAnimation()
2404
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 600))
2405
+ let controller = UIViewController()
2406
+ window.rootViewController = controller
2407
+ let view = NativeListView(frame: window.bounds)
2408
+ controller.view.addSubview(view)
2409
+ window.isHidden = false
2410
+ defer {
2411
+ view.dispose()
2412
+ view.removeFromSuperview()
2413
+ window.isHidden = true
2414
+ window.rootViewController = nil
2415
+ }
2416
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2417
+ let footer = UIView()
2418
+ view.mountContainerSlot(footer, atIndex: 2)
2419
+ view.mountContainerSlot(UIView(), atIndex: 3)
2420
+ view.setContainerSlotHeightsJson("[0,0,60,2200]")
2421
+ view.setSidecarLayoutJson("{\"width\":300,\"gap\":24,\"maxContentWidth\":1000}")
2422
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2423
+ list.contentInsetAdjustmentBehavior = .never
2424
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2425
+ view.layoutIfNeeded()
2426
+ list.layoutIfNeeded()
2427
+ drainMainQueue()
2428
+ list.contentOffset.y = 300
2429
+ list.layoutIfNeeded()
2430
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2431
+ transitionID: "interrupt-boundary", durationMs: 1200))
2432
+ let footerBottomBeforeResize = footer.convert(.zero, to: list).y + 60
2433
+ view.setContainerSlotHeightsJson("[0,0,80,2200]")
2434
+ XCTAssertEqual(footer.convert(.zero, to: list).y + 80,
2435
+ footerBottomBeforeResize, accuracy: 1)
2436
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2437
+ let prefixBottom = try XCTUnwrap(flow.layoutAttributesForItem(
2438
+ at: IndexPath(item: 5, section: 0))).frame.maxY
2439
+ let footerHost = try XCTUnwrap(footer.superview)
2440
+ let hiddenTop = prefixBottom - footerHost.frame.minY
2441
+ XCTAssertGreaterThan(hiddenTop, 0)
2442
+ XCTAssertFalse(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop / 2), with: nil))
2443
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: hiddenTop + 1), with: nil))
2444
+ var boundaryCell: NativeListRowHost?
2445
+ let deadline = Date().addingTimeInterval(1)
2446
+ while boundaryCell == nil && Date() < deadline {
2447
+ if let clip = flow.tailClip {
2448
+ for case let cell as NativeListRowHost in list.visibleCells {
2449
+ guard let path = list.indexPath(for: cell), path.item >= 6,
2450
+ let mask = cell.layer.mask else { continue }
2451
+ let visibleHeight = clip.endY - cell.frame.minY
2452
+ if clip.endY > cell.frame.minY + 2 &&
2453
+ clip.endY < cell.frame.maxY - 2 &&
2454
+ mask.frame.height > 2 &&
2455
+ mask.frame.height < cell.bounds.height - 2 &&
2456
+ abs(mask.frame.height - visibleHeight) <= 1 {
2457
+ boundaryCell = cell
2458
+ break
2459
+ }
2460
+ }
2461
+ }
2462
+ if boundaryCell == nil { RunLoop.main.run(until: Date().addingTimeInterval(0.01)) }
2463
+ }
2464
+ let boundary = try XCTUnwrap(boundaryCell)
2465
+ let displayLink = try XCTUnwrap(
2466
+ Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2467
+ displayLink.isPaused = true
2468
+ defer { displayLink.isPaused = false }
2469
+ let mask = try XCTUnwrap(boundary.layer.mask)
2470
+ XCTAssertGreaterThan(mask.frame.height, 2)
2471
+ XCTAssertLessThan(mask.frame.height, boundary.bounds.height - 2)
2472
+ XCTAssertFalse(boundary.isUserInteractionEnabled)
2473
+ XCTAssertTrue(boundary.accessibilityElementsHidden)
2474
+ let offsetBeforeInterruption = list.contentOffset.y
2475
+ view.scrollViewWillBeginDragging(list)
2476
+ list.layoutIfNeeded()
2477
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2478
+ XCTAssertNil(boundary.layer.mask)
2479
+ XCTAssertFalse(boundary.isHidden)
2480
+ XCTAssertTrue(boundary.isUserInteractionEnabled)
2481
+ XCTAssertFalse(boundary.accessibilityElementsHidden)
2482
+ XCTAssertTrue(footerHost.point(inside: CGPoint(x: 10, y: 1), with: nil))
2483
+ XCTAssertEqual(list.contentOffset.y, offsetBeforeInterruption, accuracy: 1)
2484
+ XCTAssertEqual(list.contentOffset.y, 300, accuracy: 1)
2485
+ }
2486
+
2487
+ func testStructuralTailExplicitScrollTakesOwnershipFromExpansion() throws {
2488
+ try requireStructuralAnimation()
2489
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2490
+ let controller = UIViewController()
2491
+ window.rootViewController = controller
2492
+ let view = NativeListView(frame: window.bounds)
2493
+ controller.view.addSubview(view)
2494
+ window.isHidden = false
2495
+ defer {
2496
+ view.dispose()
2497
+ view.removeFromSuperview()
2498
+ window.isHidden = true
2499
+ window.rootViewController = nil
2500
+ }
2501
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2502
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2503
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2504
+ list.contentInsetAdjustmentBehavior = .never
2505
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 6, generation: 1))
2506
+ view.layoutIfNeeded()
2507
+ list.layoutIfNeeded()
2508
+ drainMainQueue()
2509
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 50, generation: 2,
2510
+ transitionID: "explicit-scroll-over-expansion", durationMs: 400))
2511
+ waitForStructuralFrames(0.08)
2512
+ view.scrollToIndex(40, animated: false, alignment: "start")
2513
+ drainMainQueue()
2514
+ list.layoutIfNeeded()
2515
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2516
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<50).map { "row-\($0)" })
2517
+ XCTAssertEqual(list.contentOffset.y, 2400, accuracy: 1)
2518
+ waitForStructuralFrames(0.4)
2519
+ XCTAssertEqual(list.contentOffset.y, 2400, accuracy: 1)
2520
+ XCTAssertTrue(list.visibleCells.allSatisfy {
2521
+ $0.isUserInteractionEnabled && !$0.accessibilityElementsHidden && $0.layer.mask == nil
2522
+ })
2523
+ }
2524
+
2525
+ func testStructuralTransitionSurvivesVisibleDataRowPatch() throws {
2526
+ try requireStructuralAnimation()
2527
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2528
+ let controller = UIViewController()
2529
+ window.rootViewController = controller
2530
+ let view = NativeListView(frame: window.bounds)
2531
+ controller.view.addSubview(view)
2532
+ window.isHidden = false
2533
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
2534
+ let footer = UIView()
2535
+ for index in 0..<2 { view.mountContainerSlot(UIView(), atIndex: index) }
2536
+ view.mountContainerSlot(footer, atIndex: 2)
2537
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2538
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1, dataRows: true))
2539
+ view.layoutIfNeeded()
2540
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2541
+ list.layoutIfNeeded()
2542
+ drainMainQueue()
2543
+ list.contentOffset.y = 1100
2544
+ list.layoutIfNeeded()
2545
+
2546
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
2547
+ transitionID: "collapse-with-patch", durationMs: 800, dataRows: true))
2548
+ waitForStructuralFrames(0.3)
2549
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2550
+ let flow = try XCTUnwrap(list.collectionViewLayout as? NativeListFlowLayout)
2551
+ let heightBeforePatch = try XCTUnwrap(flow.tailClip).endY
2552
+ XCTAssertGreaterThan(heightBeforePatch, 1500)
2553
+ let retiring = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 25, section: 0)) as? NativeListRowHost)
2554
+ XCTAssertEqual(retiring.bounds.height, 60, accuracy: 1)
2555
+ let patch: [[String: Any]] = [[
2556
+ "key": "row-20", "type": "dataRow", "changes": [
2557
+ "revision": 2,
2558
+ "columns": [["key": "asset", "text": "Asset"],
2559
+ ["key": "price", "text": "$123.45"]],
2560
+ ],
2561
+ ]]
2562
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patch),
2563
+ as: UTF8.self))
2564
+ list.layoutIfNeeded()
2565
+ let patched = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0)))
2566
+ XCTAssertTrue(labels(in: patched).contains { $0.text == "$123.45" })
2567
+ waitForStructuralFrames(0.05)
2568
+ list.layoutIfNeeded()
2569
+ XCTAssertLessThan(try XCTUnwrap(flow.tailClip).endY, heightBeforePatch)
2570
+ waitForStructuralFrames(0.55)
2571
+ list.layoutIfNeeded()
2572
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<25).map { "row-\($0)" })
2573
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
2574
+ XCTAssertEqual(footer.convert(.zero, to: list).y, 1500, accuracy: 1)
2575
+ let finalPatched = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 20, section: 0)))
2576
+ XCTAssertTrue(labels(in: finalPatched).contains { $0.text == "$123.45" })
2577
+ }
2578
+
2579
+ func testStructuralTransitionDoesNotOverrideUserDrag() throws {
2580
+ try requireStructuralAnimation()
2581
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2582
+ let controller = UIViewController()
2583
+ window.rootViewController = controller
2584
+ let view = NativeListView(frame: window.bounds)
2585
+ controller.view.addSubview(view)
2586
+ window.isHidden = false
2587
+ defer { view.dispose(); view.removeFromSuperview(); window.isHidden = true }
2588
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2589
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2590
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1))
2591
+ view.layoutIfNeeded()
2592
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2593
+ list.layoutIfNeeded()
2594
+ drainMainQueue()
2595
+ list.contentOffset.y = 1100
2596
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
2597
+ transitionID: "collapse-drag", durationMs: 400))
2598
+ waitForStructuralFrames(0.08)
2599
+ view.scrollViewWillBeginDragging(list)
2600
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2601
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
2602
+ list.contentOffset.y = 600
2603
+ list.layoutIfNeeded()
2604
+ waitForStructuralFrames(0.15)
2605
+ XCTAssertEqual(list.contentOffset.y, 600, accuracy: 1)
2606
+ waitForStructuralFrames(0.35)
2607
+ list.layoutIfNeeded()
2608
+ XCTAssertEqual(list.contentOffset.y, 600, accuracy: 1)
2609
+ let source = try XCTUnwrap(list.dataSource as? UICollectionViewDiffableDataSource<Int, String>)
2610
+ XCTAssertEqual(source.snapshot().itemIdentifiers, (0..<25).map { "row-\($0)" })
2611
+ XCTAssertEqual(list.contentSize.height, 1560, accuracy: 1)
2612
+ XCTAssertTrue(list.visibleCells.allSatisfy { abs($0.alpha - 1) < 0.01 })
2613
+ }
2614
+
2615
+ func testStructuralTransitionDetachAndDisposeReleaseView() throws {
2616
+ try requireStructuralAnimation()
2617
+ for dispose in [false, true] {
2618
+ var callbacks = 0
2619
+ let reference = try detachStructuralTransition(dispose: dispose) { callbacks += 1 }
2620
+ if dispose {
2621
+ drainMainQueue()
2622
+ XCTAssertNil(reference.view)
2623
+ let countAtDispose = callbacks
2624
+ waitForStructuralFrames(0.5)
2625
+ XCTAssertEqual(callbacks, countAtDispose)
2626
+ } else {
2627
+ waitForStructuralFrames(0.5)
2628
+ XCTAssertNil(reference.view)
2629
+ }
2630
+ }
2631
+ }
2632
+
2633
+ private final class WeakListReference {
2634
+ weak var view: NativeListView?
2635
+ }
2636
+
2637
+ private func detachStructuralTransition(
2638
+ dispose: Bool, onCallback: @escaping () -> Void
2639
+ ) throws -> WeakListReference {
2640
+ try autoreleasepool {
2641
+ let reference = WeakListReference()
2642
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
2643
+ let controller = UIViewController()
2644
+ window.rootViewController = controller
2645
+ let view = NativeListView(frame: window.bounds)
2646
+ controller.view.addSubview(view)
2647
+ window.isHidden = false
2648
+ for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
2649
+ view.setContainerSlotHeightsJson("[0,0,60,0]")
2650
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 30, generation: 1))
2651
+ view.layoutIfNeeded()
2652
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2653
+ view.onVisibleRangeChanged = { _ in onCallback() }
2654
+ view.onEndReached = { _ in onCallback() }
2655
+ list.layoutIfNeeded()
2656
+ drainMainQueue()
2657
+ view.applySnapshotJson(try structuralRowsSnapshot(count: 25, generation: 2,
2658
+ transitionID: dispose ? "dispose-mid-transition" : "detach-mid-transition",
2659
+ durationMs: 400))
2660
+ waitForStructuralFrames(0.08)
2661
+ reference.view = view
2662
+ if dispose {
2663
+ view.dispose()
2664
+ XCTAssertNil(list.delegate)
2665
+ XCTAssertNil(list.dataSource)
2666
+ }
2667
+ view.removeFromSuperview()
2668
+ XCTAssertNil(Mirror(reflecting: view).descendant("structuralDisplayLink") as? CADisplayLink)
2669
+ XCTAssertNil((list.collectionViewLayout as? NativeListFlowLayout)?.tailClip)
2670
+ window.isHidden = true
2671
+ window.rootViewController = nil
2672
+ return reference
2673
+ }
2674
+ }
2675
+
2676
+ private func dispatchAccessoryTouchUpInside(
2677
+ _ control: UIButton, on stack: NativeListAccessoryStack,
2678
+ file: StaticString = #filePath, line: UInt = #line
2679
+ ) throws {
2680
+ guard control.allTargets.contains(stack) else {
2681
+ XCTFail("Accessory control is not attached to its stack", file: file, line: line)
2682
+ return
2683
+ }
2684
+ let actions = try XCTUnwrap(
2685
+ control.actions(forTarget: stack, forControlEvent: .touchUpInside),
2686
+ file: file, line: line)
2687
+ guard !actions.isEmpty else {
2688
+ XCTFail("Accessory control has no touch-up action", file: file, line: line)
2689
+ return
2690
+ }
2691
+ // This pod XCTest has no UIApplication to dispatch UIControl.sendActions.
2692
+ guard control.isEnabled else { return }
2693
+ for action in actions {
2694
+ let selector = NSSelectorFromString(action)
2695
+ guard stack.responds(to: selector) else {
2696
+ XCTFail("Accessory action selector is missing: \(action)", file: file, line: line)
2697
+ continue
2698
+ }
2699
+ if action.hasSuffix(":") { _ = stack.perform(selector, with: control) }
2700
+ else { _ = stack.perform(selector) }
2701
+ }
2702
+ }
2703
+
2704
+ private func requireStructuralAnimation() throws {
2705
+ if UIAccessibility.isReduceMotionEnabled {
2706
+ throw XCTSkip("Structural animation is disabled by Reduce Motion")
2707
+ }
2708
+ }
2709
+
2710
+ private func waitForStructuralFrames(_ seconds: TimeInterval) {
2711
+ let completed = expectation(description: "Native structural display link ran for \(seconds)s")
2712
+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { completed.fulfill() }
2713
+ wait(for: [completed], timeout: seconds + 1)
2714
+ }
2715
+
2716
+ private func labels(in view: UIView) -> [UILabel] {
2717
+ let current = (view as? UILabel).map { [$0] } ?? []
2718
+ return current + view.subviews.flatMap(labels(in:))
2719
+ }
2720
+
2721
+ private func structuralRowsSnapshot(
2722
+ count: Int, generation: Int? = nil, transitionID: String? = nil,
2723
+ durationMs: Int = 80, dataRows: Bool = false, firstRowHeight: Int? = nil,
2724
+ uniformHeight: Int = 60, orientation: String = "vertical", layoutKind: String = "linear",
2725
+ disclosureExpanded: Bool? = nil, disclosureInset: Int = 20
2726
+ ) throws -> String {
2727
+ let rows: [[String: Any]] = (0..<count).map {
2728
+ let height = $0 == 0 ? firstRowHeight ?? uniformHeight : uniformHeight
2729
+ if dataRows {
2730
+ return ["key": "row-\($0)", "type": "dataRow", "height": height,
2731
+ "columns": [["key": "asset", "text": "Asset"],
2732
+ ["key": "price", "text": "$1.00"]]]
2733
+ }
2734
+ return ["key": "row-\($0)", "type": "action", "title": "Row", "height": height]
2735
+ }
2736
+ var layout: [String: Any] = ["kind": layoutKind, "orientation": orientation]
2737
+ if layoutKind == "grid" { layout["gridColumns"] = 2 }
2738
+ var value: [String: Any] = [
2739
+ "schemaVersion": 1, "generation": generation ?? count + 1,
2740
+ "layout": layout, "rows": rows,
2741
+ ]
2742
+ if let transitionID {
2743
+ value["structuralTransition"] = [
2744
+ "id": transitionID, "durationMs": durationMs, "anchorKey": "row-24",
2745
+ ]
2746
+ }
2747
+ if let disclosureExpanded {
2748
+ value["disclosure"] = ["expanded": disclosureExpanded,
2749
+ "expandedTrailingInset": disclosureInset]
2750
+ }
2751
+ return String(decoding: try JSONSerialization.data(withJSONObject: value), as: UTF8.self)
2752
+ }
2753
+
2754
+ private func assertHomeSidecarGeometry(sidecarBeforeFirstLayout: Bool) throws {
2755
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1376, height: 900))
2756
+ let controller = UIViewController()
2757
+ window.rootViewController = controller
2758
+ let view = NativeListView(frame: window.bounds)
2759
+ controller.view.addSubview(view)
2760
+ window.isHidden = false
2761
+ defer {
2762
+ view.dispose()
2763
+ view.removeFromSuperview()
2764
+ window.isHidden = true
2765
+ window.rootViewController = nil
2766
+ }
2767
+ for index in 0..<4 { view.mountContainerSlot(UIView(), atIndex: index) }
2768
+ view.setContainerSlotHeightsJson("[0,0,0,1200]")
2769
+ let sidecar = "{\"width\":400,\"gap\":24,\"maxContentWidth\":1140}"
2770
+ if sidecarBeforeFirstLayout { view.setSidecarLayoutJson(sidecar) }
2771
+ view.applySnapshotJson(try homeSidecarSnapshot())
2772
+ let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)
2773
+ list.contentInsetAdjustmentBehavior = .never
2774
+ func layout() {
2775
+ window.layoutIfNeeded()
2776
+ view.layoutIfNeeded()
2777
+ list.layoutIfNeeded()
2778
+ }
2779
+ func assertRows(x: CGFloat, width: CGFloat) {
2780
+ let cells = list.visibleCells.compactMap { $0 as? NativeListDataRowCell }
2781
+ XCTAssertFalse(cells.isEmpty)
2782
+ for cell in cells {
2783
+ let frame = cell.convert(cell.bounds, to: list)
2784
+ XCTAssertEqual(frame.minX, x, accuracy: 1)
2785
+ XCTAssertEqual(frame.width, width, accuracy: 1)
2786
+ if let path = list.indexPath(for: cell),
2787
+ let attributes = list.layoutAttributesForItem(at: path)
2788
+ {
2789
+ XCTAssertEqual(attributes.frame.minX, x, accuracy: 1)
2790
+ XCTAssertEqual(attributes.frame.width, width, accuracy: 1)
2791
+ }
2792
+ let root = cell.root.convert(cell.root.bounds, to: list)
2793
+ XCTAssertGreaterThanOrEqual(root.minX, frame.minX - 1)
2794
+ XCTAssertLessThanOrEqual(root.maxX, frame.maxX + 1)
2795
+ }
2796
+ }
2797
+ layout()
2798
+ if !sidecarBeforeFirstLayout {
2799
+ assertRows(x: 8, width: 1360)
2800
+ view.setSidecarLayoutJson(sidecar)
2801
+ layout()
2802
+ }
2803
+ assertRows(x: 126, width: 700)
2804
+ list.contentOffset.y = 18 * 60
2805
+ layout()
2806
+ assertRows(x: 126, width: 700)
2807
+ let patch: [[String: Any]] = [[
2808
+ "key": "row-20", "type": "dataRow",
2809
+ "changes": ["columns": homeSidecarColumns(20, updated: true),
2810
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]]],
2811
+ ]]
2812
+ view.applyPatchesJson(String(decoding: try JSONSerialization.data(withJSONObject: patch),
2813
+ as: UTF8.self))
2814
+ layout()
2815
+ assertRows(x: 126, width: 700)
2816
+ window.frame.size.width = 1024
2817
+ controller.view.frame = window.bounds
2818
+ view.frame = window.bounds
2819
+ layout()
2820
+ assertRows(x: 8, width: 584)
2821
+ window.frame.size.width = 1376
2822
+ controller.view.frame = window.bounds
2823
+ view.frame = window.bounds
2824
+ layout()
2825
+ assertRows(x: 126, width: 700)
2826
+ view.setSidecarLayoutJson("")
2827
+ layout()
2828
+ assertRows(x: 8, width: 1360)
2829
+ }
2830
+
2831
+ private func homeSidecarSnapshot() throws -> String {
2832
+ let rows: [[String: Any]] = (0..<30).map { index in
2833
+ ["key": "row-\(index)", "type": "dataRow", "height": 60,
2834
+ "leading": ["kind": "token", "fallbackIcon": ["name": "CryptoCoinOutline"]],
2835
+ "columns": homeSidecarColumns(index, updated: false),
2836
+ "trailing": [["kind": "button", "label": "Swap", "actionKey": "swap"]],
2837
+ "style": ["horizontalPadding": 12, "verticalPadding": 8, "leadingGap": 12,
2838
+ "image": ["width": 32, "height": 32]]]
2839
+ }
2840
+ let snapshot: [String: Any] = [
2841
+ "schemaVersion": 1, "generation": 1,
2842
+ "layout": ["kind": "linear", "contentPaddingHorizontal": 8], "rows": rows,
2843
+ ]
2844
+ return String(decoding: try JSONSerialization.data(withJSONObject: snapshot), as: UTF8.self)
2845
+ }
2846
+
2847
+ private func homeSidecarColumns(_ index: Int, updated: Bool) -> [[String: Any]] {
2848
+ [
2849
+ ["key": "asset", "text": "Asset \(index)", "secondaryText": "Public fixture", "weight": 1],
2850
+ ["key": "balance", "text": updated ? "0.2966" : "0.000175",
2851
+ "secondaryText": "$0.13", "alignment": "end", "weight": 1],
2852
+ ["key": "price", "text": updated ? "$739.22" : "$0.9989",
2853
+ "secondaryText": "-0.04%", "alignment": "end", "weight": 1],
2854
+ ]
2855
+ }
2856
+
366
2857
  private func makeScrollingList() throws -> NativeListView {
367
2858
  let view = NativeListView(frame: CGRect(x: 0, y: 0, width: 320, height: 708))
368
2859
  for index in 0..<3 { view.mountContainerSlot(UIView(), atIndex: index) }
369
- view.setContainerSlotHeightsJson("[44,44,44]")
2860
+ view.setContainerSlotHeightsJson("[44,44,44,0]")
370
2861
  view.applySnapshotJson(try scrollingSnapshot(count: 40))
371
2862
  view.layoutIfNeeded()
372
2863
  let list = try XCTUnwrap(view.subviews.compactMap { $0 as? UICollectionView }.first)