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

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.
package/docs/SPEC.md CHANGED
@@ -210,6 +210,96 @@ and Web acceptance must cover narrow addresses, dynamic type/fonts, long press
210
210
  versus tap, keyboard interaction, and the horizontal warning border. Source or
211
211
  build success alone is not runtime evidence.
212
212
 
213
+ ### Identity title segments and leading title icon
214
+
215
+ Status: implemented in source for iOS, Android and Web; device and Web runtime
216
+ acceptance is pending. These fields travel in snapshot/patch JSON and do not
217
+ change the Nitro ABI. They serve recipient rows whose title is a wallet and an
218
+ account name in two styles, and address book rows marked by an icon before the
219
+ name.
220
+
221
+ `identity.titleSegments` is an optional list of 1...4 runs drawn on the title
222
+ line in place of `title`:
223
+
224
+ ```ts
225
+ titleSegments?: readonly {
226
+ text: string;
227
+ tone?: 'primary' | 'secondary';
228
+ fontWeight?: 'regular' | 'medium';
229
+ shrink?: boolean;
230
+ maxWidthRatio?: number; // (0, 1]
231
+ }[];
232
+ ```
233
+
234
+ - `title` stays required. It is the spoken label and the fallback text, so it
235
+ carries the same words as the runs; every renderer exposes `title`, not the
236
+ runs, to accessibility.
237
+ - Each run uses the title's font family, size and line height, including
238
+ `style.title` and the configured fonts. `tone` picks the primary or secondary
239
+ text color and defaults to the title color; `fontWeight` picks the weight and
240
+ defaults to the title weight.
241
+ - The runs share one line. `titleLines` and `style.title.lines` do not apply
242
+ to them; a row that draws `title` instead (it has `titleMatch`, or is a wallet
243
+ sidebar row) keeps them for drawing and for measurement.
244
+ - Layout. The runs take the whole width the title line leaves after the
245
+ leading title icon and the title accessories (title icon, title image,
246
+ suffixes, badges), so those accessories sit at the line's end rather than
247
+ right after the text. W is that width:
248
+ 1. A run's base width is its natural width, capped at `maxWidthRatio x W`
249
+ when given. A run longer than its cap truncates at the cap with a tail
250
+ ellipsis.
251
+ 2. At most one run sets `shrink: true`. Every other run keeps its base width.
252
+ 3. The shrinking run gets `min(base, W - sum of the other runs)` and
253
+ truncates with a tail ellipsis; it may shrink to zero width.
254
+ 4. When the runs that do not shrink exceed W on their own, the line is cut at
255
+ its end. Native renderers end the last visible run with an ellipsis; Web
256
+ clips it. This divergence is accepted: callers avoid the case with
257
+ `maxWidthRatio`.
258
+ - Development validation rejects an empty or oversized list, blank or
259
+ oversized text (the 4096-code-unit text bound), unknown keys, tones or
260
+ weights, a ratio outside `(0, 1]`, more than one shrinking run, `titleMatch`
261
+ on the same row (its ranges index `title`), and
262
+ `presentation: 'walletSidebar'`. Production treats the runs as decoration:
263
+ an invalid list is dropped and the row shows `title`. Renderers draw `title`
264
+ instead of runs on a row that also has `titleMatch`, and ignore runs and the
265
+ leading icon with `presentation: 'walletSidebar'`.
266
+
267
+ `identity.titleLeadingIcon` is an optional `{ name, tintColor?,
268
+ accessibilityLabel? }`: a 16-point glyph before the title text or its runs,
269
+ with a 6-point gap, vertically centered on the title line. It keeps its 16
270
+ points: a long title, or its shrinking run, truncates first. The name comes from
271
+ the same closed icon set as `titleIcon`; an unmapped name leaves an empty
272
+ 16-point slot. `tintColor` is a hex `#RRGGBB` or `#RRGGBBAA` color and defaults
273
+ to the theme's `iconSubdued`. Without `accessibilityLabel` the glyph is hidden
274
+ from accessibility. It has no action of its own. Development validation
275
+ rejects unknown keys, a blank name, a malformed color and
276
+ `presentation: 'walletSidebar'`; production drops an invalid icon.
277
+
278
+ Both fields are identity patch fields. Omission in a full snapshot removes
279
+ them; omission in a patch keeps the current value. Rebind and recycle remove the
280
+ previous runs and glyph, so a row without them never shows another row's.
281
+
282
+ | Platform | Title runs | Leading icon |
283
+ | --- | --- | --- |
284
+ | iOS | `NativeListTitleSegmentsLabel` draws the runs at the widths that `NativeListTitleSegmentLayout.swift` allocates for its bounds; it fills the title row in place of the row's filler. | `NativeListIconImageView`, first in the title row stack. A plain title beside it drops below required horizontal compression resistance, as beside `titleIcon`, so the title truncates before the glyph narrows. |
285
+ | Android | `NativeListTitleSegmentsView`, a `TextView` whose text is rebuilt for each measured width from `NativeListTitleSegmentLayout.kt` and which measures to the width it is offered. `PackedTitleLineLayout.titleChild` names the flexible title view, so a view may precede it. | `OneKeyIconView`, first in the title line. |
286
+ | Web | A flex line that fills the title line: the shrinking run is `flex: 0 1 auto; min-width: 0`, the others `flex: 0 0 auto` with a `max-width` percentage for a cap. | An icon element before the title text. |
287
+
288
+ Conformance: `src/validation.ts` (`assertTitleSegments`,
289
+ `assertTitleLeadingIcon`, production sanitizing) with `validation.test.ts`;
290
+ `src/web/templates/IdentityRowRenderer.ts` with `IdentityTitleRunsWeb.test.ts`
291
+ (run styles, flex behavior, accessibility, rebind);
292
+ `ios/NativeListTitleSegmentLayout.swift` (run widths, and when the runs and the
293
+ glyph show) with the SwiftPM `NativeListTitleSegmentLayoutTests`; the iOS
294
+ leading glyph beside a long plain title, wallet sidebar rows and the measured
295
+ height of a highlighted title with the XCTest
296
+ `NativeListIdentityTitleIconLayoutTests`; `NativeListTitleSegmentLayout.kt`
297
+ with the JVM `NativeListTitleSegmentLayoutTest`. iOS, Android and Web runtime acceptance is pending: recipient rows
298
+ with long wallet and account names in both truncation directions, narrow rows,
299
+ dark mode, dynamic type and configured fonts, and recycling between rows with
300
+ and without runs or a leading icon. Source and build success alone are not
301
+ runtime evidence.
302
+
213
303
  ### DeFi position row controls
