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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +312 -379
  2. package/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +15 -6
  3. package/android/src/main/java/com/onekey/nativelist/NativeListIdentityRenderer.kt +3 -87
  4. package/android/src/main/java/com/onekey/nativelist/NativeListMediaPlaceholderView.kt +244 -0
  5. package/android/src/main/java/com/onekey/nativelist/NativeListMediaTileRenderer.kt +32 -11
  6. package/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +60 -0
  7. package/android/src/main/java/com/onekey/nativelist/NativeListPrimitives.kt +3 -6
  8. package/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +5 -1
  9. package/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +75 -0
  10. package/android/src/main/java/com/onekey/nativelist/NativeListView.kt +25 -19
  11. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt +153 -0
  12. package/docs/ROW_TEMPLATES.md +12 -12
  13. package/docs/SPEC.md +226 -110
  14. package/docs/STYLE_SPEC.md +7 -0
  15. package/ios/NativeListActivityDetailsView.swift +13 -5
  16. package/ios/NativeListIdentityRenderer.swift +6 -94
  17. package/ios/NativeListMediaPlaceholderView.swift +189 -0
  18. package/ios/NativeListMediaTileRenderer.swift +13 -13
  19. package/ios/NativeListResolvedText.swift +15 -4
  20. package/ios/NativeListTextLabel.swift +106 -0
  21. package/ios/RNCNativeListView.swift +129 -32
  22. package/ios/tests/NativeListActivityPresentationTests.swift +270 -0
  23. package/ios/tests/NativeListIdentityTitleIconLayoutTests.swift +0 -95
  24. package/ios/tests/NativeListLifecycleTests.swift +369 -40
  25. package/ios/tests/NativeListMediaVisibilityTests.swift +16 -7
  26. package/lib/module/NativeList.js +17 -4
  27. package/lib/module/NativeList.web.js +3 -1
  28. package/lib/module/models.js +0 -2
  29. package/lib/module/validation.js +54 -71
  30. package/lib/module/web/NativeListGeneratedIcons.js +1 -0
  31. package/lib/module/web/NativeListWebEngine.js +13 -11
  32. package/lib/module/web/templates/ActivityRowRenderer.js +29 -23
  33. package/lib/module/web/templates/DataRowRenderer.js +54 -1
  34. package/lib/module/web/templates/IdentityRowRenderer.js +3 -92
  35. package/lib/module/web/templates/MediaTileRowRenderer.js +84 -15
  36. package/lib/typescript/src/models.d.ts +19 -22
  37. package/package.json +1 -1
  38. package/scripts/generate-icons.test.mjs +1 -0
  39. package/scripts/native-list-icons.json +1 -1
  40. package/src/NativeList.tsx +25 -4
  41. package/src/NativeList.web.tsx +1 -1
  42. package/src/models.ts +18 -23
  43. package/src/validation.ts +89 -113
  44. package/src/web/NativeListGeneratedIcons.ts +1 -0
  45. package/src/web/NativeListWebEngine.ts +16 -11
  46. package/src/web/templates/ActivityRowRenderer.ts +42 -32
  47. package/src/web/templates/DataRowRenderer.ts +76 -1
  48. package/src/web/templates/IdentityRowRenderer.ts +3 -141
  49. package/src/web/templates/MediaTileRowRenderer.ts +90 -15
  50. package/android/src/main/java/com/onekey/nativelist/NativeListTitleSegmentLayout.kt +0 -49
  51. package/android/src/main/java/com/onekey/nativelist/NativeListTitleSegmentsView.kt +0 -105
  52. package/android/src/test/java/com/margelo/nitro/nativelist/NativeListTitleSegmentLayoutTest.kt +0 -80
  53. package/ios/NativeListTitleSegmentLayout.swift +0 -45
  54. package/ios/NativeListTitleSegmentsLabel.swift +0 -80
@@ -49,12 +49,6 @@ 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
- }
58
52
  override class func measure(
59
53
  _ item: NativeListItem, width: CGFloat, theme: [String: Any]?, layout: String,
60
54
  fonts: NativeListFontFamilies
@@ -87,7 +81,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
87
81
  let title = NativeListResolvedText(
88
82
  item.data.string("title"), style: style.dictionary("title"), size: 16,
89
83
  weight: .medium, color: .black, lineHeight: 24,
90
- lines: showsTitleRuns(item) ? 1 : item.data.int("titleLines", default: 1), fonts: fonts)
84
+ lines: item.data.int("titleLines", default: 1), fonts: fonts)
91
85
  let subtitle = NativeListResolvedText(
92
86
  item.data.string("subtitle"), style: style.dictionary("subtitle"), size: 14,
93
87
  color: .black, lineHeight: 20,
@@ -116,12 +110,6 @@ final class NativeListIdentityCell: NativeListRendererCell {
116
110
  private let titleRowStack = UIStackView()
117
111
  private let titleLabel = NativeListTextLabel()
118
112
  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
- }
125
113
  private var titleImageSlot: NativeListImageSlot?
126
114
  private var titleImageConstraints: [NSLayoutConstraint] = []
127
115
  // Absorbs the title row's slack so the title keeps its intrinsic width and the
@@ -182,9 +170,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
182
170
  mainStack.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
183
171
  titleRowStack.axis = .horizontal
184
172
  titleRowStack.alignment = .center
185
- titleRowStack.addArrangedSubview(titleLeadingIconView)
186
173
  titleRowStack.addArrangedSubview(titleLabel)
187
- titleRowStack.addArrangedSubview(titleSegmentsLabel)
188
174
  titleRowStack.addArrangedSubview(titleIconView)
189
175
  titleRowStack.addArrangedSubview(badgeLabel)
190
176
  titleRowStack.addArrangedSubview(titleRowFiller)
@@ -199,18 +185,6 @@ final class NativeListIdentityCell: NativeListRendererCell {
199
185
  ])
