@onekeyfe/react-native-native-list 6.7.0-alpha.475 → 6.8.0-10

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 (54) hide show
  1. package/README.md +312 -379
  2. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +15 -6
  3. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +3 -87
  4. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPlaceholderView.kt +244 -0
  5. package/android/src/main/java/com/onekey/nativelist/NativeListMediaTileRenderer.kt +32 -11
  6. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +60 -0
  7. package/android/src/main/java/com/onekey/nativelist/NativeListPrimitives.kt +3 -6
  8. package/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +5 -1
  9. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +75 -0
  10. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +25 -19
  11. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt +153 -0
  12. package/docs/ROW_TEMPLATES.md +12 -12
  13. package/docs/SPEC.md +226 -110
  14. package/docs/STYLE_SPEC.md +7 -0
  15. package/ios/NativeListActivityDetailsView.swift +13 -5
  16. package/ios/NativeListIdentityRenderer.swift +6 -94
  17. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  18. package/ios/NativeListMediaTileRenderer.swift +13 -13
  19. package/ios/NativeListResolvedText.swift +15 -4
  20. package/ios/NativeListTextLabel.swift +106 -0
  21. package/ios/RNCNativeListView.swift +129 -32
  22. package/ios/tests/NativeListActivityPresentationTests.swift +270 -0
  23. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +0 -95
  24. package/ios/tests/NativeListLifecycleTests.swift +369 -40
  25. package/ios/tests/NativeListMediaVisibilityTests.swift +16 -7
  26. package/lib/module/NativeList.js +17 -4
  27. package/lib/module/NativeList.web.js +3 -1
  28. package/lib/module/models.js +0 -2
  29. package/lib/module/validation.js +54 -71
  30. package/lib/module/web/NativeListGeneratedIcons.js +1 -0
  31. package/lib/module/web/NativeListWebEngine.js +13 -11
  32. package/lib/module/web/templates/ActivityRowRenderer.js +29 -23
  33. package/lib/module/web/templates/DataRowRenderer.js +54 -1
  34. package/lib/module/web/templates/IdentityRowRenderer.js +3 -92
  35. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -15
  36. package/lib/typescript/src/models.d.ts +19 -22
  37. package/package.json +1 -1
  38. package/scripts/generate-icons.test.mjs +1 -0
  39. package/scripts/native-list-icons.json +1 -1
  40. package/src/NativeList.tsx +25 -4
  41. package/src/NativeList.web.tsx +1 -1
  42. package/src/models.ts +18 -23
  43. package/src/validation.ts +89 -113
  44. package/src/web/NativeListGeneratedIcons.ts +1 -0
  45. package/src/web/NativeListWebEngine.ts +16 -11
  46. package/src/web/templates/ActivityRowRenderer.ts +42 -32
  47. package/src/web/templates/DataRowRenderer.ts +76 -1
  48. package/src/web/templates/IdentityRowRenderer.ts +3 -141
  49. package/src/web/templates/MediaTileRowRenderer.ts +90 -15
  50. package/android/src/main/java/com/onekey/nativelist/NativeListTitleSegmentLayout.kt +0 -49
  51. package/android/src/main/java/com/onekey/nativelist/NativeListTitleSegmentsView.kt +0 -105
  52. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListTitleSegmentLayoutTest.kt +0 -80
  53. package/ios/NativeListTitleSegmentLayout.swift +0 -45
  54. package/ios/NativeListTitleSegmentsLabel.swift +0 -80
