@onekeyfe/react-native-native-list 6.7.0-alpha.466 → 6.8.0-2

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 (42) 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/NativeListMediaPlaceholderView.kt +244 -0
  4. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPreviewSlot.kt +66 -31
  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/NativeListResolvedText.kt +5 -1
  8. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +75 -0
  9. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +25 -19
  10. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt +153 -0
  11. package/docs/ROW_TEMPLATES.md +8 -3
  12. package/docs/SPEC.md +258 -18
  13. package/docs/STYLE_SPEC.md +12 -0
  14. package/ios/NativeListActivityDetailsView.swift +13 -5
  15. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  16. package/ios/NativeListMediaPreviewSlot.swift +122 -61
  17. package/ios/NativeListMediaTileRenderer.swift +13 -13
  18. package/ios/NativeListResolvedText.swift +15 -4
  19. package/ios/NativeListTextLabel.swift +106 -0
  20. package/ios/RNCNativeListView.swift +50 -7
  21. package/ios/tests/NativeListActivityPresentationTests.swift +270 -0
  22. package/ios/tests/NativeListLifecycleTests.swift +176 -16
  23. package/ios/tests/NativeListMediaVisibilityTests.swift +41 -7
  24. package/lib/module/NativeList.js +17 -4
  25. package/lib/module/NativeList.web.js +3 -1
  26. package/lib/module/validation.js +19 -2
  27. package/lib/module/web/NativeListWebEngine.js +13 -11
  28. package/lib/module/web/templates/ActivityRowRenderer.js +29 -23
  29. package/lib/module/web/templates/DataRowRenderer.js +16 -0
  30. package/lib/module/web/templates/IdentityRowRenderer.js +3 -1
  31. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -15
  32. package/lib/typescript/src/models.d.ts +9 -1
  33. package/package.json +1 -1
  34. package/src/NativeList.tsx +25 -4
  35. package/src/NativeList.web.tsx +1 -1
  36. package/src/models.ts +9 -0
  37. package/src/validation.ts +34 -0
  38. package/src/web/NativeListWebEngine.ts +16 -11
  39. package/src/web/templates/ActivityRowRenderer.ts +42 -32
  40. package/src/web/templates/DataRowRenderer.ts +28 -0
  41. package/src/web/templates/IdentityRowRenderer.ts +3 -3
  42. package/src/web/templates/MediaTileRowRenderer.ts +90 -15
@@ -1,4 +1,5 @@
1
1
  import AVFoundation
2
+ import OneKeyImage
2
3
  import UIKit
3
4
 
4
5
  private final class NativeListPausedVideoView: UIView {
@@ -17,6 +18,18 @@ final class NativeListMediaPreviewSlot {
17
18
  private let image = NativeListImageSlot()
18
19
  private let video = NativeListPausedVideoView()
19
20
  private let frameView = UIImageView()
21
+ private final class PendingFrame {
22
+ private let lock = NSLock()
23
+ private var buffer: CVPixelBuffer?
24
+ init(_ buffer: CVPixelBuffer) { self.buffer = buffer }
25
+ func take() -> CVPixelBuffer? { lock.lock(); defer { lock.unlock() }; let value = buffer; buffer = nil; return value }
26
+ func cancel() { lock.lock(); buffer = nil; lock.unlock() }
27
+ }
28
+ private var pendingFrame: PendingFrame?
29
+ private var requestedEdge: Int?
30
+ private var subscription: OneKeyMediaPreviewCache.Subscription?
31
+ private var extractionLease: UUID?
32
+ private static let frameWorker = DispatchQueue(label: "onekey.native-list.frame", qos: .userInitiated)
20
33
  private var videoOutput: AVPlayerItemVideoOutput?
21
34
  private static let frameContext = CIContext(options: [.cacheIntermediates: false])
22
35
  private static let frameCaptureAttempts = 6
@@ -26,6 +39,7 @@ final class NativeListMediaPreviewSlot {
26
39
  private var playerGeneration = 0
27
40
  private var result: Bool?
28
41
  private var completion: ((Bool) -> Void)?
42
+ private(set) var createdPlayerCount = 0
29
43
  private var player: AVPlayer?
30
44
  private var itemObservation: NSKeyValueObservation?
31
45
  private var readyObservation: NSKeyValueObservation?
@@ -49,7 +63,7 @@ final class NativeListMediaPreviewSlot {
49
63
  video.onWindowChanged = { [weak self] in self?.observeViewport(); self?.updateVisibility() }
50
64
  video.onLayoutChanged = { [weak self] in self?.updateVisibility() }
51
65
  lifecycleObservers = [
52
- NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.releasePlayer() },
66
+ NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.cancelPreview() },
53
67
  NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.updateVisibility() },
54
68
  ]
55
69
  }