214
304
 
215
305
  Status: implemented in local source, unreleased. Focused validation and Web
@@ -1296,6 +1386,76 @@ disposal. Unit checks prove transition semantics, not rendered behavior.
1296
1386
 
1297
1387
  ## Native media preview probing
1298
1388
 
1389
+ ### Persistent first-frame revision — Source implemented; scoped iOS validation
1390
+
1391
+ This revision supersedes the cell-only frame retention, unbounded visible-player
1392
+ count and copy-failure retained-player behavior described in the baseline below.
1393
+ Image owns the native-only preview cache and extraction coordinator defined in
1394
+ its SPEC §6.3; NativeList retains the paused/muted player and view lifecycle.
1395
+ No public descriptor, JavaScript API or Web renderer behavior changes.
1396
+
1397
+ On reaching the video candidate, a visible slot queries permitted decoded memory
1398
+ and then disk before requesting extraction. A hit displays the still frame and
1399
+ creates no AVPlayer/ExoPlayer. Normal image candidates retain their original
1400
+ precedence and image cache; a video-cache hit MUST NOT bypass an earlier image
1401
+ candidate. Cache identity excludes row key and includes URI, canonical headers,
1402
+ bounded pixel tier, schema and capture fit. Recycle drops cell state, not the
1403
+ shared cached frame. Fit, orientation, black/transparent platform letterbox and
1404
+ row-owned tap behavior match a newly captured frame.
1405
+
1406
+ The media descriptor exposes URI, explicit headers, dimensions, fit and cache
1407
+ policy, with no cookie/session management API. Preview identity does not track
1408
+ ambient cookie sessions or automatically invalidate on cookie changes; media
1409
+ that requires that behavior is outside the supported preview-cache contract.
1410
+ Existing AVPlayer/Media3 networking and cookie handling remain unchanged. The
1411
+ cache does not promise that underlying network requests are cookie-free.
1412
+ Detaching an iOS view with no window MUST preserve its last pixel tier and captured
1413
+ still; only a real attached-window scale/layout change can invalidate that tier.
1414
+
1415
+ Slots subscribe only while visible, attached and foreground eligible. They
1416
+ cancel on invisibility, detach, background, recycle or identity/size change and
1417
+ release any owned player immediately. A same-key visible peer may take over;
1418
+ old owner, binding, candidate and player generations cannot attach a frame or
1419
+ complete a newer request. At most two flights extract concurrently, bounded by
1420
+ Image's queue and 10-second grant deadline. The existing six short copy attempts
1421
+ may run, but exhaustion now releases the player and advances/fails the candidate
1422
+ instead of retaining a paused player indefinitely. Success is emitted after a
1423
+ valid still exists, not solely when the player reports its first rendered frame.
1424
+ No failed extraction is cached. Disk-write failure still permits a successful
1425
+ still to display. A cached or newly copied still releases player and viewport
1426
+ observers, and ordinary text-only rebinding retains the current presentation.
1427
+
1428
+ The cache dimensions use actual view pixel size, capped to a 1024-pixel long edge
1429
+ and 1,048,576 pixels with source aspect ratio preserved. Empty layout defers work.
1430
+ iOS retains the CVPixelBuffer for bounded background CI conversion rather than
1431
+ building a full-resolution UIImage on the UI thread. Android performs a bounded
1432
+ TextureView copy on the UI thread and background encoding; its cached presentation
1433
+ must restore the aspect-ratio container after reuse. Source headers and URL/query
1434
+ text are not written into cache filenames, metadata or logs.
1435
+
1436
+ The production iOS video slot passed 14 simulator checks with a real H.264 MP4,
1437
+ including cold capture/player release, cross-cell/recycled memory reuse, disk
1438
+ reuse after memory clear and a layout-tier resize. Its harness substitutes only
1439
+ the unused image-candidate host; image-to-video fallback and full-app integration
1440
+ were not exercised. Android runtime and physical-device performance remain
1441
+ pending. The complete acceptance matrix adds warm cross-cell/recycled hits with
1442
+ zero new players, disk hits after memory clear and process restart, same-source
1443
+ deduplication, owner cancellation/transfer, concurrency and timeout bounds,
1444
+ clear-generation races, corrupt entry repair and all existing probing/lifecycle
1445
+ cases. Native tests and simulator evidence cannot establish device FPS or memory
1446
+ improvement; those require workload-specific measurements on target devices.
1447
+
1448
+ The final Android slot, including deferred Media3 error release, compiled in the
1449
+ consumer's normal native build and final incremental APK. Matching SDK/consumer
1450
+ source hashes and APK provenance were checked, and the App visibly started on
1451
+ the isolated emulator. This is build/startup acceptance, not Android video-frame
1452
+ or complete Home NFT route acceptance. A temporary Home probe lacked account
1453
+ context; a later diagnostic Dialog had an unexplained black capture. Neither is
1454
+ recorded as a passing NFT visual case. Further scrolling, frame-cache and
1455
+ memory/performance measurements are outside this PR's recorded acceptance scope.
1456
+
1457
+ ### Baseline before the persistent first-frame revision
1458
+
1299
1459
  Status: Source implemented; native runtime acceptance pending. `mediaTile.media`