@@ -31,6 +31,8 @@ final class NativeListView: UIView {
31
31
  private var refreshEmittedForDrag = false
32
32
  private var minimumDragOffset: CGFloat = 0
33
33
  private var containerSlotHeights: [CGFloat] = [0, 0, 0, 0, 0, 0]
34
+ private var containerHeaderHeightIsAuthoritative = false
35
+ private weak var currentHeaderRoot: UIView?
34
36
  private var disclosureCVisibleHeight: CGFloat = 0
35
37
  private var disclosureInset: CGFloat = 0
36
38
  private var disclosureStartCHeight: CGFloat = 0
@@ -197,8 +199,10 @@ final class NativeListView: UIView {
197
199
  if !tail.retiringKeys.isEmpty {
198
200
  var snapshot = dataSource.snapshot()
199
201
  snapshot.deleteItems(Array(tail.retiringKeys))
200
- dataSource.apply(snapshot, animatingDifferences: false)
201
- itemsByKey = Dictionary(uniqueKeysWithValues: config.items.map { ($0.key, $0) })
202
+ let finishRetiringCells = replaceCellItems(
203
+ with: Dictionary(uniqueKeysWithValues: config.items.map { ($0.key, $0) }),
204
+ outgoingKeys: tail.retiringKeys)
205
+ dataSource.apply(snapshot, animatingDifferences: false, completion: finishRetiringCells)
202
206
  }
203
207
  clearStructuralTail()
204
208
  structuralSpacerHeight = 0
@@ -295,6 +299,10 @@ final class NativeListView: UIView {
295
299
  host.addSubview(view)
296
300
  reactContainerSlots.insert((view, host), at: min(index, reactContainerSlots.count))
297
301
  collectionView.addSubview(host)
302
+ if index == 0 {
303
+ currentHeaderRoot = view
304
+ if !containerHeaderHeightIsAuthoritative { updatePendingHeaderHeight() }
305
+ }
298
306
  layoutContainerSlots()
299
307
  setNeedsLayout()
300
308
  }
@@ -306,12 +314,17 @@ final class NativeListView: UIView {
306
314
  updateTopScrollEdge()
307
315
  return
308
316
  }
317
+ let removedCurrentHeader = currentHeaderRoot === view
318
+ if removedCurrentHeader { currentHeaderRoot = nil }
309
319
  reactContainerSlots.removeAll { slot in
310
320
  guard slot.content === view else { return false }
311
321
  view.removeFromSuperview()
312
322
  slot.host.removeFromSuperview()
313
323
  return true
314
324
  }
325
+ if removedCurrentHeader && !containerHeaderHeightIsAuthoritative {
326
+ updatePendingHeaderHeight()
327
+ }
315
328
  }
316
329
 
317
330
  func setTopScrollEdge(effect: NativeListTopScrollEdgeEffect, overlayHeight: CGFloat) {
@@ -376,12 +389,37 @@ final class NativeListView: UIView {
376
389
 
377
390
  func setContainerSlotHeightsJson(_ json: String, followedBySnapshot: Bool = false) {
378
391
  guard let data = json.data(using: .utf8),
379
- let heights = try? JSONSerialization.jsonObject(with: data) as? [Double],
380
- (heights.count == 4 || heights.count == 6),
392
+ var values = try? JSONSerialization.jsonObject(with: data) as? [Any],
393
+ (values.count == 4 || values.count == 6) else { return }
394
+ let headerPending = values[0] is NSNull
395
+ if headerPending { values[0] = 0.0 }
396
+ guard let heights = values as? [Double],
381
397
  heights.allSatisfy({ $0.isFinite && $0 >= 0 }) else { return }
398
+ containerHeaderHeightIsAuthoritative = !headerPending
399
+ var next = heights.map { CGFloat($0) } + (heights.count == 4 ? [0, 0] : [])
400
+ if headerPending { next[0] = pendingHeaderHeight() }
401
+ applyContainerSlotHeights(next, followedBySnapshot: followedBySnapshot)
402
+ }
403
+
404
+ private func pendingHeaderHeight() -> CGFloat {
405
+ guard let bounds = currentHeaderRoot?.bounds,
406
+ bounds.width.isFinite, bounds.width > 0,
407
+ bounds.height.isFinite, bounds.height >= 0 else { return 0 }
408
+ return ceil(bounds.height)
409
+ }
410
+
411
+ private func updatePendingHeaderHeight() {
412
+ let height = pendingHeaderHeight()
413
+ guard height != containerSlotHeights[0] else { return }
414
+ var next = containerSlotHeights
415
+ next[0] = height
416
+ applyContainerSlotHeights(next)
417
+ }
418
+
419
+ private func applyContainerSlotHeights(_ heights: [CGFloat], followedBySnapshot: Bool = false) {
382
420
  let previousHeights = containerSlotHeights
383
- let footerDelta = containerSlotHeights[2] - CGFloat(heights[2])
384
- containerSlotHeights = heights.map { CGFloat($0) } + (heights.count == 4 ? [0, 0] : [])
421
+ let footerDelta = containerSlotHeights[2] - heights[2]
422
+ containerSlotHeights = heights
385
423
  let contentHeightChanged = previousHeights[4] != containerSlotHeights[4]
386
424
  let toggleHeightChanged = previousHeights[5] != containerSlotHeights[5]
387
425
  let disclosureGeometryInvalid = structuralTail != nil && config?.disclosure != nil
@@ -665,6 +703,9 @@ final class NativeListView: UIView {
665
703
  private var config: NativeListConfig?
666
704
  private var acceptedRowIndex: AcceptedRowIndex?
667
705
  private var itemsByKey: [String: NativeListItem] = [:]
706
+ private static let emptyCellReuseIdentifier = "NativeList.EmptyCell"
707
+ private var retiringCellItems: [String: (item: NativeListItem, update: UInt64)] = [:]
708
+ private var cellUpdate: UInt64 = 0
668
709
  private var endReachedGeneration: Int?
669
710
  private var lastVisibleRange: (first: Int, last: Int, firstKey: String?, lastKey: String?)?
670
711
  private var visibleEventScheduled = false
@@ -741,6 +782,8 @@ final class NativeListView: UIView {
741
782
  self.collectionView.setContentOffset(self.collectionView.contentOffset, animated: false)
742
783
  }
743
784
  NativeListRendererRegistry.register(in: collectionView)
785
+ collectionView.register(UICollectionViewCell.self,
786
+ forCellWithReuseIdentifier: Self.emptyCellReuseIdentifier)
744
787
  collectionView.backgroundColor = .clear
745
788
  collectionView.delegate = self
746
789
  collectionView.dragDelegate = self
@@ -837,14 +880,30 @@ final class NativeListView: UIView {
837
880
  footerCell.addGestureRecognizer(footerHighlight)
838
881
  dataSource = UICollectionViewDiffableDataSource<Int, String>(collectionView: collectionView) {
839
882
  [weak self] collectionView, indexPath, key in
840
- guard let self,
841
- let item = self.itemsByKey[key],
842
- let cell = collectionView.dequeueReusableCell(
843
- withReuseIdentifier: NativeListRendererRegistry.reuseIdentifier(for: item.rendererKey),
844
- for: indexPath
845
- ) as? NativeListRowHost else { return nil }
883
+ guard let self, let item = self.itemsByKey[key] ?? self.retiringCellItems[key]?.item else {
884
+ let cell = collectionView.dequeueReusableCell(
885
+ withReuseIdentifier: NativeListView.emptyCellReuseIdentifier, for: indexPath)
886
+ cell.isUserInteractionEnabled = false
887
+ cell.accessibilityElementsHidden = true
888
+ return cell
889
+ }
890
+ let reusableCell = collectionView.dequeueReusableCell(
891
+ withReuseIdentifier: NativeListRendererRegistry.reuseIdentifier(for: item.rendererKey),
892
+ for: indexPath)
893
+ guard let cell = reusableCell as? NativeListRowHost else { return reusableCell }
894
+ if self.itemsByKey[key] == nil {
895
+ cell.onAction = nil
896
+ cell.onBindingInvalidated = nil
897
+ cell.isHidden = true
898
+ cell.isUserInteractionEnabled = false
899
+ cell.accessibilityElementsHidden = true
900
+ return cell
901
+ }
846
902
  cell.onAction = { [weak self] item, action, target, origin in
847
- self?.handleAction(item: item, actionKey: action, target: target, origin: origin)
903
+ // A child renderer can emit a different key than the collection row that owns it.
904
+ guard let self, self.itemsByKey[key] != nil,
905
+ !self.isInertPresentationKey(key) else { return }
906
+ self.handleAction(item: item, actionKey: action, target: target, origin: origin)
848
907
  }
849
908
  cell.onBindingInvalidated = { [weak self] cell, epoch in
850
909
  self?.handleBindingInvalidated(cell: cell, epoch: epoch)
@@ -937,6 +996,7 @@ final class NativeListView: UIView {
937
996
  guard !disposed,
938
997
  window != nil,
939
998
  collectionView.delegate === self,
999
+ flowLayout.scrollDirection == .vertical,
940
1000
  collectionView.bounds.width > 0,
941
1001
  collectionView.bounds.height > 0 else { return }
942
1002
  NotificationCenter.default.post(
@@ -971,11 +1031,11 @@ final class NativeListView: UIView {
971
1031
  configureLayout(config)
972
1032
  if lastLayoutDirection != direction { rebindRowsForLayoutDirection(config) }
973
1033
  }
974
- performPendingScrollIfNeeded()
975
- layoutContainerSlots()
976
1034
  if !hadUsableBounds && collectionView.bounds.width > 0 && collectionView.bounds.height > 0 {
977
1035
  notifyPagerScrollViewReadyIfNeeded()
978
1036
  }
1037
+ performPendingScrollIfNeeded()
1038
+ layoutContainerSlots()
979
1039
  }
980
1040
 
981
1041
  // A layout-direction change may arrive without a layout pass (semantic attribute or trait).
@@ -1017,6 +1077,29 @@ final class NativeListView: UIView {
1017
1077
  acceptedRowIndex = AcceptedRowIndex(items: next.items)
1018
1078
  }
1019
1079
 
1080
+ // Layout can ask UIKit's outgoing snapshot for cells before apply starts or while it settles.
1081
+ // Keep those descriptors outside the accepted row lookup and release each at its own commit.
1082
+ private func replaceCellItems(
1083
+ with nextItems: [String: NativeListItem], outgoingKeys: some Sequence<String>
1084
+ ) -> (() -> Void)? {
1085
+ cellUpdate &+= 1
1086
+ let update = cellUpdate
1087
+ var retiringKeys: [String] = []
1088
+ for key in outgoingKeys where nextItems[key] == nil {
1089
+ guard let item = itemsByKey[key] ?? retiringCellItems[key]?.item else { continue }
1090
+ retiringCellItems[key] = (item, update)
1091
+ retiringKeys.append(key)
1092
+ }
1093
+ itemsByKey = nextItems
1094
+ guard !retiringKeys.isEmpty else { return nil }
1095
+ return { [weak self] in
1096
+ guard let self else { return }
1097
+ for key in retiringKeys where self.retiringCellItems[key]?.update == update {
1098
+ self.retiringCellItems.removeValue(forKey: key)
1099
+ }
1100
+ }
1101
+ }
1102
+
1020
1103
  func applySnapshotJson(_ json: String) {
1021
1104
  guard let next = try? NativeListConfig.parse(json: json) else { return }
1022
1105
  let transition = next.structuralTransition
@@ -1207,13 +1290,14 @@ final class NativeListView: UIView {
1207
1290
  disclosureInset = next.disclosure?.expanded == true
1208
1291
  ? next.disclosure?.expandedTrailingInset ?? 0 : 0
1209
1292
  }
1210
- itemsByKey = Dictionary(uniqueKeysWithValues: next.items.map { ($0.key, $0) })
1211
- itemsByKey.merge(structuralRemovedItems) { current, _ in current }
1293
+ var nextItemsByKey = Dictionary(uniqueKeysWithValues: next.items.map { ($0.key, $0) })
1294
+ nextItemsByKey.merge(structuralRemovedItems) { current, _ in current }
1212
1295
  if let tail = structuralTail, !tail.retiringKeys.isEmpty {
1213
- itemsByKey.merge(presentationItems.filter { tail.retiringKeys.contains($0.key) }) {
1296
+ nextItemsByKey.merge(presentationItems.filter { tail.retiringKeys.contains($0.key) }) {
1214
1297
  current, _ in current
1215
1298
  }
1216
1299
  }
1300
+ let finishRetiringCells = replaceCellItems(with: nextItemsByKey, outgoingKeys: oldKeys)
1217
1301
  if !animateStructure, let tail = structuralTail {
1218
1302
  if themeChanged || tailGeometryChanged {
1219
1303
  if !newDisclosureCommand { interruptedPendingID = activePendingID }
@@ -1304,7 +1388,8 @@ final class NativeListView: UIView {
1304
1388
  let explicitScrollPendingAtApply = pendingScrollRequest != nil
1305
1389
  dataSource.apply(snapshot, animatingDifferences: animateStructure && structuralRemovedItems.isEmpty
1306
1390
  && structuralTail == nil) { [weak self] in
1307
- guard let self else { return }
1391
+ finishRetiringCells?()
1392
+ guard let self, !self.disposed else { return }
1308
1393
  self.collectionView.layoutIfNeeded()
1309
1394
  self.updateStructuralTailWindow()
1310
1395
  self.layoutContainerSlots()
@@ -1473,11 +1558,14 @@ final class NativeListView: UIView {
1473
1558
  if progress >= 1 {
1474
1559
  if !structuralRemovedItems.isEmpty {
1475
1560
  var snapshot = dataSource.snapshot()
1476
- snapshot.deleteItems(Array(structuralRemovedItems.keys))
1561
+ let outgoingKeys = Array(structuralRemovedItems.keys)
1562
+ snapshot.deleteItems(outgoingKeys)
1477
1563
  structuralRemovedItems.removeAll()
1478
1564
  structuralRemovedHeights.removeAll()
1479
- dataSource.apply(snapshot, animatingDifferences: false)
1480
- itemsByKey = Dictionary(uniqueKeysWithValues: config.items.map { ($0.key, $0) })
1565
+ let finishRetiringCells = replaceCellItems(
1566
+ with: Dictionary(uniqueKeysWithValues: config.items.map { ($0.key, $0) }),
1567
+ outgoingKeys: outgoingKeys)
1568
+ dataSource.apply(snapshot, animatingDifferences: false, completion: finishRetiringCells)
1481
1569
  collectionView.layoutIfNeeded()
1482
1570
  if !structuralScrollInterrupted && !collectionView.isTracking
1483
1571
  && !collectionView.isDragging && !collectionView.isDecelerating {
@@ -1653,6 +1741,7 @@ final class NativeListView: UIView {
1653
1741
  requestScroll(.index(index, animated, alignment, viewPosition, viewOffset))
1654
1742
  }
1655
1743
 
1744
+ @objc(onekeyScrollToOffset:animated:)
1656
1745
  func scrollToOffset(_ offset: Double, animated: Bool) {
1657
1746
  requestScroll(.offset(offset, animated))
1658
1747
  }
@@ -2242,7 +2331,9 @@ final class NativeListView: UIView {
2242
2331
  // while the diffable snapshot and cell index paths keep the pre-drag order until
2243
2332
  // the move commits. Resolving sizes from the snapshot swaps row heights.
2244
2333
  private func layoutItem(at indexPath: IndexPath) -> NativeListItem? {
2245
- guard let keys = interactiveMovementKeys else { return item(at: indexPath) }
2334
+ guard let keys = interactiveMovementKeys else {
2335
+ return item(at: indexPath, includeRetiringCell: true)
2336
+ }
2246
2337
  return keys[safe: indexPath.item].flatMap { itemsByKey[$0] }
2247
2338
  }
2248
2339
 
@@ -2255,15 +2346,16 @@ final class NativeListView: UIView {
2255
2346
  interactiveMovementKeys = keys
2256
2347
  }
2257
2348
 
2258
- private func item(at indexPath: IndexPath) -> NativeListItem? {
2259
- if let key = dataSource.itemIdentifier(for: indexPath), let item = itemsByKey[key] {
2260
- return item
2349
+ private func item(at indexPath: IndexPath, includeRetiringCell: Bool = false) -> NativeListItem? {
2350
+ if let key = dataSource.itemIdentifier(for: indexPath) {
2351
+ return itemsByKey[key] ?? (includeRetiringCell ? retiringCellItems[key]?.item : nil)
2261
2352
  }
2262
2353
  return config?.items[safe: indexPath.item]
2263
2354
  }
2264
2355
 
2265
2356
  private func isInertPresentationKey(_ key: String) -> Bool {
2266
2357
  structuralTail?.indexByKey[key] != nil || structuralRemovedItems[key] != nil
2358
+ || (itemsByKey[key] == nil && retiringCellItems[key] != nil)
2267
2359
  }
2268
2360
 
2269
2361
  private func updateAtomicReorderTarget(to targetIndex: Int, key targetKey: String, animated: Bool) {
@@ -2609,7 +2701,7 @@ final class NativeListView: UIView {
2609
2701
  if item.key == interactiveReorderCompactKey {
2610
2702
  cell.setWalletGroupReorderCompact(true)
2611
2703
  }
2612
- let retiring = structuralRemovedItems[item.key] != nil
2704
+ let retiring = cell !== footerCell && structuralRemovedItems[item.key] != nil
2613
2705
  cell.structuralContentHeight = retiring
2614
2706
  ? rowHeight(item, allocatedWidth: cell.bounds.width) : nil
2615
2707
  if retiring { cell.clipsToBounds = true }
@@ -2625,7 +2717,7 @@ final class NativeListView: UIView {
2625
2717
 
2626
2718
  private func handleRowPress(_ item: NativeListItem, origin: NativeListActionOrigin?) {
2627
2719
  // OneKey patch: missing-address rows keep accessory actions available.
2628
- guard let config, item.isRowPressEnabled, !isInertPresentationKey(item.key) else { return }
2720
+ guard let config, item.isRowPressEnabled else { return }
2629
2721
  if config.rowPressToggles && item.isSelectable && config.selectionMode != "none" {
2630
2722
  updateSelection(target: NativeSelectionTarget(scope: "row", key: item.key), sourceKey: item.key)
2631
2723
  return
@@ -2661,7 +2753,7 @@ final class NativeListView: UIView {
2661
2753
  target: NativeSelectionTarget?,
2662
2754
  origin: NativeListActionOrigin?
2663
2755
  ) {
2664
- guard !item.data.bool("disabled"), !isInertPresentationKey(item.key) else { return }
2756
+ guard !item.data.bool("disabled") else { return }
2665
2757
  if let target, config?.selectionMode != "none" {
2666
2758
  updateSelection(target: target, sourceKey: item.key)
2667
2759
  return
@@ -2670,8 +2762,7 @@ final class NativeListView: UIView {
2670
2762
  }
2671
2763
 
2672
2764
  private func updateSelection(target: NativeSelectionTarget, sourceKey: String) {
2673
- guard var current = config, current.selectionMode != "none",
2674
- !isInertPresentationKey(sourceKey) else { return }
2765
+ guard var current = config, current.selectionMode != "none" else { return }
2675
2766
  let keys = selectionKeys(target: target, items: current.items)
2676
2767
  guard !keys.isEmpty else { return }
2677
2768
  let before = current.selectedKeys
@@ -3084,6 +3175,9 @@ final class NativeListView: UIView {
3084
3175
  dataSource = nil
3085
3176
 
3086
3177
  config = nil
3178
+ currentHeaderRoot = nil
3179
+ containerHeaderHeightIsAuthoritative = false
3180
+ containerSlotHeights[0] = 0
3087
3181
  acceptedRowIndex = nil
3088
3182
  pagerStickyHeights.removeAllObjects()
3089
3183
  for slot in reactContainerSlots { slot.host.layer.mask = nil }
@@ -3092,6 +3186,7 @@ final class NativeListView: UIView {
3092
3186
  structuralSpacerHeight = 0
3093
3187
  structuralFooterStartY = nil
3094
3188
  itemsByKey.removeAll()
3189
+ retiringCellItems.removeAll()
3095
3190
  sectionIndexEntries.removeAll()
3096
3191
  if let pagerCommandCancelObserver {
3097
3192
  NotificationCenter.default.removeObserver(pagerCommandCancelObserver)
@@ -3573,7 +3668,9 @@ final class NativeListFlowLayout: UICollectionViewFlowLayout {
3573
3668
  guard scrollDirection == .horizontal, let collectionView else { return }
3574
3669
 
3575
3670
  var nextX = sectionInset.left
3576
- let itemCount = collectionView.numberOfItems(inSection: 0)
3671
+ let itemCount = collectionView.numberOfSections > 0
3672
+ ? collectionView.numberOfItems(inSection: 0)
3673
+ : 0
3577
3674
  for item in 0..<itemCount {
3578
3675
  let indexPath = IndexPath(item: item, section: 0)
3579
3676
  guard let attributes = super.layoutAttributesForItem(at: indexPath)?.copy()
@@ -60,6 +60,276 @@ final class NativeListActivityPresentationTests: XCTestCase {
60
60
  }
61
61
  }
62
62
 
63
+ // The description label spans the identity column, so a tap anywhere on its
64
+ // line used to open the description action. Only the action text opens it
65
+ // now; the blank rest of the line belongs to the row press (OK-67219). Where
66
+ // that text starts is the caller's `descriptionActionStart`, never something
67
+ // read out of the string.
68
+ func testDescriptionActionTakesTouchesOnItsTextOnly() throws {
69
+ let details = NativeListActivityDetailsView()
70
+ // Wide enough that the label keeps blank space beside its text even when
71
+ // the amounts take their full half of the row.
72
+ let container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 300))
73
+ details.translatesAutoresizingMaskIntoConstraints = false
74
+ container.addSubview(details)
75
+ NSLayoutConstraint.activate([
76
+ details.leadingAnchor.constraint(equalTo: container.leadingAnchor),
77
+ details.trailingAnchor.constraint(equalTo: container.trailingAnchor),
78
+ details.topAnchor.constraint(equalTo: container.topAnchor),
79
+ ])
80
+ func bind(description: String, actionKey: String?, actionStart: Int? = nil) throws -> NativeListTextLabel {
81
+ var data: [String: Any] = [
82
+ "type": "activity", "key": "tx", "title": "Swap", "description": description,
83
+ "leading": ["kind": "icon", "name": "ArrowTopOutline"],
84
+ "amounts": [["key": "send", "text": "-1"]],
85
+ ]
86
+ if let actionKey { data["descriptionActionKey"] = actionKey }
87
+ if let actionStart { data["descriptionActionStart"] = actionStart }
88
+ details.bind(try NativeListItem(data: data), theme: nil, fonts: NativeListFontFamilies())
89
+ container.layoutIfNeeded()
90
+ func find(_ view: UIView) -> NativeListTextLabel? {
91
+ if let label = view as? NativeListTextLabel, label.text == description { return label }
92
+ return view.subviews.lazy.compactMap(find).first
93
+ }
94
+ return try XCTUnwrap(find(details))
95
+ }
96
+ func hit(_ label: NativeListTextLabel, x: CGFloat) -> Bool {
97
+ label.point(inside: CGPoint(x: x, y: label.bounds.midY), with: nil)
98
+ }
99
+
100
+ // Without a start the whole text is the action, also a label holding the
101
+ // separator a time prefix would use.
102
+ let label = try bind(description: "Router • V2", actionKey: "address-info")
103
+ let labelText = try XCTUnwrap(label.touchableTextRegions.first)
104
+ XCTAssertEqual(label.touchableTextStart, 0)
105
+ XCTAssertEqual(label.touchableTextRegions.count, 1)
106
+ XCTAssertGreaterThan(label.bounds.width, labelText.maxX + 40)
107
+ XCTAssertTrue(hit(label, x: 4))
108
+ XCTAssertTrue(hit(label, x: labelText.maxX - 12))
109
+ XCTAssertFalse(hit(label, x: label.bounds.maxX - 4))
110
+
111
+ // With a start only the text from there on is the action: the time is
112
+ // not, the complete label behind it is.
113
+ let prefix = "08:48 • "
114
+ let timed = try bind(
115
+ description: prefix + "Router • V2", actionKey: "address-info",
116
+ actionStart: (prefix as NSString).length)
117
+ let timedText = try XCTUnwrap(timed.touchableTextRegions.first)
118
+ XCTAssertEqual(timed.touchableTextRegions.count, 1)
119
+ XCTAssertGreaterThan(timed.bounds.width, timedText.maxX + 40)
120
+ // The same label, less the slop on the side where the time is.
121
+ XCTAssertEqual(timedText.width, labelText.width - 8, accuracy: 1)
122
+ XCTAssertFalse(hit(timed, x: 4))
123
+ XCTAssertFalse(hit(timed, x: timedText.minX - 2))
124
+ XCTAssertTrue(hit(timed, x: timedText.minX + 2))
125
+ XCTAssertTrue(hit(timed, x: timedText.maxX - 12))
126
+ XCTAssertFalse(hit(timed, x: timed.bounds.maxX - 4))
127
+
128
+ // The start counts UTF-16 units: the emoji takes two.
129
+ let emojiPrefix = "🕘 08:48 • "
130
+ XCTAssertEqual((emojiPrefix as NSString).length, 11)
131
+ let emoji = try bind(
132
+ description: emojiPrefix + "Router • V2", actionKey: "address-info", actionStart: 11)
133
+ let emojiText = try XCTUnwrap(emoji.touchableTextRegions.first)
134
+ XCTAssertEqual(emojiText.width, labelText.width - 8, accuracy: 1)
135
+ XCTAssertFalse(hit(emoji, x: 4))
136
+ XCTAssertFalse(hit(emoji, x: emojiText.minX - 2))
137
+ XCTAssertTrue(hit(emoji, x: emojiText.minX + 2))
138
+ XCTAssertTrue(hit(emoji, x: emojiText.maxX - 12))
139
+
140
+ // A start at the end of the text, or clamped to it, leaves nothing to tap.
141
+ // 4294967296 is a safe integer past 32 bits; it must clamp, not wrap to 0.
142
+ for start in [(prefix as NSString).length, 99, 4_294_967_296] {
143
+ let ended = try bind(description: prefix, actionKey: "address-info", actionStart: start)
144
+ XCTAssertTrue(ended.touchableTextRegions.isEmpty)
145
+ XCTAssertFalse(ended.isUserInteractionEnabled)
146
+ XCTAssertFalse(hit(ended, x: 4))
147
+ }
148
+
149
+ // The reused view keeps no state: a rebind without a start covers the
150
+ // whole text again, one without the action restores the label's own hit
151
+ // testing even when a start is still supplied, and so does recycling.
152
+ let rebound = try bind(description: "Router • V2", actionKey: "address-info")
153
+ XCTAssertEqual(rebound.touchableTextStart, 0)
154
+ XCTAssertTrue(rebound.isUserInteractionEnabled)
155
+ XCTAssertTrue(hit(rebound, x: 4))
156
+ let plain = try bind(description: "Router • V2", actionKey: nil, actionStart: 3)
157
+ XCTAssertNil(plain.touchableTextStart)
158
+ XCTAssertFalse(plain.isUserInteractionEnabled)
159
+ XCTAssertTrue(hit(plain, x: plain.bounds.maxX - 4))
160
+ let recycled = try bind(
161
+ description: prefix + "Router", actionKey: "address-info",
162
+ actionStart: (prefix as NSString).length)
163
+ XCTAssertEqual(recycled.touchableTextStart, (prefix as NSString).length)
164
+ details.recycle()
165
+ XCTAssertNil(recycled.touchableTextStart)
166
+ }
167
+
168
+ // A narrow column wraps "time • address". The time stays outside the action
169
+ // on its line, while the address is hit on both lines, also at the x the
170
+ // time occupies one line above. The label is sized directly so the wrap does
171
+ // not depend on how the row shares its width.
172
+ func testWrappedDescriptionKeepsTheTimeOutsideTheAction() throws {
173
+ let description = "08:48 • Uniswap Router"
174
+ let label = NativeListTextLabel()
175
+ NativeListResolvedText(
176
+ description, style: nil, size: 14, color: .label, lineHeight: 20, lines: 2,
177
+ fonts: NativeListFontFamilies()
178
+ ).bind(label)
179
+ label.frame = CGRect(x: 0, y: 0, width: 142, height: 40)
180
+ label.touchableTextStart = ("08:48 • " as NSString).length
181
+ func hit(_ x: CGFloat, _ y: CGFloat) -> Bool {
182
+ label.point(inside: CGPoint(x: x, y: y), with: nil)
183
+ }
184
+
185
+ let lines = label.touchableTextRegions
186
+ XCTAssertEqual(lines.count, 2)
187
+ guard lines.count == 2 else { return }
188
+ XCTAssertFalse(hit(4, lines[0].midY))
189
+ XCTAssertTrue(hit(lines[0].maxX - 12, lines[0].midY))
190
+ XCTAssertTrue(hit(4, lines[1].midY))
191
+ XCTAssertFalse(hit(label.bounds.maxX - 2, lines[1].midY))
192
+ }
193
+
194
+ // The first line holds only the time, so it takes no touches, and the slop
195
+ // of the address line below it must not reach up into the time.
196
+ func testAddressStartingOnTheSecondLineLeavesTheTimeLineAlone() throws {
197
+ let prefix = "08:48 • "
198
+ let address = "UniswapUniversalRouter"
199
+ func text(_ value: String) -> NativeListResolvedText {
200
+ NativeListResolvedText(
201
+ value, style: nil, size: 14, color: .label, lineHeight: 20, lines: 2,
202
+ fonts: NativeListFontFamilies())
203
+ }
204
+ let label = NativeListTextLabel()
205
+ text(prefix + address).bind(label)
206
+ // Wide enough for the address alone, too narrow for the time beside it.
207
+ label.frame = CGRect(x: 0, y: 0, width: text(address).measureWidth() + 4, height: 40)
208
+ label.touchableTextStart = (prefix as NSString).length
209
+ func hit(y: CGFloat) -> Bool { label.point(inside: CGPoint(x: 4, y: y), with: nil) }
210
+
211
+ let line = try XCTUnwrap(label.touchableTextRegions.first)
212
+ XCTAssertEqual(label.touchableTextRegions.count, 1)
213
+ XCTAssertEqual(line.minY, 20, accuracy: 0.5)
214
+ XCTAssertFalse(hit(y: 10))
215
+ XCTAssertFalse(hit(y: line.minY - 2))
216
+ XCTAssertTrue(hit(y: line.minY + 2))
217
+ // The last line of the layout still takes its slop below the text.
218
+ XCTAssertTrue(hit(y: label.bounds.maxY + 4))
219
+ }
220
+
221
+ private func descriptionText(_ value: String, style: [String: Any]? = nil) -> NativeListResolvedText {
222
+ NativeListResolvedText(
223
+ value, style: style, size: 14, color: .label, lineHeight: 20, lines: 1,
224
+ fonts: NativeListFontFamilies())
225
+ }
226
+
227
+ /// Width the description font gives `value` on its own.
228
+ private func descriptionWidth(_ value: String) -> CGFloat {
229
+ descriptionText(value).attributed(direction: .leftToRight).size().width
230
+ }
231
+
232
+ private func descriptionLabel(
233
+ _ value: String, start: Int, width: CGFloat = 300, style: [String: Any]? = nil
234
+ ) -> NativeListTextLabel {
235
+ let label = NativeListTextLabel()
236
+ descriptionText(value, style: style).bind(label)
237
+ label.frame = CGRect(x: 0, y: 0, width: width, height: 20)
238
+ label.touchableTextStart = start
239
+ return label
240
+ }
241
+
242
+ private func hit(_ label: NativeListTextLabel, x: CGFloat) -> Bool {
243
+ label.point(inside: CGPoint(x: x, y: label.bounds.midY), with: nil)
244
+ }
245
+
246
+ // The slop is for blank space. It stops at plain text beside the action
247
+ // text, or a prefix narrower than the slop, like the "i" of "iRouter", would
248
+ // open an action it is not part of.
249
+ func testSlopStopsAtPlainTextBesideTheActionText() throws {
250
+ let short = descriptionLabel("iRouter", start: 1)
251
+ let i = descriptionWidth("i")
252
+ XCTAssertLessThan(i, 8)
253
+ let region = try XCTUnwrap(short.touchableTextRegions.first)
254
+ XCTAssertEqual(short.touchableTextRegions.count, 1)
255
+ XCTAssertEqual(region.minX, i, accuracy: 0.5)
256
+ XCTAssertFalse(hit(short, x: i / 2))
257
+ XCTAssertFalse(hit(short, x: -3))
258
+ XCTAssertTrue(hit(short, x: i + 2))
259
+ // Into the blank after the text the slop still reaches.
260
+ XCTAssertTrue(hit(short, x: descriptionWidth("iRouter") + 6))
261
+ XCTAssertFalse(hit(short, x: descriptionWidth("iRouter") + 10))
262
+ // And into the blank before a line that starts with the action text.
263
+ XCTAssertTrue(hit(descriptionLabel("Router", start: 0), x: -6))
264
+ }
265
+
266
+ // Mixed-direction text can split one logical suffix into several visual
267
+ // runs. From offset 6 of "ABC אבג XYZ" the suffix is the last Hebrew letter
268
+ // and " XYZ"; the Hebrew run is drawn right to left, so that letter sits
269
+ // left of the two plain ones. Each run is its own region and the plain text
270
+ // between them takes no touches.
271
+ func testMixedDirectionSuffixFollowsTheLaidOutRuns() {
272
+ let label = descriptionLabel("ABC \u{05D0}\u{05D1}\u{05D2} XYZ", start: 6)
273
+ let abc = descriptionWidth("ABC ")
274
+ let last = descriptionWidth("\u{05D2}")
275
+ let plain = descriptionWidth("\u{05D1}\u{05D0}")
276
+ let xyz = descriptionWidth(" XYZ")
277
+ let regions = label.touchableTextRegions.sorted { $0.minX < $1.minX }
278
+ XCTAssertEqual(regions.count, 2)
279
+ guard regions.count == 2 else { return }
280
+ XCTAssertEqual(regions[0].minX, abc, accuracy: 1)
281
+ XCTAssertEqual(regions[0].maxX, abc + last, accuracy: 1)
282
+ XCTAssertEqual(regions[1].minX, abc + last + plain, accuracy: 1)
283
+ XCTAssertFalse(hit(label, x: abc / 2))
284
+ XCTAssertTrue(hit(label, x: abc + last / 2))
285
+ XCTAssertFalse(hit(label, x: abc + last + plain / 2))
286
+ XCTAssertTrue(hit(label, x: abc + last + plain + xyz / 2))
287
+ // Only the outer edge of the last run faces blank space.
288
+ XCTAssertTrue(hit(label, x: abc + last + plain + xyz + 5))
289
+ }
290
+
291
+ // A one-line description that does not fit ends in an ellipsis. Action text
292
+ // it only shortens stays touchable up to and including the ellipsis. Once it
293
+ // hides the action text altogether the ellipsis also stands for plain text,
294
+ // and nothing is left to touch.
295
+ func testTruncationCanHideTheActionText() throws {
296
+ let cut = descriptionLabel(
297
+ "08:48 • UniswapUniversalRouterWithAVeryLongName", start: 8, width: 150,
298
+ style: ["lines": 1])
299
+ let region = try XCTUnwrap(cut.touchableTextRegions.first)
300
+ XCTAssertEqual(cut.touchableTextRegions.count, 1)
301
+ XCTAssertEqual(region.minX, descriptionWidth("08:48 • "), accuracy: 1)
302
+ XCTAssertFalse(hit(cut, x: 20))
303
+ XCTAssertTrue(hit(cut, x: 100))
304
+ XCTAssertTrue(hit(cut, x: 145))
305
+
306
+ let prefix = "A very long plain prefix that fills the row • "
307
+ let hidden = descriptionLabel(
308
+ prefix + "Router", start: (prefix as NSString).length, width: 150, style: ["lines": 1])
309
+ XCTAssertTrue(hidden.touchableTextRegions.isEmpty)
310
+ XCTAssertFalse(hit(hidden, x: 145))
311
+ }
312
+
313
+ // A one-line description folds each line break into one space, so the
314
+ // caller's offset is mapped onto the displayed text and kept inside it.
315
+ func testDescriptionActionStartFollowsTheDisplayedText() {
316
+ let source = "08:48\r\n• Router"
317
+ func text(_ style: [String: Any]?) -> NativeListResolvedText {
318
+ NativeListResolvedText(
319
+ source, style: style, size: 14, color: .label, lineHeight: 20, lines: 2,
320
+ fonts: NativeListFontFamilies())
321
+ }
322
+ let oneLine = text(["lines": 1])
323
+ XCTAssertEqual(oneLine.text, "08:48 • Router")
324
+ XCTAssertEqual(oneLine.displayOffset(9, in: source), 8)
325
+ XCTAssertEqual(oneLine.displayOffset(-3, in: source), 0)
326
+ XCTAssertEqual(oneLine.displayOffset(99, in: source), 14)
327
+ let wrapping = text(nil)
328
+ XCTAssertEqual(wrapping.text, source)
329
+ XCTAssertEqual(wrapping.displayOffset(9, in: source), 9)
330
+ XCTAssertEqual(wrapping.displayOffset(99, in: source), 15)
331
+ }
332
+
63
333
  func testSmallNumberRunsPreserveBaselineAcrossAmountsFiatAndFee() throws {
64
334
  func segments(_ prefix: String, _ suffix: String) -> [[String: Any]] {
65
335
  [["text": prefix], ["text": "5", "style": "subscript"], ["text": suffix]]