@@ -87,7 +101,7 @@ final class NativeListMediaPreviewSlot {
87
101
  let candidate = candidateGeneration
88
102
  resumeVideo = nil
89
103
  viewportObservations.removeAll()
90
- releasePlayer()
104
+ cancelPreview()
91
105
  guard attempt < order.count else {
92
106
  result = false
93
107
  completion?(false)
@@ -113,81 +127,108 @@ final class NativeListMediaPreviewSlot {
113
127
  image.view.isHidden = true
114
128
  video.isHidden = false
115
129
  guard let url = URL(string: source.string("uri")), !source.string("uri").isEmpty else { finished(false); return }
130
+ let headers = (source.dictionary("headers") ?? [:]).compactMapValues { $0 as? String }
131
+ let fitKey = coverFit(fit ?? source.string("contentFit"))
116
132
  resumeVideo = { [weak self] in
117
- guard let self, self.epoch == token, self.candidateGeneration == candidate, self.player == nil else { return }
118
- self.playerGeneration &+= 1
119
- let generation = self.playerGeneration
120
- let asset = AVURLAsset(url: url, options: ["AVURLAssetHTTPHeaderFieldsKey": source.dictionary("headers") ?? [:]])
121
- let item = AVPlayerItem(asset: asset)
122
- item.preferredForwardBufferDuration = 1
123
- let output = AVPlayerItemVideoOutput(pixelBufferAttributes: [
124
- kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
125
- ])
126
- item.add(output)
127
- self.videoOutput = output
128
- let player = AVPlayer(playerItem: item)
129
- player.isMuted = true
130
- player.pause()
131
- self.player = player
132
- self.video.playerLayer.player = player
133
- self.itemObservation = item.observe(\.status, options: [.initial, .new]) { [weak self] item, _ in
134
- DispatchQueue.main.async {
135
- guard let self, self.playerGeneration == generation else { return }
136
- if item.status == .failed { finished(false) }
137
- }
138
- }
139
- self.readyObservation = self.video.playerLayer.observe(\.isReadyForDisplay, options: [.initial, .new]) { [weak self] layer, _ in
140
- DispatchQueue.main.async {
141
- guard let self, self.playerGeneration == generation else { return }
142
- guard layer.isReadyForDisplay else { return }
133
+ guard let self, self.epoch == token, self.candidateGeneration == candidate,
134
+ self.subscription == nil, self.frameView.image == nil, !self.video.bounds.isEmpty else { return }
135
+ let edge = OneKeyMediaPreviewCache.targetEdge(max(self.video.bounds.width, self.video.bounds.height) * (self.video.window?.screen.scale ?? 1))
136
+ self.requestedEdge = edge
137
+ self.subscription = OneKeyMediaPreviewCache.shared.request(uri: url.absoluteString, headers: headers,
138
+ edge: edge, fit: fitKey, policy: source.string("cachePolicy", default: "memory-disk"),
139
+ onImage: { [weak self] still in
140
+ guard let self, self.epoch == token, self.candidateGeneration == candidate else { return }
141
+ self.subscription = nil
142
+ self.frameView.image = still; self.frameView.isHidden = false
143
+ self.viewportObservations.removeAll()
143
144
  finished(true)
144
- self.captureFirstFrame(generation: generation, attemptsLeft: Self.frameCaptureAttempts)
145
- }
146
- }
145
+ }, onExtract: { [weak self] lease in
146
+ guard let self, self.epoch == token, self.candidateGeneration == candidate else { return }
147
+ self.extractionLease = lease
148
+ self.updateVisibility()
149
+ guard self.extractionLease == lease, self.requestedEdge == edge else { return }
150
+ self.startPlayer(url: url, headers: headers, edge: edge, lease: lease)
151
+ }, onRevoked: { [weak self] in
152
+ self?.extractionLease = nil; self?.pendingFrame?.cancel(); self?.pendingFrame = nil; self?.releasePlayer()
153
+ },
154
+ onFailure: { [weak self] in
155
+ guard let self, self.epoch == token, self.candidateGeneration == candidate else { return }
156
+ self.subscription = nil; finished(false)
157
+ })
147
158
  }
148
159
  observeViewport()
149
160
  updateVisibility()
150
161
  }
151
162
 
152
- /// A paused item may not have handed its preroll frame to the output yet, so copying retries
153
- /// on later runloop turns. If no frame arrives the paused player stays attached.
154
- private func captureFirstFrame(generation: Int, attemptsLeft: Int) {
163
+ private func coverFit(_ fit: String) -> String { fit == "cover" ? "cover" : "contain" }
164
+
165
+ private func startPlayer(url: URL, headers: [String: String], edge: Int, lease: UUID) {
166
+ createdPlayerCount += 1
167
+ self.playerGeneration &+= 1
168
+ let generation = self.playerGeneration
169
+ let asset = AVURLAsset(url: url, options: ["AVURLAssetHTTPHeaderFieldsKey": headers])
170
+ let item = AVPlayerItem(asset: asset)
171
+ item.preferredForwardBufferDuration = 1
172
+ let output = AVPlayerItemVideoOutput(pixelBufferAttributes: [
173
+ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
174
+ ])
175
+ item.add(output)
176
+ self.videoOutput = output
177
+ let player = AVPlayer(playerItem: item)
178
+ player.isMuted = true
179
+ player.pause()
180
+ self.player = player
181
+ self.video.playerLayer.player = player
182
+ self.itemObservation = item.observe(\.status, options: [.initial, .new]) { [weak self] item, _ in
183
+ DispatchQueue.main.async {
184
+ guard let self, self.playerGeneration == generation else { return }
185
+ if item.status == .failed { OneKeyMediaPreviewCache.shared.fail(lease) }
186
+ }
187
+ }
188
+ self.readyObservation = self.video.playerLayer.observe(\.isReadyForDisplay, options: [.initial, .new]) { [weak self] layer, _ in
189
+ DispatchQueue.main.async {
190
+ guard let self, self.playerGeneration == generation, layer.isReadyForDisplay else { return }
191
+ self.readyObservation = nil
192
+ self.captureFirstFrame(generation: generation, attemptsLeft: Self.frameCaptureAttempts, edge: edge, lease: lease)
193
+ }
194
+ }
195
+ }
196
+
197
+ /// Capture only the buffer on UI; CI normalizes orientation and size on a worker.
198
+ private func captureFirstFrame(generation: Int, attemptsLeft: Int, edge: Int, lease: UUID) {
155
199
  guard playerGeneration == generation, let player, let item = player.currentItem, let output = videoOutput else { return }
156
200
  let time = item.currentTime()
157
- if let buffer = output.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil),
158
- let still = Self.frameContext.createCGImage(CIImage(cvPixelBuffer: buffer), from: CGRect(
159
- x: 0, y: 0, width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer))) {
160
- let transform = item.tracks.lazy.compactMap(\.assetTrack).first { $0.mediaType == .video }?.preferredTransform
161
- frameView.image = UIImage(cgImage: still, scale: 1, orientation: Self.orientation(transform))
162
- frameView.isHidden = false
163
- resumeVideo = nil
164
- viewportObservations.removeAll()
201
+ if let buffer = output.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil) {
202
+ let transform = item.tracks.lazy.compactMap(\.assetTrack).first { $0.mediaType == .video }?.preferredTransform ?? .identity
165
203
  releasePlayer()
204
+ let pending = PendingFrame(buffer)
205
+ pendingFrame = pending
206
+ Self.frameWorker.async { [weak self] in
207
+ guard let buffer = pending.take() else { return }
208
+ var image = CIImage(cvPixelBuffer: buffer).transformed(by: transform)
209
+ let origin = image.extent.origin
210
+ image = image.transformed(by: CGAffineTransform(translationX: -origin.x, y: -origin.y))
211
+ let scale = min(1, CGFloat(edge) / max(image.extent.width, image.extent.height))
212
+ image = image.transformed(by: CGAffineTransform(scaleX: scale, y: scale))
213
+ let still = Self.frameContext.createCGImage(image, from: image.extent).map { UIImage(cgImage: $0) }
214
+ DispatchQueue.main.async {
215
+ guard let self, self.extractionLease == lease else { return }
216
+ if let still { OneKeyMediaPreviewCache.shared.complete(lease, image: still) }
217
+ else { OneKeyMediaPreviewCache.shared.fail(lease) }
218
+ }
219
+ }
166
220
  return
167
221
  }
168
- guard attemptsLeft > 1 else { return }
169
- // An exact seek re-delivers the paused preroll frame to newly attached outputs.
170
- if attemptsLeft == Self.frameCaptureAttempts {
171
- player.seek(to: time, toleranceBefore: .zero, toleranceAfter: .zero)
172
- }
222
+ guard attemptsLeft > 1 else { OneKeyMediaPreviewCache.shared.fail(lease); return }
223
+ if attemptsLeft == Self.frameCaptureAttempts { player.seek(to: time, toleranceBefore: .zero, toleranceAfter: .zero) }
173
224
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
174
- self?.captureFirstFrame(generation: generation, attemptsLeft: attemptsLeft - 1)
175
- }
176
- }
177
-
178
- private static func orientation(_ transform: CGAffineTransform?) -> UIImage.Orientation {
179
- guard let transform else { return .up }
180
- switch (transform.a, transform.b, transform.c, transform.d) {
181
- case (0, 1, -1, 0): return .right
182
- case (0, -1, 1, 0): return .left
183
- case (-1, 0, 0, -1): return .down
184
- default: return .up
225
+ self?.captureFirstFrame(generation: generation, attemptsLeft: attemptsLeft - 1, edge: edge, lease: lease)
185
226
  }
186
227
  }
