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

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 +194 -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 +50 -7
  22. package/ios/tests/NativeListActivityPresentationTests.swift +270 -0
  23. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +0 -95
  24. package/ios/tests/NativeListLifecycleTests.swift +176 -16
  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
@@ -0,0 +1,189 @@
1
+ import UIKit
2
+
3
+ /// Loading sheen and failed hatch drawn over a media tile while it has no picture.
4
+ /// Geometry mirrors the Web renderer (`MediaTileRowRenderer.ts`) and Android
5
+ /// (`NativeListMediaPlaceholderView.kt`) so every platform draws the same placeholder.
6
+ final class NativeListMediaPlaceholderView: UIView {
7
+ enum State { case hidden, loading, failed }
8
+
9
+ private static let sweepPeriod: CFTimeInterval = 1.6
10
+ private static let sweepKey = "nativeListMediaSweep"
11
+
12
+ private let sheen = CAGradientLayer()
13
+ private let hatch = CAShapeLayer()
14
+ private let hatchMask = CAGradientLayer()
15
+ private let picture = CAShapeLayer()
16
+ private let pictureCut = CAShapeLayer()
17
+ private let slash = CAShapeLayer()
18
+ private(set) var state: State = .hidden
19
+ private var laidOutSize: CGSize = .zero
20
+ private var loadingFill: UIColor = .clear
21
+
22
+ override init(frame: CGRect) {
23
+ super.init(frame: frame)
24
+ isUserInteractionEnabled = false
25
+ isHidden = true
26
+ clipsToBounds = true
27
+ layer.borderWidth = 1 / UIScreen.main.scale
28
+ sheen.startPoint = CGPoint(x: 0, y: 0.5)
29
+ sheen.endPoint = CGPoint(x: 1, y: 0.5)
30
+ sheen.locations = [0, 0.5, 1]
31
+ hatch.lineWidth = 1
32
+ hatch.fillColor = nil
33
+ hatchMask.type = .radial
34
+ hatchMask.startPoint = CGPoint(x: 0.5, y: 0.5)
35
+ // CSS `radial-gradient(circle ...)` defaults to the farthest corner.
36
+ hatchMask.endPoint = CGPoint(x: 0.5 + 0.7071, y: 0.5 + 0.7071)
37
+ hatchMask.colors = [UIColor.clear.cgColor, UIColor.clear.cgColor, UIColor.black.cgColor, UIColor.black.cgColor]
38
+ hatchMask.locations = [0, 0.22, 0.7, 1]
39
+ hatch.mask = hatchMask
40
+ for shape in [picture, slash] {
41
+ shape.fillColor = nil
42
+ shape.lineCap = .round
43
+ shape.lineJoin = .round
44
+ }
45
+ pictureCut.fillRule = .evenOdd
46
+ pictureCut.fillColor = UIColor.black.cgColor
47
+ [hatch, sheen, picture, slash].forEach(layer.addSublayer)
48
+ NotificationCenter.default.addObserver(
49
+ self, selector: #selector(restartSweep),
50
+ name: UIApplication.willEnterForegroundNotification, object: nil)
51
+ }
52
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
53
+
54
+ func applyTheme(_ theme: [String: Any]?) {
55
+ loadingFill = nativeListColor(theme, "strongBackground", "#0000000F")
56
+ if state == .loading { backgroundColor = loadingFill }
57
+ let glyph = nativeListColor(theme, "disabledText", "#8C8C8C")
58
+ let glyphColor = glyph.withAlphaComponent(glyph.cgAlpha * 0.7).cgColor
59
+ picture.strokeColor = glyphColor
60
+ slash.strokeColor = glyphColor
61
+ let separator = nativeListColor(theme, "separator", "#E5E7EB")
62
+ layer.borderColor = separator.withAlphaComponent(separator.cgAlpha * 0.6).cgColor
63
+ hatch.strokeColor = nativeListColor(theme, "primaryText", "#202020").withAlphaComponent(0.045).cgColor
64
+ let dark = nativeListIsDark(nativeListColor(theme, "rowBackground", "#FFFFFF"))
65
+ let shine = UIColor.white.withAlphaComponent(dark ? 0.07 : 0.75)
66
+ sheen.colors = [shine.withAlphaComponent(0).cgColor, shine.cgColor, shine.withAlphaComponent(0).cgColor]
67
+ }
68
+
69
+ func setState(_ next: State) {
70
+ guard next != state else { return }
71
+ state = next
72
+ isHidden = next == .hidden
73
+ // The failed state sits on the cell's own fill; while loading nothing else paints the slot.
74
+ backgroundColor = next == .loading ? loadingFill : .clear
75
+ CATransaction.begin()
76
+ CATransaction.setDisableActions(true)
77
+ sheen.isHidden = next != .loading
78
+ hatch.isHidden = next != .failed
79
+ slash.isHidden = next != .failed
80
+ picture.mask = next == .failed ? pictureCut : nil
81
+ CATransaction.commit()
82
+ restartSweep()
83
+ }
84
+
85
+ override func layoutSubviews() {
86
+ super.layoutSubviews()
87
+ guard bounds.size != laidOutSize else { return }
88
+ laidOutSize = bounds.size
89
+ CATransaction.begin()
90
+ CATransaction.setDisableActions(true)
91
+ layoutHatch()
92
+ layoutGlyph()
93
+ let width = bounds.width, height = bounds.height
94
+ sheen.bounds = CGRect(x: 0, y: 0, width: width * 0.6, height: height * 2)
95
+ sheen.position = CGPoint(x: width * 0.6, y: height / 2)
96
+ // CSS skewX(-12deg).
97
+ sheen.setAffineTransform(CGAffineTransform(a: 1, b: 0, c: -tan(12 * .pi / 180), d: 1, tx: 0, ty: 0))
98
+ CATransaction.commit()
99
+ restartSweep()
100
+ }
101
+
102
+ override func didMoveToWindow() {
103
+ super.didMoveToWindow()
104
+ restartSweep()
105
+ }
106
+
107
+ @objc private func restartSweep() {
108
+ sheen.removeAnimation(forKey: Self.sweepKey)
109
+ guard state == .loading, window != nil, bounds.width > 0 else { return }
110
+ let width = bounds.width
111
+ guard !UIAccessibility.isReduceMotionEnabled else {
112
+ sheen.opacity = 0.6
113
+ return
114
+ }
115
+ sheen.opacity = 1
116
+ let sweep = CAKeyframeAnimation(keyPath: "position.x")
117
+ // Band left edge travels from -80% to 130% of the tile, then rests for 30% of the period.
118
+ sweep.values = [width * -0.5, width * 1.6, width * 1.6]
119
+ sweep.keyTimes = [0, 0.7, 1]
120
+ sweep.timingFunctions = [
121
+ CAMediaTimingFunction(controlPoints: 0.4, 0, 0.2, 1), CAMediaTimingFunction(name: .linear),
122
+ ]
123
+ sweep.duration = Self.sweepPeriod
124
+ sweep.repeatCount = .infinity
125
+ sweep.isRemovedOnCompletion = false
126
+ // Every tile derives its phase from the shared media clock so the grid sweeps in step,
127
+ // including cells that are recycled mid-period.
128
+ sweep.timeOffset = CACurrentMediaTime().truncatingRemainder(dividingBy: Self.sweepPeriod)
129
+ sheen.add(sweep, forKey: Self.sweepKey)
130
+ }
131
+
132
+ private func layoutHatch() {
133
+ hatch.frame = bounds
134
+ hatchMask.frame = bounds
135
+ let path = UIBezierPath()
136
+ // Lines along x + y = c, 7pt apart measured perpendicular to the stripes.
137
+ let step = 7 * CGFloat(2).squareRoot()
138
+ var c: CGFloat = 0
139
+ while c <= bounds.width + bounds.height {
140
+ path.move(to: CGPoint(x: c, y: 0))
141
+ path.addLine(to: CGPoint(x: 0, y: c))
142
+ c += step
143
+ }
144
+ hatch.path = path.cgPath
145
+ }
146
+
147
+ private func layoutGlyph() {
148
+ let size = min(bounds.width * 0.28, 44)
149
+ let scale = size / 24
150
+ let origin = CGPoint(x: (bounds.width - size) / 2, y: (bounds.height - size) / 2)
151
+ var transform = CGAffineTransform(translationX: origin.x, y: origin.y).scaledBy(x: scale, y: scale)
152
+ let frame = UIBezierPath(roundedRect: CGRect(x: 3, y: 3, width: 18, height: 18), cornerRadius: 4)
153
+ frame.append(UIBezierPath(ovalIn: CGRect(x: 7.4, y: 7.4, width: 3.2, height: 3.2)))
154
+ let ridge = UIBezierPath()
155
+ ridge.move(to: CGPoint(x: 5, y: 20.5))
156
+ ridge.addLine(to: CGPoint(x: 14.5, y: 11))
157
+ ridge.addLine(to: CGPoint(x: 21, y: 17.5))
158
+ frame.append(ridge)
159
+ picture.frame = bounds
160
+ picture.lineWidth = 1.5 * scale
161
+ picture.path = frame.cgPath.copy(using: &transform)
162
+ let line = UIBezierPath()
163
+ line.move(to: CGPoint(x: 3, y: 3))
164
+ line.addLine(to: CGPoint(x: 21, y: 21))
165
+ slash.frame = bounds
166
+ slash.lineWidth = 1.5 * scale
167
+ slash.path = line.cgPath.copy(using: &transform)
168
+ let band = UIBezierPath()
169
+ band.move(to: CGPoint(x: 2.6, y: -0.6))
170
+ band.addLine(to: CGPoint(x: 24.6, y: 21.4))
171
+ band.addLine(to: CGPoint(x: 21.4, y: 24.6))
172
+ band.addLine(to: CGPoint(x: -0.6, y: 2.6))
173
+ band.close()
174
+ let cut = UIBezierPath(rect: bounds)
175
+ if let bandPath = band.cgPath.copy(using: &transform) { cut.append(UIBezierPath(cgPath: bandPath)) }
176
+ pictureCut.frame = bounds
177
+ pictureCut.path = cut.cgPath
178
+ }
179
+ }
180
+
181
+ private extension UIColor {
182
+ var cgAlpha: CGFloat { cgColor.alpha }
183
+ }
184
+
185
+ func nativeListIsDark(_ color: UIColor) -> Bool {
186
+ var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
187
+ guard color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return false }
188
+ return red * 299 + green * 587 + blue * 114 < 500
189
+ }
@@ -11,7 +11,7 @@ final class NativeListMediaTileCell: NativeListRendererCell {
11
11
  private let picture = UIView()
12
12
  private let image = NativeListMediaPreviewSlot()
13
13
  private let network = NativeListImageSlot()
14
- private let errorIcon = NativeListIconImageView()
14
+ private let placeholderView = NativeListMediaPlaceholderView()
15
15
  private let title = NativeListTextLabel()
16
16
  private let subtitle = NativeListTextLabel()
17
17
  private let badge = NativeListTextLabel()
@@ -50,7 +50,7 @@ final class NativeListMediaTileCell: NativeListRendererCell {
50
50
  closeStack.addArrangedSubview(close)
51
51
  [picture, metadata, closeStack].forEach(root.addArrangedSubview)
52
52
  picture.translatesAutoresizingMaskIntoConstraints = false
53
- [image.view, errorIcon, badge].forEach {
53
+ [image.view, placeholderView, badge].forEach {
54
54
  picture.addSubview($0)
55
55
  $0.translatesAutoresizingMaskIntoConstraints = false
56
56
  }
@@ -60,17 +60,16 @@ final class NativeListMediaTileCell: NativeListRendererCell {
60
60
  image.view.leadingAnchor.constraint(equalTo: picture.leadingAnchor),
61
61
  image.view.topAnchor.constraint(equalTo: picture.topAnchor),
62
62
  image.view.heightAnchor.constraint(equalTo: picture.heightAnchor), imageWidth, imageHeight,
63
- errorIcon.centerXAnchor.constraint(equalTo: image.view.centerXAnchor),
64
- errorIcon.centerYAnchor.constraint(equalTo: image.view.centerYAnchor),
65
- errorIcon.widthAnchor.constraint(equalToConstant: 24),
66
- errorIcon.heightAnchor.constraint(equalToConstant: 24),
63
+ placeholderView.leadingAnchor.constraint(equalTo: image.view.leadingAnchor),
64
+ placeholderView.trailingAnchor.constraint(equalTo: image.view.trailingAnchor),
65
+ placeholderView.topAnchor.constraint(equalTo: image.view.topAnchor),
66
+ placeholderView.bottomAnchor.constraint(equalTo: image.view.bottomAnchor),
67
67
  badge.trailingAnchor.constraint(equalTo: image.view.trailingAnchor),
68
68
  badge.bottomAnchor.constraint(equalTo: image.view.bottomAnchor),
69
69
  badge.heightAnchor.constraint(equalToConstant: 24),
70
70
  network.view.widthAnchor.constraint(equalToConstant: 14),
71
71
  network.view.heightAnchor.constraint(equalToConstant: 14),
72
72
  ])
73
- errorIcon.contentMode = .scaleAspectFit
74
73
  badge.textAlignment = .center
75
74
  badge.layer.cornerRadius = 10
76
75
  badge.layer.borderWidth = 2
@@ -87,8 +86,6 @@ final class NativeListMediaTileCell: NativeListRendererCell {
87
86
  _ item: NativeListItem, theme: [String: Any]?, layout: String,
88
87
  checkboxState: (NativeListItem, NativeSelectionTarget?, String) -> String
89
88
  ) {
90
- let iconUpdate = NativeListIconUpdate(self)
91
- defer { iconUpdate.finish() }
92
89
 
93
90
  let style = item.data.dictionary("style") ?? [:]
94
91
  imageStyle = style.dictionary("image") ?? [:]
@@ -124,9 +121,7 @@ final class NativeListMediaTileCell: NativeListRendererCell {
124
121
  badge.layer.borderColor = nativeListColor(theme, "rowBackground", "#FFFFFF").cgColor
125
122
  let state = item.data.string("imageState")
126
123
  let placeholder = theme?.string("strongBackground", default: "#0000000F") ?? "#0000000F"
127
- errorIcon.isHidden = state != "error"
128
- errorIcon.bindIcon("ImageSquareWavesOutline")
129
- errorIcon.tintColor = nativeListColor(theme, "disabledText", "#8C8C8C")
124
+ placeholderView.applyTheme(theme)
130
125
  let media = item.data.dictionary("media")
131
126
  if state != "empty", state != "error", let source = media?.dictionary("source") ?? item.data.dictionary("image") {
132
127
  // Legacy source-backed media had a transparent container. Clear only a fill this
@@ -135,11 +130,13 @@ final class NativeListMediaTileCell: NativeListRendererCell {
135
130
  image.view.backgroundColor = .clear
136
131
  ownsImageFill = false
137
132
  }
133
+ // Set before binding: a cached result completes synchronously inside bind.
134
+ placeholderView.setState(.loading)
138
135
  image.bind(
139
136
  source, key: "\(item.key):media", fit: imageStyle["contentFit"] as? String,
140
137
  placeholder: placeholder, probeOrder: media?["probeOrder"] as? [String] ?? ["image"]
141
138
  ) { [weak self] loaded in
142
- self?.errorIcon.isHidden = loaded
139
+ self?.placeholderView.setState(loaded ? .hidden : .failed)
143
140
  self?.ownsImageFill = !loaded
144
141
  self?.image.view.backgroundColor = loaded ? .clear : UIColor(nativeListHex: placeholder, fallback: .lightGray)
145
142
  }
@@ -147,6 +144,7 @@ final class NativeListMediaTileCell: NativeListRendererCell {
147
144
  image.recycle()
148
145
  image.view.backgroundColor =
149
146
  state == "error" ? nativeListColor(theme, "strongBackground", "#0000000F") : .clear
147
+ placeholderView.setState(state == "error" ? .failed : .hidden)
150
148
  ownsImageFill = true
151
149
  }
152
150
  if let source = item.data.dictionary("networkImage") {
@@ -184,6 +182,7 @@ final class NativeListMediaTileCell: NativeListRendererCell {
184
182
  default: shape == "circle"
185
183
  ? Double(min(width, imageHeight.constant) / 2) : shape == "square" ? 0 : 10))
186
184
  image.view.clipsToBounds = true
185
+ placeholderView.layer.cornerRadius = image.view.layer.cornerRadius
187
186
  super.layoutSubviews()
188
187
  }
189
188
  @objc private func closePressed() {
@@ -191,6 +190,7 @@ final class NativeListMediaTileCell: NativeListRendererCell {
191
190
  }
192
191
  override func recycleContent() {
193
192
  image.recycle()
193
+ placeholderView.setState(.hidden)
194
194
  network.recycle()
195
195
  closeKey = ""
196
196
  picture.alpha = 1
@@ -29,10 +29,7 @@ struct NativeListResolvedText {
29
29
  let requestedLines = style.int("lines", default: lines)
30
30
  self.lines = requestedLines == 0 ? 0 : min(3, max(1, requestedLines))
31
31
  explicitTruncation = style["lines"] != nil || style["truncate"] != nil
32
- text =
33
- self.lines == 1 && explicitTruncation
34
- ? value.replacingOccurrences(of: "\r\n|[\r\n]", with: " ", options: .regularExpression)
35
- : value
32
+ text = self.lines == 1 && explicitTruncation ? Self.foldingLineBreaks(value) : value
36
33
  let resolvedWeight: NativeListFontWeight
37
34
  switch style.string("fontWeight") {
38
35
  case "regular": resolvedWeight = .regular
@@ -59,6 +56,20 @@ struct NativeListResolvedText {
59
56
  offsetY = CGFloat(style.double("offsetY"))
60
57
  }
61
58
 
59
+ private static func foldingLineBreaks(_ value: String) -> String {
60
+ value.replacingOccurrences(of: "\r\n|[\r\n]", with: " ", options: .regularExpression)
61
+ }
62
+
63
+ /// UTF-16 offset in `text` for an offset into the caller's `source`, kept
64
+ /// within the text. A one-line label folds each line break into one space,
65
+ /// which moves every offset after a CRLF.
66
+ func displayOffset(_ offset: Int, in source: String) -> Int {
67
+ let units = source as NSString
68
+ let clamped = min(max(offset, 0), units.length)
69
+ guard lines == 1, explicitTruncation else { return clamped }
70
+ return (Self.foldingLineBreaks(units.substring(to: clamped)) as NSString).length
71
+ }
72
+
62
73
  /// Start/end follow the host view's layout direction, as legacy `marketTextAlignment` did.
63
74
  func alignment(for direction: UIUserInterfaceLayoutDirection) -> NSTextAlignment {
64
75
  guard let alignmentName else { return .natural }
@@ -3,6 +3,112 @@ import UIKit
3
3
  class NativeListTextLabel: UILabel {
4
4
  var rowVerticalAlignment: String? { didSet { setNeedsDisplay() } }
5
5
  var rowOffsetY: CGFloat = 0 { didSet { setNeedsDisplay() } }
6
+ /// UTF-16 offset the touchable text starts at. `nil` keeps the label's own
7
+ /// hit testing, its whole bounds. With an offset only the drawn text from
8
+ /// there on takes touches, plus a small slop, so text before the offset and
9
+ /// the unused width of a stretched label fall through to the row behind it:
10
+ /// `0` covers all of the text, the text length leaves nothing to touch.
11
+ var touchableTextStart: Int?
12
+ private static let touchSlop = CGSize(width: 8, height: 6)
13
+
14
+ /// One rect per laid-out run of touchable text, in label coordinates. The
15
+ /// label's own layout is not public, so the runs come from a text container
16
+ /// with the label's width, line cap and truncation. A line holds one run, or
17
+ /// several where mixed-direction text puts plain text between touchable text.
18
+ var touchableTextRegions: [CGRect] {
19
+ guard let start = touchableTextStart, let attributed = attributedText, attributed.length > start,
20
+ bounds.width > 0
21
+ else { return [] }
22
+ let storage = NSTextStorage(attributedString: attributed)
23
+ let manager = NSLayoutManager()
24
+ let container = NSTextContainer(
25
+ size: CGSize(width: bounds.width, height: .greatestFiniteMagnitude))
26
+ container.lineFragmentPadding = 0
27
+ container.maximumNumberOfLines = numberOfLines
28
+ container.lineBreakMode = lineBreakMode
29
+ manager.addTextContainer(container)
30
+ storage.addLayoutManager(manager)
31
+ let glyphs = manager.glyphRange(for: container)
32
+ // Mirrors drawText: the text is centered unless the row aligns it.
33
+ let textHeight = manager.usedRect(for: container).height
34
+ var originY = (bounds.height - textHeight) / 2
35
+ if let alignment = rowVerticalAlignment {
36
+ originY = alignment == "top" ? 0 : alignment == "bottom" ? bounds.height - textHeight : originY
37
+ }
38
+ originY += rowOffsetY
39
+ var lines: [CGRect] = []
40
+ var visibleEnd = attributed.length
41
+ manager.enumerateLineFragments(forGlyphRange: glyphs) { _, usedRect, _, lineGlyphs, _ in
42
+ lines.append(usedRect)
43
+ let truncated = manager.truncatedGlyphRange(inLineFragmentForGlyphAt: lineGlyphs.location)
44
+ if truncated.location != NSNotFound {
45
+ visibleEnd = min(visibleEnd, manager.characterIndexForGlyph(at: truncated.location))
46
+ }
47
+ }
48
+ // Truncation can hide the touchable text altogether. The ellipsis then
49
+ // stands for plain text as well, so nothing is left to touch.
50
+ guard start < visibleEnd else { return [] }
51
+ // The layout engine's own rects for a character range: one per line and
52
+ // per visual run, which is what makes mixed-direction text come out right.
53
+ func runs(_ characters: NSRange) -> [CGRect] {
54
+ let range = NSIntersectionRange(
55
+ manager.glyphRange(forCharacterRange: characters, actualCharacterRange: nil), glyphs)
56
+ guard range.length > 0 else { return [] }
57
+ var rects: [CGRect] = []
58
+ manager.enumerateEnclosingRects(
59
+ forGlyphRange: range, withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0),
60
+ in: container
61
+ ) { rect, _ in
62
+ // A run that continues on the next line is reported up to the
63
+ // container edge; its text ends where the line's used rect does.
64
+ guard let used = lines.first(where: { $0.minY <= rect.midY && rect.midY < $0.maxY })
65
+ else { return }
66
+ let minX = max(rect.minX, used.minX)
67
+ let maxX = min(rect.maxX, used.maxX)
68
+ if maxX > minX {
69
+ rects.append(CGRect(x: minX, y: rect.minY, width: maxX - minX, height: rect.height))
70
+ }
71
+ }
72
+ return rects
73
+ }
74
+ let plain = runs(NSRange(location: 0, length: start))
75
+ return runs(NSRange(location: start, length: attributed.length - start)).map { run in
76
+ // The slop reaches into blank space only. Sideways it stops at plain
77
+ // text on the same line, so text before the start never takes the
78
+ // touch, however narrow it is.
79
+ var minX = run.minX - Self.touchSlop.width
80
+ var maxX = run.maxX + Self.touchSlop.width
81
+ for other in plain where other.minY < run.midY && run.midY < other.maxY {
82
+ if other.maxX <= run.minX + 0.5 { minX = max(minX, other.maxX) }
83
+ if other.minX >= run.maxX - 0.5 { maxX = min(maxX, other.minX) }
84
+ }
85
+ // Vertically it grows only past the first and last line of the whole
86
+ // layout, so it never reaches into another line.
87
+ let line = lines.firstIndex { $0.minY <= run.midY && run.midY < $0.maxY }
88
+ let top = line == 0 ? Self.touchSlop.height : 0
89
+ let bottom = line == lines.count - 1 ? Self.touchSlop.height : 0
90
+ return CGRect(
91
+ x: minX, y: run.minY + originY - top, width: maxX - minX,
92
+ height: run.height + top + bottom)
93
+ }
94
+ }
95
+
96
+ override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
97
+ guard touchableTextStart != nil else { return super.point(inside: point, with: event) }
98
+ return touchableTextRegions.contains { $0.contains(point) }
99
+ }
100
+
101
+ // Assistive activation taps this point; the label's center can be blank.
102
+ override var accessibilityActivationPoint: CGPoint {
103
+ get {
104
+ guard let region = touchableTextRegions.first else {
105
+ return super.accessibilityActivationPoint
106
+ }
107
+ let target = UIAccessibility.convertToScreenCoordinates(region.intersection(bounds), in: self)
108
+ return CGPoint(x: target.midX, y: target.midY)
109
+ }
110
+ set { super.accessibilityActivationPoint = newValue }
111
+ }
6
112
 
7
113
  override func drawText(in rect: CGRect) {
8
114
  var target = rect
@@ -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
@@ -295,6 +297,10 @@ final class NativeListView: UIView {
295
297
  host.addSubview(view)
296
298
  reactContainerSlots.insert((view, host), at: min(index, reactContainerSlots.count))
297
299
  collectionView.addSubview(host)
300
+ if index == 0 {
301
+ currentHeaderRoot = view
302
+ if !containerHeaderHeightIsAuthoritative { updatePendingHeaderHeight() }
303
+ }
298
304
  layoutContainerSlots()
299
305
  setNeedsLayout()
300
306
  }
@@ -306,12 +312,17 @@ final class NativeListView: UIView {
306
312
  updateTopScrollEdge()
307
313
  return
308
314
  }
315
+ let removedCurrentHeader = currentHeaderRoot === view
316
+ if removedCurrentHeader { currentHeaderRoot = nil }
309
317
  reactContainerSlots.removeAll { slot in
310
318
  guard slot.content === view else { return false }
311
319
  view.removeFromSuperview()
312
320
  slot.host.removeFromSuperview()
313
321
  return true
314
322
  }
323
+ if removedCurrentHeader && !containerHeaderHeightIsAuthoritative {
324
+ updatePendingHeaderHeight()
325
+ }
315
326
  }
316
327
 
317
328
  func setTopScrollEdge(effect: NativeListTopScrollEdgeEffect, overlayHeight: CGFloat) {
@@ -376,12 +387,37 @@ final class NativeListView: UIView {
376
387
 
377
388
  func setContainerSlotHeightsJson(_ json: String, followedBySnapshot: Bool = false) {
378
389
  guard let data = json.data(using: .utf8),
379
- let heights = try? JSONSerialization.jsonObject(with: data) as? [Double],
380
- (heights.count == 4 || heights.count == 6),
390
+ var values = try? JSONSerialization.jsonObject(with: data) as? [Any],
391
+ (values.count == 4 || values.count == 6) else { return }
392
+ let headerPending = values[0] is NSNull
393
+ if headerPending { values[0] = 0.0 }
394
+ guard let heights = values as? [Double],
381
395
  heights.allSatisfy({ $0.isFinite && $0 >= 0 }) else { return }
396
+ containerHeaderHeightIsAuthoritative = !headerPending
397
+ var next = heights.map { CGFloat($0) } + (heights.count == 4 ? [0, 0] : [])
398
+ if headerPending { next[0] = pendingHeaderHeight() }
399
+ applyContainerSlotHeights(next, followedBySnapshot: followedBySnapshot)
400
+ }
401
+
402
+ private func pendingHeaderHeight() -> CGFloat {
403
+ guard let bounds = currentHeaderRoot?.bounds,
404
+ bounds.width.isFinite, bounds.width > 0,
405
+ bounds.height.isFinite, bounds.height >= 0 else { return 0 }
406
+ return ceil(bounds.height)
407
+ }
408
+
409
+ private func updatePendingHeaderHeight() {
410
+ let height = pendingHeaderHeight()
411
+ guard height != containerSlotHeights[0] else { return }
412
+ var next = containerSlotHeights
413
+ next[0] = height
414
+ applyContainerSlotHeights(next)
415
+ }
416
+
417
+ private func applyContainerSlotHeights(_ heights: [CGFloat], followedBySnapshot: Bool = false) {
382
418
  let previousHeights = containerSlotHeights
383
- let footerDelta = containerSlotHeights[2] - CGFloat(heights[2])
384
- containerSlotHeights = heights.map { CGFloat($0) } + (heights.count == 4 ? [0, 0] : [])
419
+ let footerDelta = containerSlotHeights[2] - heights[2]
420
+ containerSlotHeights = heights
385
421
  let contentHeightChanged = previousHeights[4] != containerSlotHeights[4]
386
422
  let toggleHeightChanged = previousHeights[5] != containerSlotHeights[5]
387
423
  let disclosureGeometryInvalid = structuralTail != nil && config?.disclosure != nil
@@ -937,6 +973,7 @@ final class NativeListView: UIView {
937
973
  guard !disposed,
938
974
  window != nil,
939
975
  collectionView.delegate === self,
976
+ flowLayout.scrollDirection == .vertical,
940
977
  collectionView.bounds.width > 0,
941
978
  collectionView.bounds.height > 0 else { return }
942
979
  NotificationCenter.default.post(
@@ -971,11 +1008,11 @@ final class NativeListView: UIView {
971
1008
  configureLayout(config)
972
1009
  if lastLayoutDirection != direction { rebindRowsForLayoutDirection(config) }
973
1010
  }
974
- performPendingScrollIfNeeded()
975
- layoutContainerSlots()
976
1011
  if !hadUsableBounds && collectionView.bounds.width > 0 && collectionView.bounds.height > 0 {
977
1012
  notifyPagerScrollViewReadyIfNeeded()
978
1013
  }
1014
+ performPendingScrollIfNeeded()
1015
+ layoutContainerSlots()
979
1016
  }
980
1017
 
981
1018
  // A layout-direction change may arrive without a layout pass (semantic attribute or trait).
@@ -1653,6 +1690,7 @@ final class NativeListView: UIView {
1653
1690
  requestScroll(.index(index, animated, alignment, viewPosition, viewOffset))
1654
1691
  }
1655
1692
 
1693
+ @objc(onekeyScrollToOffset:animated:)
1656
1694
  func scrollToOffset(_ offset: Double, animated: Bool) {
1657
1695
  requestScroll(.offset(offset, animated))
1658
1696
  }
@@ -3084,6 +3122,9 @@ final class NativeListView: UIView {
3084
3122
  dataSource = nil
3085
3123
 
3086
3124
  config = nil
3125
+ currentHeaderRoot = nil
3126
+ containerHeaderHeightIsAuthoritative = false
3127
+ containerSlotHeights[0] = 0
3087
3128
  acceptedRowIndex = nil
3088
3129
  pagerStickyHeights.removeAllObjects()
3089
3130
  for slot in reactContainerSlots { slot.host.layer.mask = nil }
@@ -3573,7 +3614,9 @@ final class NativeListFlowLayout: UICollectionViewFlowLayout {
3573
3614
  guard scrollDirection == .horizontal, let collectionView else { return }
3574
3615
 
3575
3616
  var nextX = sectionInset.left
3576
- let itemCount = collectionView.numberOfItems(inSection: 0)
3617
+ let itemCount = collectionView.numberOfSections > 0
3618
+ ? collectionView.numberOfItems(inSection: 0)
3619
+ : 0
3577
3620
  for item in 0..<itemCount {
3578
3621
  let indexPath = IndexPath(item: item, section: 0)
3579
3622
  guard let attributes = super.layoutAttributesForItem(at: indexPath)?.copy()