@onekeyfe/react-native-native-overlay 6.7.0-alpha.466 → 6.8.0-10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +119 -21
  2. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayEntryRootView.kt +60 -0
  3. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayHost.kt +37 -5
  4. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayPackage.kt +1 -1
  5. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayPageHostView.kt +14 -3
  6. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastCardView.kt +869 -0
  7. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastSpec.kt +327 -0
  8. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterView.kt +574 -0
  9. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterViewManager.kt +54 -0
  10. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayView.kt +12 -0
  11. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayViewManager.kt +8 -0
  12. package/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayAccessibilityIsolationTest.kt +172 -0
  13. package/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayMotionTest.kt +42 -0
  14. package/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayPageHostLayoutTest.kt +58 -0
  15. package/android/src/test/java/com/onekey/nativeoverlay/NativeOverlaySheetInsetTest.kt +78 -0
  16. package/docs/SPEC.md +337 -33
  17. package/ios/NativeOverlayContainerView.swift +6 -0
  18. package/ios/NativeOverlayToastCardView.swift +572 -0
  19. package/ios/NativeOverlayToastSpec.swift +356 -0
  20. package/ios/NativeOverlayToasterView.swift +519 -0
  21. package/ios/NativeOverlayWindowManager.swift +244 -7
  22. package/ios/RCTNativeOverlayToasterComponentView.h +11 -0
  23. package/ios/RCTNativeOverlayToasterComponentView.mm +85 -0
  24. package/lib/module/NativeOverlayNativeComponent.ts +13 -0
  25. package/lib/module/NativeOverlayToasterNativeComponent.ts +24 -0
  26. package/lib/module/OverlayView.js +7 -1
  27. package/lib/module/OverlayView.js.map +1 -1
  28. package/lib/module/animation/anchoredOrigin.js +26 -0
  29. package/lib/module/animation/anchoredOrigin.js.map +1 -0
  30. package/lib/module/animation/resolveAnimation.js +26 -4
  31. package/lib/module/animation/resolveAnimation.js.map +1 -1
  32. package/lib/module/index.js +3 -0
  33. package/lib/module/index.js.map +1 -1
  34. package/lib/module/toast/OverlayToastHost.js +42 -0
  35. package/lib/module/toast/OverlayToastHost.js.map +1 -0
  36. package/lib/module/toast/OverlayToastHost.web.js +32 -0
  37. package/lib/module/toast/OverlayToastHost.web.js.map +1 -0
  38. package/lib/module/toast/OverlayToastStore.js +217 -0
  39. package/lib/module/toast/OverlayToastStore.js.map +1 -0
  40. package/lib/module/toast/toastBridge.js +65 -0
  41. package/lib/module/toast/toastBridge.js.map +1 -0
  42. package/lib/module/toast/toastDomContent.web.js +298 -0
  43. package/lib/module/toast/toastDomContent.web.js.map +1 -0
  44. package/lib/module/toast/toastDomRenderer.web.js +695 -0
  45. package/lib/module/toast/toastDomRenderer.web.js.map +1 -0
  46. package/lib/module/toast/toastStyles.web.js +97 -0
  47. package/lib/module/toast/toastStyles.web.js.map +1 -0
  48. package/lib/module/toast/types.js +2 -0
  49. package/lib/module/toast/types.js.map +1 -0
  50. package/lib/module/web/animateTransition.js +38 -12
  51. package/lib/module/web/animateTransition.js.map +1 -1
  52. package/lib/module/web/overlayLayers.js +5 -0
  53. package/lib/module/web/overlayLayers.js.map +1 -1
  54. package/lib/typescript/src/NativeOverlayNativeComponent.d.ts +13 -0
  55. package/lib/typescript/src/NativeOverlayNativeComponent.d.ts.map +1 -1
  56. package/lib/typescript/src/NativeOverlayToasterNativeComponent.d.ts +19 -0
  57. package/lib/typescript/src/NativeOverlayToasterNativeComponent.d.ts.map +1 -0
  58. package/lib/typescript/src/OverlayView.d.ts.map +1 -1
  59. package/lib/typescript/src/animation/anchoredOrigin.d.ts +7 -0
  60. package/lib/typescript/src/animation/anchoredOrigin.d.ts.map +1 -0
  61. package/lib/typescript/src/animation/resolveAnimation.d.ts +9 -3
  62. package/lib/typescript/src/animation/resolveAnimation.d.ts.map +1 -1
  63. package/lib/typescript/src/animation/types.d.ts +5 -1
  64. package/lib/typescript/src/animation/types.d.ts.map +1 -1
  65. package/lib/typescript/src/index.d.ts +5 -0
  66. package/lib/typescript/src/index.d.ts.map +1 -1
  67. package/lib/typescript/src/toast/OverlayToastHost.d.ts +6 -0
  68. package/lib/typescript/src/toast/OverlayToastHost.d.ts.map +1 -0
  69. package/lib/typescript/src/toast/OverlayToastHost.web.d.ts +6 -0
  70. package/lib/typescript/src/toast/OverlayToastHost.web.d.ts.map +1 -0
  71. package/lib/typescript/src/toast/OverlayToastStore.d.ts +47 -0
  72. package/lib/typescript/src/toast/OverlayToastStore.d.ts.map +1 -0
  73. package/lib/typescript/src/toast/toastBridge.d.ts +11 -0
  74. package/lib/typescript/src/toast/toastBridge.d.ts.map +1 -0
  75. package/lib/typescript/src/toast/toastDomContent.web.d.ts +15 -0
  76. package/lib/typescript/src/toast/toastDomContent.web.d.ts.map +1 -0
  77. package/lib/typescript/src/toast/toastDomRenderer.web.d.ts +8 -0
  78. package/lib/typescript/src/toast/toastDomRenderer.web.d.ts.map +1 -0
  79. package/lib/typescript/src/toast/toastStyles.web.d.ts +2 -0
  80. package/lib/typescript/src/toast/toastStyles.web.d.ts.map +1 -0
  81. package/lib/typescript/src/toast/types.d.ts +240 -0
  82. package/lib/typescript/src/toast/types.d.ts.map +1 -0
  83. package/lib/typescript/src/web/animateTransition.d.ts +12 -0
  84. package/lib/typescript/src/web/animateTransition.d.ts.map +1 -1
  85. package/lib/typescript/src/web/overlayLayers.d.ts.map +1 -1
  86. package/package.json +3 -2
  87. package/react-native.config.js +1 -0
  88. package/src/NativeOverlayNativeComponent.ts +13 -0
  89. package/src/NativeOverlayToasterNativeComponent.ts +24 -0
  90. package/src/OverlayView.tsx +7 -0
  91. package/src/animation/anchoredOrigin.ts +35 -0
  92. package/src/animation/resolveAnimation.ts +28 -7
  93. package/src/animation/types.ts +5 -1
  94. package/src/index.ts +24 -0
  95. package/src/toast/OverlayToastHost.tsx +62 -0
  96. package/src/toast/OverlayToastHost.web.tsx +29 -0
  97. package/src/toast/OverlayToastStore.ts +254 -0
  98. package/src/toast/toastBridge.ts +62 -0
  99. package/src/toast/toastDomContent.web.ts +351 -0
  100. package/src/toast/toastDomRenderer.web.ts +856 -0
  101. package/src/toast/toastStyles.web.ts +97 -0
  102. package/src/toast/types.ts +251 -0
  103. package/src/web/animateTransition.ts +54 -14
  104. package/src/web/overlayLayers.ts +7 -0