200
186
  titleIconView.contentMode = .scaleAspectFit
201
187
  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
214
188
  [titleRowStack, subtitleLabel, tertiaryLabel].forEach(mainStack.addArrangedSubview)
215
189
  visual.translatesAutoresizingMaskIntoConstraints = false
216
190
  leadingWidth = visual.widthAnchor.constraint(equalToConstant: 40)
@@ -275,15 +249,6 @@ final class NativeListIdentityCell: NativeListRendererCell {
275
249
  titleIconView.isHidden = true
276
250
  titleIconView.accessibilityLabel = nil
277
251
  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)
287
252
  titleImageSlot?.view.isHidden = true
288
253
  titleImageSlot?.view.accessibilityLabel = nil
289
254
  titleImageSlot?.view.isAccessibilityElement = false
@@ -345,7 +310,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
345
310
  let label = titleIcon.string("accessibilityLabel")
346
311
  titleIconView.accessibilityLabel = label.isEmpty ? nil : label
347
312
  titleIconView.isAccessibilityElement = !label.isEmpty
348
- titleRowStack.setCustomSpacing(4, after: visibleTitleView)
313
+ titleRowStack.setCustomSpacing(4, after: titleLabel)
349
314
  // A long title truncates ahead of the 20pt glyph (Android caps the title
350
315
  // at row width minus accessories, Web shrinks the title first); with the
351
316
  // title at `.required` the icon's 999 width constraint collapsed to 0.
@@ -377,7 +342,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
377
342
  ]
378
343
  titleImageConstraints.forEach { $0.priority = UILayoutPriority(999) }
379
344
  NSLayoutConstraint.activate(titleImageConstraints)
380
- titleRowStack.setCustomSpacing(4, after: titleIconView.isHidden ? visibleTitleView : titleIconView)
345
+ titleRowStack.setCustomSpacing(4, after: titleIconView.isHidden ? titleLabel : titleIconView)
381
346
  titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
382
347
  slot.bind(image, key: "\(item.key):titleImage", placeholder: "#00000000")
383
348
  } else {
@@ -420,7 +385,7 @@ final class NativeListIdentityCell: NativeListRendererCell {
420
385
  titleRowStack.setCustomSpacing(
421
386
  CGFloat(style.double("titleBadgeGap")),
422
387
  after: titleImageSlot?.view.isHidden == false ? titleImageSlot!.view
423
- : titleIconView.isHidden ? visibleTitleView : titleIconView)
388
+ : titleIconView.isHidden ? titleLabel : titleIconView)
424
389
  }
425
390
  }
426
391
  if style["trailingGap"] != nil { trailingStack.spacing = CGFloat(style.double("trailingGap")) }
@@ -434,7 +399,6 @@ final class NativeListIdentityCell: NativeListRendererCell {
434
399
  labels.forEach { NativeListTextStyles.applyStyledText($0, text, fonts: fonts) }
435
400
  }
436
401
  }
437
- if !titleSegmentsLabel.isHidden { bindTitleRuns(item, theme: theme, style: style) }
438
402
  contentInsets = UIEdgeInsets(
439
403
  top: topInset, left: leftInset, bottom: -bottomInset, right: -rightInset)
440
404
  if root.axis == .horizontal {
@@ -500,8 +464,6 @@ final class NativeListIdentityCell: NativeListRendererCell {
500
464
  }
501
465
  override func recycleContent() {
502
466
  visual.recycle()
503
- titleSegmentsLabel.reset()
504
- titleLeadingIconView.image = nil
505
467
  titleImageSlot?.recycle()
506
468
  titleImageSlot?.view.isHidden = true
507
469
  titleImageSlot?.view.accessibilityLabel = nil
@@ -550,30 +512,6 @@ final class NativeListIdentityCell: NativeListRendererCell {
550
512
  visual.bind(
551
513
  descriptor, style: image, key: key, theme: currentTheme, isUnread: false, fonts: fonts)
552
514
  }
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
- }
577
515
  private func bindIdentity(
578
516
  _ item: NativeListItem,
579
517
  theme: [String: Any]?,
@@ -705,36 +643,10 @@ final class NativeListIdentityCell: NativeListRendererCell {
705
643
  }
706
644
  root.addArrangedSubview(mainStack)
707
645
  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
- }
734
646
  let titleSuffixes = item.data.dictionaries("titleSuffixes")
735
647
  if !titleSuffixes.isEmpty {
736
- visibleTitleView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
737
- let minimumTitleWidth = visibleTitleView.widthAnchor.constraint(greaterThanOrEqualToConstant: 80)
648
+ titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
649
+ let minimumTitleWidth = titleLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 80)
738
650
  minimumTitleWidth.priority = UILayoutPriority(751)
739
651
  minimumTitleWidth.isActive = true
740
652
  selectorConstraints.append(minimumTitleWidth)
@@ -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