1300
1460
  is an opt-in native-only preview descriptor: `{ source: ImageSource, probeOrder:
1301
1461
  ('image' | 'video')[] }`. The order contains one or two distinct candidates.
@@ -635,6 +635,11 @@ the list's general section mechanism.
635
635
  | Reorder preview | no | — | — | r12, shadow `0 4px 24px` |
636
636
  | Reorder count badge | no | 24 h, r12, 12 semibold | dp(24), r dp(12), sp(12) semibold | 24px, r12, 12/22/600 |
637
637
 
638
+ Pinned section headers draw no separator or shadow on any platform. The pinned
639
+ overlay paints the header's own row background, which is what hides the rows
640
+ scrolling underneath it; a list that wants a visible boundary supplies it through
641
+ the header row's style, not through container chrome.
642
+
638
643
  The section index rail is three separate constant sets for one control; Android's
639
644
  `sectionIndexDp()` deliberately never follows the source-scale switch.
640
645
 
@@ -49,6 +49,12 @@ final class NativeListIdentityCell: NativeListRendererCell {
49
49
  stack.spacing = 10
50
50
  }
51
51
  }
52
+ private class func showsTitleRuns(_ item: NativeListItem) -> Bool {
53
+ nativeListShowsTitleRuns(
54
+ presentation: item.data.string("presentation"),
55
+ runCount: item.data.dictionaries("titleSegments").count,
56
+ matchCount: item.data.dictionaries("titleMatch").count)
57
+ }
52
58
  override class func measure(
53
59
  _ item: NativeListItem, width: CGFloat, theme: [String: Any]?, layout: String,
54
60
  fonts: NativeListFontFamilies
@@ -81,7 +87,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
81
87
  let title = NativeListResolvedText(
82
88
  item.data.string("title"), style: style.dictionary("title"), size: 16,
83
89
  weight: .medium, color: .black, lineHeight: 24,
84
- lines: item.data.int("titleLines", default: 1), fonts: fonts)
90
+ lines: showsTitleRuns(item) ? 1 : item.data.int("titleLines", default: 1), fonts: fonts)
85
91
  let subtitle = NativeListResolvedText(
86
92
  item.data.string("subtitle"), style: style.dictionary("subtitle"), size: 14,
87
93
  color: .black, lineHeight: 20,
@@ -110,6 +116,12 @@ final class NativeListIdentityCell: NativeListRendererCell {
110
116
  private let titleRowStack = UIStackView()
111
117
  private let titleLabel = NativeListTextLabel()
112
118
  private let titleIconView = NativeListIconImageView()
119
+ private let titleLeadingIconView = NativeListIconImageView()
120
+ private let titleSegmentsLabel = NativeListTitleSegmentsLabel()
121
+ // Runs, when shown, take the title's place in the title row.
122
+ private var visibleTitleView: UIView {
123
+ titleSegmentsLabel.isHidden ? titleLabel : titleSegmentsLabel
124
+ }
113
125
  private var titleImageSlot: NativeListImageSlot?
114
126
  private var titleImageConstraints: [NSLayoutConstraint] = []
115
127
  // Absorbs the title row's slack so the title keeps its intrinsic width and the
@@ -170,7 +182,9 @@ final class NativeListIdentityCell: NativeListRendererCell {
170
182
  mainStack.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
171
183
  titleRowStack.axis = .horizontal
172
184
  titleRowStack.alignment = .center
185
+ titleRowStack.addArrangedSubview(titleLeadingIconView)
173
186
  titleRowStack.addArrangedSubview(titleLabel)
187
+ titleRowStack.addArrangedSubview(titleSegmentsLabel)
174
188
  titleRowStack.addArrangedSubview(titleIconView)
175
189
  titleRowStack.addArrangedSubview(badgeLabel)
176
190
  titleRowStack.addArrangedSubview(titleRowFiller)
@@ -185,6 +199,18 @@ final class NativeListIdentityCell: NativeListRendererCell {
185
199
  ])
186
200
  titleIconView.contentMode = .scaleAspectFit
187
201
  titleIconView.setContentHuggingPriority(.required, for: .horizontal)
202
+ titleLeadingIconView.translatesAutoresizingMaskIntoConstraints = false
203
+ let leadingIconWidth = titleLeadingIconView.widthAnchor.constraint(equalToConstant: 16)
204
+ leadingIconWidth.priority = UILayoutPriority(999)
205
+ NSLayoutConstraint.activate([
206
+ leadingIconWidth,
207
+ titleLeadingIconView.heightAnchor.constraint(equalToConstant: 16),
208
+ ])
209
+ titleLeadingIconView.contentMode = .scaleAspectFit
210
+ titleLeadingIconView.setContentHuggingPriority(.required, for: .horizontal)
211
+ titleLeadingIconView.setContentCompressionResistancePriority(.required, for: .horizontal)
212
+ titleLeadingIconView.isHidden = true
213
+ titleSegmentsLabel.isHidden = true
188
214
  [titleRowStack, subtitleLabel, tertiaryLabel].forEach(mainStack.addArrangedSubview)
189
215
  visual.translatesAutoresizingMaskIntoConstraints = false
190
216
  leadingWidth = visual.widthAnchor.constraint(equalToConstant: 40)
@@ -249,6 +275,15 @@ final class NativeListIdentityCell: NativeListRendererCell {
249
275
  titleIconView.isHidden = true
250
276
  titleIconView.accessibilityLabel = nil
251
277
  titleIconView.isAccessibilityElement = false
278
+ titleLeadingIconView.image = nil
279
+ titleLeadingIconView.isHidden = true
280
+ titleLeadingIconView.accessibilityLabel = nil
281
+ titleLeadingIconView.isAccessibilityElement = false
282
+ titleSegmentsLabel.isHidden = true
283
+ titleSegmentsLabel.reset()
284
+ titleRowFiller.isHidden = false
285
+ titleSegmentsLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
286
+ titleSegmentsLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
252
287
  titleImageSlot?.view.isHidden = true
253
288
  titleImageSlot?.view.accessibilityLabel = nil
254
289
  titleImageSlot?.view.isAccessibilityElement = false
@@ -310,7 +345,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
310
345
  let label = titleIcon.string("accessibilityLabel")
311
346
  titleIconView.accessibilityLabel = label.isEmpty ? nil : label
312
347
  titleIconView.isAccessibilityElement = !label.isEmpty
313
- titleRowStack.setCustomSpacing(4, after: titleLabel)
348
+ titleRowStack.setCustomSpacing(4, after: visibleTitleView)
314
349
  // A long title truncates ahead of the 20pt glyph (Android caps the title
315
350
  // at row width minus accessories, Web shrinks the title first); with the
316
351
  // title at `.required` the icon's 999 width constraint collapsed to 0.
@@ -342,7 +377,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
342
377
  ]
343
378
  titleImageConstraints.forEach { $0.priority = UILayoutPriority(999) }
344
379
  NSLayoutConstraint.activate(titleImageConstraints)
345
- titleRowStack.setCustomSpacing(4, after: titleIconView.isHidden ? titleLabel : titleIconView)
380
+ titleRowStack.setCustomSpacing(4, after: titleIconView.isHidden ? visibleTitleView : titleIconView)
346
381
  titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
347
382
  slot.bind(image, key: "\(item.key):titleImage", placeholder: "#00000000")
348
383
  } else {
@@ -385,7 +420,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
385
420
  titleRowStack.setCustomSpacing(
386
421
  CGFloat(style.double("titleBadgeGap")),
387
422
  after: titleImageSlot?.view.isHidden == false ? titleImageSlot!.view
388
- : titleIconView.isHidden ? titleLabel : titleIconView)
423
+ : titleIconView.isHidden ? visibleTitleView : titleIconView)
389
424
  }