@@ -0,0 +1,572 @@
1
+ import ObjectiveC
2
+ import UIKit
3
+
4
+ // The card geometry of the layouts this replaces.
5
+ private enum ToastMetrics {
6
+ static let cardPaddingHorizontal: CGFloat = 16
7
+ static let cardPaddingVertical: CGFloat = 12
8
+ static let cardRadius: CGFloat = 8
9
+ static let messageIconGap: CGFloat = 8
10
+ static let messageTextGap: CGFloat = 4
11
+ static let notificationGap: CGFloat = 8
12
+ static let notificationTextGap: CGFloat = 2
13
+ static let actionsGap: CGFloat = 8
14
+ static let actionsPaddingTop: CGFloat = 12
15
+ static let actionsPaddingEnd: CGFloat = 2
16
+ static let actionsPaddingBottom: CGFloat = 2
17
+ }
18
+
19
+ private func pixelCeil(_ value: CGFloat) -> CGFloat {
20
+ let scale = UIScreen.main.scale
21
+ return ceil(value * scale) / scale
22
+ }
23
+
24
+ /// The text engine this replaces measured a text box one pixel taller than
25
+ /// its lines; every card height depends on it.
26
+ private var textBoxSlack: CGFloat { 1 / UIScreen.main.scale }
27
+
28
+ /// Named icons come from the image package's process-wide registry. It is
29
+ /// reached through the Objective-C runtime so this pod needs no dependency on
30
+ /// it; without the registry the icon stays blank.
31
+ private enum ToastNamedIcon {
32
+ private typealias Request = @convention(c) (
33
+ AnyClass, Selector, AnyObject, NSString, NSString, Int, Int, Double,
34
+ @escaping @convention(block) (UIImage?) -> Void
35
+ ) -> Void
36
+ private typealias Cancel = @convention(c) (AnyClass, Selector, AnyObject) -> Void
37
+
38
+ private static let bridge: AnyClass? =
39
+ NSClassFromString("OneKeyNamedSVGBridge") ?? NSClassFromString("OneKeyImage.OneKeyNamedSVGBridge")
40
+ private static let requestSelector =
41
+ NSSelectorFromString("requestWithOwner:name:color:width:height:scale:complete:")
42
+ private static let cancelSelector = NSSelectorFromString("cancelWithOwner:")
43
+
44
+ static func request(
45
+ owner: AnyObject, name: String, color: String, size: CGFloat, scale: CGFloat,
46
+ complete: @escaping (UIImage?) -> Void
47
+ ) {
48
+ guard let bridge, let method = class_getClassMethod(bridge, requestSelector) else {
49
+ complete(nil)
50
+ return
51
+ }
52
+ let pixels = Int(ceil(size * scale))
53
+ let call = unsafeBitCast(method_getImplementation(method), to: Request.self)
54
+ call(bridge, requestSelector, owner, name as NSString, color as NSString,
55
+ pixels, pixels, Double(scale), complete)
56
+ }
57
+
58
+ static func cancel(owner: AnyObject) {
59
+ guard let bridge, let method = class_getClassMethod(bridge, cancelSelector) else { return }
60
+ unsafeBitCast(method_getImplementation(method), to: Cancel.self)(bridge, cancelSelector, owner)
61
+ }
62
+ }
63
+
64
+ private final class ToastIconView: UIView {
65
+ private let imageView = UIImageView()
66
+ private var spinner: UIActivityIndicatorView?
67
+ private var task: URLSessionDataTask?
68
+ private var requested = false
69
+ let icon: NativeOverlayToastIcon
70
+
71
+ init(icon: NativeOverlayToastIcon) {
72
+ self.icon = icon
73
+ super.init(frame: CGRect(x: 0, y: 0, width: icon.size, height: icon.size))
74
+ isUserInteractionEnabled = false
75
+ imageView.frame = bounds
76
+ imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
77
+ imageView.contentMode = .scaleAspectFill
78
+ imageView.clipsToBounds = true
79
+ addSubview(imageView)
80
+ switch icon {
81
+ case let .spinner(color, _):
82
+ let indicator = UIActivityIndicatorView(style: .medium)
83
+ indicator.color = color
84
+ indicator.startAnimating()
85
+ indicator.center = CGPoint(x: bounds.midX, y: bounds.midY)
86
+ addSubview(indicator)
87
+ spinner = indicator
88
+ case let .image(uri, _, radius):
89
+ imageView.layer.cornerRadius = radius
90
+ load(uri)
91
+ case .named:
92
+ break
93
+ }
94
+ }
95
+
96
+ @available(*, unavailable)
97
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
98
+
99
+ deinit {
100
+ task?.cancel()
101
+ ToastNamedIcon.cancel(owner: self)
102
+ }
103
+
104
+ override func didMoveToWindow() {
105
+ super.didMoveToWindow()
106
+ guard !requested, let window, case let .named(name, colorString, color, size) = icon else { return }
107
+ requested = true
108
+ ToastNamedIcon.request(
109
+ owner: self, name: name, color: colorString, size: size, scale: window.screen.scale
110
+ ) { [weak self] image in
111
+ DispatchQueue.main.async {
112
+ // The registry hands back final-colour pixels; a template tint keeps
113
+ // single-colour glyphs crisp on any surface.
114
+ self?.imageView.tintColor = color
115
+ self?.imageView.image = image
116
+ }
117
+ }
118
+ }
119
+
120
+ private func load(_ uri: String) {
121
+ guard let url = URL(string: uri) else { return }
122
+ if url.scheme == "data" {
123
+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in
124
+ let image = (try? Data(contentsOf: url)).flatMap(UIImage.init(data:))
125
+ DispatchQueue.main.async { self?.imageView.image = image }
126
+ }
127
+ return
128
+ }
129
+ task = URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
130
+ let image = data.flatMap(UIImage.init(data:))
131
+ DispatchQueue.main.async { self?.imageView.image = image }
132
+ }
133
+ task?.resume()
134
+ }
135
+ }
136
+
137
+ /// A paragraph of styled runs, laid out and drawn with TextKit the way the
138
+ /// text engine this replaces did, so line boxes, glyph positions and
139
+ /// truncation match it. Link runs report taps through the `onLink` closure.
140
+ final class ToastTextLabel: UIView {
141
+ var onLink: ((String) -> Void)?
142
+ var onPress: (() -> Void)?
143
+ private var links: [(range: NSRange, link: String)] = []
144
+ private let storage = NSTextStorage()
145
+ private let layoutManager = NSLayoutManager()
146
+ private let container = NSTextContainer(size: .zero)
147
+
148
+ init(text: NativeOverlayToastText, runs: [NativeOverlayToastTextRun], pressable: Bool = false) {
149
+ super.init(frame: .zero)
150
+ backgroundColor = .clear
151
+ isOpaque = false
152
+ contentMode = .redraw
153
+ let attributed = NSMutableAttributedString()
154
+ let baseFont = NativeOverlayToastFont.make(
155
+ family: text.fontFamily, faces: text.fontFaces, weight: text.fontWeight,
156
+ size: text.fontSize, tabular: text.tabularNumbers
157
+ )
158
+ let paragraph = NSMutableParagraphStyle()
159
+ paragraph.minimumLineHeight = text.lineHeight
160
+ paragraph.maximumLineHeight = text.lineHeight
161
+ for run in runs {
162
+ let font = (run.fontWeight == nil && run.fontSize == nil)
163
+ ? baseFont
164
+ : NativeOverlayToastFont.make(
165
+ family: text.fontFamily, faces: text.fontFaces,
166
+ weight: run.fontWeight ?? text.fontWeight,
167
+ size: run.fontSize ?? text.fontSize, tabular: text.tabularNumbers
168
+ )
169
+ var attributes: [NSAttributedString.Key: Any] = [
170
+ .font: font,
171
+ .foregroundColor: run.color ?? text.color,
172
+ .paragraphStyle: paragraph,
173
+ // Centre the glyphs in the fixed line box.
174
+ .baselineOffset: (text.lineHeight - font.lineHeight) / 2,
175
+ // An explicit letter spacing, zero included, replaces the font's own
176
+ // pair kerning.
177
+ .kern: text.letterSpacing,
178
+ ]
179
+ if run.underline {
180
+ attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue
181
+ }
182
+ let start = attributed.length
183
+ attributed.append(NSAttributedString(string: run.text, attributes: attributes))
184
+ if let link = run.link {
185
+ links.append((NSRange(location: start, length: attributed.length - start), link))
186
+ }
187
+ }
188
+ container.lineFragmentPadding = 0
189
+ container.maximumNumberOfLines = text.numberOfLines
190
+ container.lineBreakMode = text.numberOfLines > 0 ? .byTruncatingTail : .byClipping
191
+ layoutManager.usesFontLeading = false
192
+ layoutManager.addTextContainer(container)
193
+ storage.addLayoutManager(layoutManager)
194
+ storage.setAttributedString(attributed)
195
+ isAccessibilityElement = attributed.length > 0
196
+ accessibilityLabel = attributed.string
197
+ if !links.isEmpty {
198
+ accessibilityTraits = .link
199
+ } else if pressable {
200
+ accessibilityTraits = [.staticText, .button]
201
+ } else {
202
+ accessibilityTraits = .staticText
203
+ }
204
+ if !links.isEmpty {
205
+ addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))))
206
+ } else {
207
+ isUserInteractionEnabled = false
208
+ }
209
+ }
210
+
211
+ @available(*, unavailable)
212
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
213
+
214
+ var string: String { storage.string }
215
+
216
+ private func layout(width: CGFloat) -> CGRect {
217
+ container.size = CGSize(width: width, height: .greatestFiniteMagnitude)
218
+ layoutManager.ensureLayout(for: container)
219
+ return layoutManager.usedRect(for: container)
220
+ }
221
+
222
+ func fittedHeight(width: CGFloat) -> CGFloat {
223
+ guard storage.length > 0 else { return 0 }
224
+ return pixelCeil(layout(width: width).height) + textBoxSlack
225
+ }
226
+
227
+ override func draw(_ rect: CGRect) {
228
+ guard storage.length > 0 else { return }
229
+ _ = layout(width: bounds.width)
230
+ let glyphs = layoutManager.glyphRange(for: container)
231
+ layoutManager.drawBackground(forGlyphRange: glyphs, at: .zero)
232
+ layoutManager.drawGlyphs(forGlyphRange: glyphs, at: .zero)
233
+ }
234
+
235
+ private func link(at point: CGPoint) -> String? {
236
+ guard storage.length > 0 else { return nil }
237
+ _ = layout(width: bounds.width)
238
+ let glyph = layoutManager.glyphIndex(for: point, in: container)
239
+ guard layoutManager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: container)
240
+ .insetBy(dx: -4, dy: -4).contains(point) else { return nil }
241
+ let index = layoutManager.characterIndexForGlyph(at: glyph)
242
+ return links.first { NSLocationInRange(index, $0.range) }?.link
243
+ }
244
+
245
+ override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
246
+ link(at: point) != nil
247
+ }
248
+
249
+ @objc private func handleTap(_ gesture: UITapGestureRecognizer) {
250
+ if let hit = link(at: gesture.location(in: self)) {
251
+ onLink?(hit)
252
+ }
253
+ }
254
+
255
+ override func accessibilityActivate() -> Bool {
256
+ if let firstLink = links.first?.link, let onLink {
257
+ onLink(firstLink)
258
+ return true
259
+ }
260
+ if let onPress {
261
+ onPress()
262
+ return true
263
+ }
264
+ return super.accessibilityActivate()
265
+ }
266
+ }
267
+
268
+ private final class ToastActionButton: UIControl {
269
+ let action: NativeOverlayToastAction
270
+ private let label = UILabel()
271
+ private var iconView: ToastIconView?
272
+
273
+ init(action: NativeOverlayToastAction) {
274
+ self.action = action
275
+ super.init(frame: .zero)
276
+ backgroundColor = action.backgroundColor
277
+ layer.cornerCurve = .continuous
278
+ isEnabled = !action.disabled
279
+ alpha = action.disabled ? action.disabledOpacity : 1
280
+ accessibilityIdentifier = action.testID
281
+ accessibilityLabel = action.label
282
+ accessibilityTraits = .button
283
+ isAccessibilityElement = true
284
+ label.font = NativeOverlayToastFont.make(
285
+ family: action.fontFamily, faces: action.fontFaces, weight: action.fontWeight,
286
+ size: action.fontSize, tabular: false
287
+ )
288
+ label.attributedText = NSAttributedString(
289
+ string: action.label,
290
+ attributes: [.font: label.font as Any, .foregroundColor: action.color, .kern: 0]
291
+ )
292
+ label.isUserInteractionEnabled = false
293
+ addSubview(label)
294
+ if let icon = action.icon {
295
+ let view = ToastIconView(icon: icon)
296
+ addSubview(view)
297
+ iconView = view
298
+ }
299
+ }
300
+
301
+ @available(*, unavailable)
302
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
303
+
304
+ override var isHighlighted: Bool {
305
+ didSet {
306
+ backgroundColor = isHighlighted
307
+ ? (action.pressedBackgroundColor ?? action.backgroundColor)
308
+ : action.backgroundColor
309
+ }
310
+ }
311
+
312
+ private var labelWidth: CGFloat { pixelCeil(label.intrinsicContentSize.width) }
313
+ private var iconExtent: CGFloat { action.icon.map { $0.size + action.iconGap } ?? 0 }
314
+
315
+ /// The button's border box.
316
+ var fittedSize: CGSize {
317
+ CGSize(
318
+ width: labelWidth + iconExtent + 2 * (action.paddingHorizontal + action.borderWidth),
319
+ height: max(action.lineHeight + textBoxSlack, action.icon?.size ?? 0)
320
+ + 2 * (action.paddingVertical + action.borderWidth)
321
+ )
322
+ }
323
+
324
+ override func layoutSubviews() {
325
+ super.layoutSubviews()
326
+ layer.cornerRadius = min(action.borderRadius, bounds.height / 2)
327
+ var x = action.paddingHorizontal + action.borderWidth
328
+ if let iconView, let icon = action.icon {
329
+ iconView.frame = CGRect(
330
+ x: x, y: (bounds.height - icon.size) / 2, width: icon.size, height: icon.size
331
+ )
332
+ x += icon.size + action.iconGap
333
+ }
334
+ label.frame = CGRect(
335
+ x: x, y: (bounds.height - action.lineHeight - textBoxSlack) / 2, width: labelWidth,
336
+ height: action.lineHeight
337
+ )
338
+ }
339
+
340
+ // The tertiary button's negative margins shrink its row; keep the whole
341
+ // pill touchable.
342
+ override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
343
+ bounds.insetBy(dx: -4, dy: -4).contains(point)
344
+ }
345
+ }
346
+
347
+ /// One toast card, drawn with UIKit from a spec.
348
+ final class NativeOverlayToastCardView: UIView {
349
+ private(set) var spec: NativeOverlayToastSpec
350
+ var onAction: ((String) -> Void)?
351
+ var onLink: ((String) -> Void)?
352
+ var onPress: (() -> Void)?
353
+
354
+ private let surface = UIView()
355
+ private let content = UIView()
356
+ private var layoutBlocks: [(CGFloat) -> CGFloat] = []
357
+
358
+ init(spec: NativeOverlayToastSpec, cardColor: UIColor) {
359
+ self.spec = spec
360
+ super.init(frame: .zero)
361
+ surface.layer.cornerRadius = ToastMetrics.cardRadius
362
+ surface.layer.shadowColor = UIColor(red: 0x18 / 255, green: 0x18 / 255, blue: 0x21 / 255, alpha: 1).cgColor
363
+ surface.layer.shadowOffset = CGSize(width: 0, height: 3)
364
+ surface.layer.shadowOpacity = 0.15
365
+ surface.layer.shadowRadius = 4.65
366
+ addSubview(surface)
367
+ content.clipsToBounds = true
368
+ surface.addSubview(content)
369
+ apply(spec: spec, cardColor: cardColor)
370
+ }
371
+
372
+ @available(*, unavailable)
373
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
374
+
375
+ func apply(spec: NativeOverlayToastSpec, cardColor: UIColor) {
376
+ self.spec = spec
377
+ surface.backgroundColor = cardColor
378
+ accessibilityIdentifier = spec.testID
379
+ content.subviews.forEach { $0.removeFromSuperview() }
380
+ layoutBlocks = []
381
+ switch spec.layout {
382
+ case .message: buildMessage()
383
+ case .notification: buildNotification()
384
+ }
385
+ if spec.pressable {
386
+ accessibilityCustomActions = [
387
+ UIAccessibilityCustomAction(
388
+ name: announcement.isEmpty ? "Activate" : announcement,
389
+ target: self,
390
+ selector: #selector(handleAccessibilityPressAction)
391
+ ),
392
+ ]
393
+ } else {
394
+ accessibilityCustomActions = nil
395
+ }
396
+ }
397
+
398
+ @objc private func handleAccessibilityPressAction() -> Bool {
399
+ guard spec.pressable, let onPress else { return false }
400
+ onPress()
401
+ return true
402
+ }
403
+
404
+ override func accessibilityActivate() -> Bool {
405
+ guard spec.pressable, let onPress else { return super.accessibilityActivate() }
406
+ onPress()
407
+ return true
408
+ }
409
+
410
+ /// What VoiceOver reads when the card appears.
411
+ var announcement: String {
412
+ [spec.title, spec.message].compactMap { text in
413
+ text?.paragraphs.map { $0.map(\.text).joined() }.joined(separator: "\n")
414
+ }.filter { !$0.isEmpty }.joined(separator: ". ")
415
+ }
416
+
417
+ private func makeLabels(_ text: NativeOverlayToastText?) -> [ToastTextLabel] {
418
+ guard let text else { return [] }
419
+ return text.paragraphs.map { runs in
420
+ let label = ToastTextLabel(text: text, runs: runs, pressable: spec.pressable)
421
+ label.onLink = { [weak self] link in self?.onLink?(link) }
422
+ if spec.pressable {
423
+ label.onPress = { [weak self] in self?.onPress?() }
424
+ }
425
+ content.addSubview(label)
426
+ return label
427
+ }
428
+ }
429
+
430
+ private func makeButtons() -> [ToastActionButton] {
431
+ spec.actions.map { action in
432
+ let button = ToastActionButton(action: action)
433
+ button.addTarget(self, action: #selector(handleAction(_:)), for: .touchUpInside)
434
+ content.addSubview(button)
435
+ return button
436
+ }
437
+ }
438
+
439
+ @objc private func handleAction(_ sender: ToastActionButton) {
440
+ onAction?(sender.action.id)
441
+ }
442
+
443
+ /// Lays the action row out at `y` and returns the height it occupies.
444
+ private func layoutActions(
445
+ _ buttons: [ToastActionButton], x: CGFloat, y: CGFloat, width: CGFloat,
446
+ paddingEnd: CGFloat, paddingBottom: CGFloat
447
+ ) -> CGFloat {
448
+ guard !buttons.isEmpty else { return 0 }
449
+ let sizes = buttons.map(\.fittedSize)
450
+ // Each button takes its border box plus its margins in the row.
451
+ let extents = zip(buttons, sizes).map { $1.width + 2 * $0.action.marginHorizontal }
452
+ let rowWidth = extents.reduce(0, +) + ToastMetrics.actionsGap * CGFloat(buttons.count - 1)
453
+ let rowHeight = zip(buttons, sizes).map { $1.height + 2 * $0.action.marginVertical }.max() ?? 0
454
+ var cursor = spec.actionsAlignLeft ? x : x + width - paddingEnd - rowWidth
455
+ let top = y + ToastMetrics.actionsPaddingTop
456
+ for (index, button) in buttons.enumerated() {
457
+ let size = sizes[index]
458
+ button.frame = CGRect(
459
+ x: cursor + button.action.marginHorizontal,
460
+ y: top + button.action.marginVertical,
461
+ width: size.width, height: size.height
462
+ )
463
+ cursor += extents[index] + ToastMetrics.actionsGap
464
+ }
465
+ return ToastMetrics.actionsPaddingTop + rowHeight + paddingBottom
466
+ }
467
+
468
+ private func buildMessage() {
469
+ let iconView = spec.icon.map(ToastIconView.init(icon:))
470
+ iconView.map(content.addSubview)
471
+ let titleLabels = makeLabels(spec.title)
472
+ let messageLabels = makeLabels(spec.message)
473
+ let buttons = makeButtons()
474
+ let iconSize = spec.icon?.size ?? 0
475
+ layoutBlocks.append { [weak self] width in
476
+ guard let self else { return 0 }
477
+ iconView?.frame = CGRect(x: 0, y: 0, width: iconSize, height: iconSize)
478
+ let x = iconView == nil ? 0 : iconSize + ToastMetrics.messageIconGap
479
+ let columnWidth = max(width - x, 0)
480
+ var y: CGFloat = 0
481
+ var hasBlock = false
482
+ for labels in [titleLabels, messageLabels] where !labels.isEmpty {
483
+ if hasBlock { y += ToastMetrics.messageTextGap }
484
+ hasBlock = true
485
+ for label in labels {
486
+ let height = label.fittedHeight(width: columnWidth)
487
+ label.frame = CGRect(x: x, y: y, width: columnWidth, height: height)
488
+ y += height
489
+ }
490
+ }
491
+ if !buttons.isEmpty {
492
+ if hasBlock { y += ToastMetrics.messageTextGap }
493
+ y += self.layoutActions(
494
+ buttons, x: x, y: y, width: columnWidth,
495
+ paddingEnd: ToastMetrics.actionsPaddingEnd,
496
+ paddingBottom: ToastMetrics.actionsPaddingBottom
497
+ )
498
+ }
499
+ return max(y, iconSize)
500
+ }
501
+ }
502
+
503
+ private func buildNotification() {
504
+ let badge = UIView()
505
+ badge.backgroundColor = spec.badgeColor
506
+ badge.layer.cornerRadius = spec.badgeSize / 2
507
+ badge.isUserInteractionEnabled = false
508
+ content.addSubview(badge)
509
+ let iconView = spec.icon.map(ToastIconView.init(icon:))
510
+ iconView.map(badge.addSubview)
511
+ let titleLabels = makeLabels(spec.title)
512
+ let messageLabels = makeLabels(spec.message)
513
+ let buttons = makeButtons()
514
+ let imageView = spec.image.map(ToastIconView.init(icon:))
515
+ imageView.map(content.addSubview)
516
+ let badgeSize = spec.badgeSize
517
+ let iconSize = spec.icon?.size ?? 0
518
+ let imageSize = spec.image?.size ?? 0
519
+ layoutBlocks.append { [weak self] width in
520
+ guard let self else { return 0 }
521
+ badge.frame = CGRect(x: 0, y: 0, width: badgeSize, height: badgeSize)
522
+ iconView?.frame = CGRect(
523
+ x: (badgeSize - iconSize) / 2, y: (badgeSize - iconSize) / 2,
524
+ width: iconSize, height: iconSize
525
+ )
526
+ let x = badgeSize + ToastMetrics.notificationGap
527
+ let trailing = imageView == nil ? 0 : imageSize + ToastMetrics.notificationGap
528
+ let columnWidth = max(width - x - trailing, 0)
529
+ imageView?.frame = CGRect(x: width - imageSize, y: 0, width: imageSize, height: imageSize)
530
+ var y: CGFloat = 0
531
+ var count = 0
532
+ for label in titleLabels + messageLabels {
533
+ if count > 0 { y += ToastMetrics.notificationTextGap }
534
+ count += 1
535
+ let height = label.fittedHeight(width: columnWidth)
536
+ label.frame = CGRect(x: x, y: y, width: columnWidth, height: height)
537
+ y += height
538
+ }
539
+ if !buttons.isEmpty {
540
+ y += ToastMetrics.notificationTextGap
541
+ y += self.layoutActions(
542
+ buttons, x: x, y: y, width: columnWidth, paddingEnd: 0, paddingBottom: 0
543
+ )
544
+ }
545
+ return max(y, badgeSize, imageSize)
546
+ }
547
+ }
548
+
549
+ /// Sizes the card for a content box of `contentWidth` and lays its content
550
+ /// out. Returns the card's size.
551
+ @discardableResult
552
+ func layoutCard(contentWidth: CGFloat, contentMaxHeight: CGFloat?) -> CGSize {
553
+ var height = layoutBlocks.reduce(CGFloat(0)) { $0 + $1(contentWidth) }
554
+ if let contentMaxHeight, contentMaxHeight > 0 {
555
+ height = min(height, contentMaxHeight)
556
+ }
557
+ let size = CGSize(
558
+ width: contentWidth + 2 * ToastMetrics.cardPaddingHorizontal,
559
+ height: height + 2 * ToastMetrics.cardPaddingVertical
560
+ )
561
+ bounds.size = size
562
+ surface.frame = CGRect(origin: .zero, size: size)
563
+ surface.layer.shadowPath = UIBezierPath(
564
+ roundedRect: surface.bounds, cornerRadius: ToastMetrics.cardRadius
565
+ ).cgPath
566
+ content.frame = CGRect(
567
+ x: ToastMetrics.cardPaddingHorizontal, y: ToastMetrics.cardPaddingVertical,
568
+ width: contentWidth, height: height
569
+ )
570
+ return size
571
+ }
572
+ }