187
228
 
188
229
  private func observeViewport() {
189
230
  viewportObservations.removeAll()
190
- guard resumeVideo != nil, video.window != nil else { return }
231
+ guard resumeVideo != nil, frameView.image == nil, video.window != nil else { return }
191
232
  var ancestor = video.superview
192
233
  while let current = ancestor {
193
234
  if let scrollView = current as? UIScrollView {
@@ -223,8 +264,24 @@ final class NativeListMediaPreviewSlot {
223
264
  }
224
265
 
225
266
  private func updateVisibility() {
267
+ if let requestedEdge, let window = video.window, !video.bounds.isEmpty {
268
+ let edge = OneKeyMediaPreviewCache.targetEdge(max(video.bounds.width, video.bounds.height) * window.screen.scale)
269
+ if edge != requestedEdge {
270
+ cancelPreview(); self.requestedEdge = nil
271
+ frameView.image = nil; frameView.isHidden = true; result = nil
272
+ observeViewport()
273
+ }
274
+ }
226
275
  if Self.intersectsViewport(video) && UIApplication.shared.applicationState == .active { resumeVideo?() }
227
- else { releasePlayer() }
276
+ else { cancelPreview() }
277
+ }
278
+ private func cancelPreview() {
279
+ let previous = subscription
280
+ subscription = nil
281
+ OneKeyMediaPreviewCache.shared.cancel(previous)
282
+ extractionLease = nil
283
+ pendingFrame?.cancel(); pendingFrame = nil
284
+ releasePlayer()
228
285
  }
229
286
  private func releasePlayer() {
230
287
  playerGeneration &+= 1
@@ -241,10 +298,11 @@ final class NativeListMediaPreviewSlot {
241
298
  candidateGeneration &+= 1
242
299
  resumeVideo = nil
243
300
  viewportObservations.removeAll()
244
- releasePlayer()
301
+ cancelPreview()
245
302
  image.recycle()
246
303
  image.view.isHidden = false
247
304
  video.isHidden = true
305
+ requestedEdge = nil
248
306
  frameView.image = nil
249
307
  frameView.isHidden = true
250
308
  identity = nil
@@ -252,6 +310,9 @@ final class NativeListMediaPreviewSlot {
252
310
  completion = nil
253
311
  }
254
312
  deinit {
313
+ pendingFrame?.cancel()
314
+ let pending = subscription
315
+ DispatchQueue.main.async { OneKeyMediaPreviewCache.shared.cancel(pending) }
255
316
  lifecycleObservers.forEach(NotificationCenter.default.removeObserver)
256
317
  player?.pause()
257
318
  player?.replaceCurrentItem(with: nil)
@@ -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()