390
425
  }
391
426
  if style["trailingGap"] != nil { trailingStack.spacing = CGFloat(style.double("trailingGap")) }
@@ -399,6 +434,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
399
434
  labels.forEach { NativeListTextStyles.applyStyledText($0, text, fonts: fonts) }
400
435
  }
401
436
  }
437
+ if !titleSegmentsLabel.isHidden { bindTitleRuns(item, theme: theme, style: style) }
402
438
  contentInsets = UIEdgeInsets(
403
439
  top: topInset, left: leftInset, bottom: -bottomInset, right: -rightInset)
404
440
  if root.axis == .horizontal {
@@ -464,6 +500,8 @@ final class NativeListIdentityCell: NativeListRendererCell {
464
500
  }
465
501
  override func recycleContent() {
466
502
  visual.recycle()
503
+ titleSegmentsLabel.reset()
504
+ titleLeadingIconView.image = nil
467
505
  titleImageSlot?.recycle()
468
506
  titleImageSlot?.view.isHidden = true
469
507
  titleImageSlot?.view.accessibilityLabel = nil
@@ -512,6 +550,30 @@ final class NativeListIdentityCell: NativeListRendererCell {
512
550
  visual.bind(
513
551
  descriptor, style: image, key: key, theme: currentTheme, isUnread: false, fonts: fonts)
514
552
  }
553
+ // Runs take the title's font, size and color unless they set their own tone
554
+ // or weight; the title label holds the final style by now.
555
+ private func bindTitleRuns(_ item: NativeListItem, theme: [String: Any]?, style: [String: Any]) {
556
+ let baseFont = titleLabel.font ?? nativeListFont(ofSize: 16, weight: .medium, fonts: fonts)
557
+ let baseColor = titleLabel.textColor ?? nativeListColor(theme, "primaryText", "#202020")
558
+ let runs = item.data.dictionaries("titleSegments").map { segment in
559
+ let weight = segment.string("fontWeight")
560
+ let tone = segment.string("tone")
561
+ return NativeListTitleSegmentsLabel.Run(
562
+ text: segment.string("text"),
563
+ font: weight.isEmpty
564
+ ? baseFont
565
+ : nativeListFont(
566
+ ofSize: baseFont.pointSize, weight: weight == "medium" ? .medium : .regular, fonts: fonts),
567
+ color: tone == "secondary"
568
+ ? nativeListColor(theme, "secondaryText", "#646464")
569
+ : tone == "primary" ? nativeListColor(theme, "primaryText", "#202020") : baseColor,
570
+ shrink: segment.bool("shrink"),
571
+ maxWidthRatio: (segment["maxWidthRatio"] as? NSNumber).map { CGFloat(truncating: $0) })
572
+ }
573
+ titleSegmentsLabel.lineHeight = CGFloat(
574
+ style.dictionary("title")?.double("lineHeight", default: 24) ?? 24)
575
+ titleSegmentsLabel.configure(runs, spokenText: item.data.string("title"))
576
+ }
515
577
  private func bindIdentity(
516
578
  _ item: NativeListItem,
517
579
  theme: [String: Any]?,
@@ -643,10 +705,36 @@ final class NativeListIdentityCell: NativeListRendererCell {
643
705
  }
644
706
  root.addArrangedSubview(mainStack)
645
707
  show(titleLabel, item.data.string("title"), lines: item.data.int("titleLines", default: 1))
708
+ // Runs replace the drawn title except where `title` itself is highlighted;
709
+ // their content is bound once the title style is final.
710
+ if Self.showsTitleRuns(item) {
711
+ titleLabel.isHidden = true
712
+ titleSegmentsLabel.isHidden = false
713
+ // The runs fill what the title row leaves, so a ratio is a share of it.
714
+ titleRowFiller.isHidden = true
715
+ titleSegmentsLabel.setContentHuggingPriority(UILayoutPriority(1), for: .horizontal)
716
+ }
717
+ if nativeListAllowsTitleDecorations(presentation: item.data.string("presentation")),
718
+ let icon = item.data.dictionary("titleLeadingIcon")
719
+ {
720
+ titleLeadingIconView.bindIcon(icon.string("name"))
721
+ titleLeadingIconView.tintColor = UIColor(
722
+ nativeListHex: icon.string("tintColor",
723
+ default: theme?["iconSubdued"] as? String ?? "#8D8D8D"),
724
+ fallback: .gray)
725
+ titleLeadingIconView.isHidden = false
726
+ let label = icon.string("accessibilityLabel")
727
+ titleLeadingIconView.accessibilityLabel = label.isEmpty ? nil : label
728
+ titleLeadingIconView.isAccessibilityElement = !label.isEmpty
729
+ titleRowStack.setCustomSpacing(6, after: titleLeadingIconView)
730
+ // As beside `titleIcon`: a plain title left at `.required` collapses the
731
+ // glyph's 999 width constraint instead of truncating.
732
+ titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
733
+ }
646
734
  let titleSuffixes = item.data.dictionaries("titleSuffixes")
647
735
  if !titleSuffixes.isEmpty {
648
- titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
649
- let minimumTitleWidth = titleLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 80)
736
+ visibleTitleView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
737
+ let minimumTitleWidth = visibleTitleView.widthAnchor.constraint(greaterThanOrEqualToConstant: 80)
650
738
  minimumTitleWidth.priority = UILayoutPriority(751)
651
739
  minimumTitleWidth.isActive = true
652
740
  selectorConstraints.append(minimumTitleWidth)
@@ -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)