@onekeyfe/react-native-native-overlay 6.8.0-alpha.514 → 6.8.0-alpha.539

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 (79) hide show
  1. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayHost.kt +37 -5
  2. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayPackage.kt +1 -1
  3. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastCardView.kt +869 -0
  4. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastSpec.kt +327 -0
  5. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterView.kt +574 -0
  6. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterViewManager.kt +54 -0
  7. package/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayAccessibilityIsolationTest.kt +172 -0
  8. package/docs/SPEC.md +172 -11
  9. package/ios/NativeOverlayContainerView.swift +20 -4
  10. package/ios/NativeOverlayToastCardView.swift +572 -0
  11. package/ios/NativeOverlayToastSpec.swift +356 -0
  12. package/ios/NativeOverlayToasterView.swift +519 -0
  13. package/ios/RCTNativeOverlayToasterComponentView.h +11 -0
  14. package/ios/RCTNativeOverlayToasterComponentView.mm +85 -0
  15. package/lib/module/NativeOverlayToasterNativeComponent.ts +24 -0
  16. package/lib/module/OverlayStore.js +20 -3
  17. package/lib/module/OverlayStore.js.map +1 -1
  18. package/lib/module/OverlayView.web.js +9 -18
  19. package/lib/module/OverlayView.web.js.map +1 -1
  20. package/lib/module/index.js +2 -0
  21. package/lib/module/index.js.map +1 -1
  22. package/lib/module/toast/OverlayToastHost.js +42 -0
  23. package/lib/module/toast/OverlayToastHost.js.map +1 -0
  24. package/lib/module/toast/OverlayToastHost.web.js +32 -0
  25. package/lib/module/toast/OverlayToastHost.web.js.map +1 -0
  26. package/lib/module/toast/OverlayToastStore.js +217 -0
  27. package/lib/module/toast/OverlayToastStore.js.map +1 -0
  28. package/lib/module/toast/toastBridge.js +65 -0
  29. package/lib/module/toast/toastBridge.js.map +1 -0
  30. package/lib/module/toast/toastDomContent.web.js +298 -0
  31. package/lib/module/toast/toastDomContent.web.js.map +1 -0
  32. package/lib/module/toast/toastDomRenderer.web.js +695 -0
  33. package/lib/module/toast/toastDomRenderer.web.js.map +1 -0
  34. package/lib/module/toast/toastStyles.web.js +97 -0
  35. package/lib/module/toast/toastStyles.web.js.map +1 -0
  36. package/lib/module/toast/types.js +2 -0
  37. package/lib/module/toast/types.js.map +1 -0
  38. package/lib/module/web/overlayLayers.js +82 -0
  39. package/lib/module/web/overlayLayers.js.map +1 -1
  40. package/lib/typescript/src/NativeOverlayToasterNativeComponent.d.ts +19 -0
  41. package/lib/typescript/src/NativeOverlayToasterNativeComponent.d.ts.map +1 -0
  42. package/lib/typescript/src/OverlayStore.d.ts +8 -1
  43. package/lib/typescript/src/OverlayStore.d.ts.map +1 -1
  44. package/lib/typescript/src/OverlayView.web.d.ts.map +1 -1
  45. package/lib/typescript/src/index.d.ts +4 -0
  46. package/lib/typescript/src/index.d.ts.map +1 -1
  47. package/lib/typescript/src/toast/OverlayToastHost.d.ts +6 -0
  48. package/lib/typescript/src/toast/OverlayToastHost.d.ts.map +1 -0
  49. package/lib/typescript/src/toast/OverlayToastHost.web.d.ts +6 -0
  50. package/lib/typescript/src/toast/OverlayToastHost.web.d.ts.map +1 -0
  51. package/lib/typescript/src/toast/OverlayToastStore.d.ts +47 -0
  52. package/lib/typescript/src/toast/OverlayToastStore.d.ts.map +1 -0
  53. package/lib/typescript/src/toast/toastBridge.d.ts +11 -0
  54. package/lib/typescript/src/toast/toastBridge.d.ts.map +1 -0
  55. package/lib/typescript/src/toast/toastDomContent.web.d.ts +15 -0
  56. package/lib/typescript/src/toast/toastDomContent.web.d.ts.map +1 -0
  57. package/lib/typescript/src/toast/toastDomRenderer.web.d.ts +8 -0
  58. package/lib/typescript/src/toast/toastDomRenderer.web.d.ts.map +1 -0
  59. package/lib/typescript/src/toast/toastStyles.web.d.ts +2 -0
  60. package/lib/typescript/src/toast/toastStyles.web.d.ts.map +1 -0
  61. package/lib/typescript/src/toast/types.d.ts +240 -0
  62. package/lib/typescript/src/toast/types.d.ts.map +1 -0
  63. package/lib/typescript/src/web/overlayLayers.d.ts +2 -0
  64. package/lib/typescript/src/web/overlayLayers.d.ts.map +1 -1
  65. package/package.json +3 -2
  66. package/react-native.config.js +1 -0
  67. package/src/NativeOverlayToasterNativeComponent.ts +24 -0
  68. package/src/OverlayStore.ts +35 -4
  69. package/src/OverlayView.web.tsx +10 -11
  70. package/src/index.ts +23 -0
  71. package/src/toast/OverlayToastHost.tsx +62 -0
  72. package/src/toast/OverlayToastHost.web.tsx +29 -0
  73. package/src/toast/OverlayToastStore.ts +254 -0
  74. package/src/toast/toastBridge.ts +62 -0
  75. package/src/toast/toastDomContent.web.ts +351 -0
  76. package/src/toast/toastDomRenderer.web.ts +856 -0
  77. package/src/toast/toastStyles.web.ts +97 -0
  78. package/src/toast/types.ts +251 -0
  79. package/src/web/overlayLayers.ts +114 -0
@@ -0,0 +1,869 @@
1
+ package com.onekey.nativeoverlay
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.Context
5
+ import android.content.res.AssetManager
6
+ import android.content.res.ColorStateList
7
+ import android.graphics.Bitmap
8
+ import android.graphics.BitmapFactory
9
+ import android.graphics.Canvas
10
+ import android.graphics.Color
11
+ import android.graphics.ColorFilter
12
+ import android.graphics.Paint
13
+ import android.graphics.PixelFormat
14
+ import android.graphics.Rect
15
+ import android.graphics.RectF
16
+ import android.graphics.Typeface
17
+ import android.graphics.drawable.Drawable
18
+ import android.graphics.drawable.GradientDrawable
19
+ import android.os.Build
20
+ import android.os.Bundle
21
+ import android.os.Handler
22
+ import android.os.Looper
23
+ import android.text.Layout
24
+ import android.text.SpannableStringBuilder
25
+ import android.text.Spanned
26
+ import android.text.TextPaint
27
+ import android.text.TextUtils
28
+ import android.text.method.LinkMovementMethod
29
+ import android.text.style.AbsoluteSizeSpan
30
+ import android.text.style.ClickableSpan
31
+ import android.text.style.ForegroundColorSpan
32
+ import android.text.style.LineHeightSpan
33
+ import android.text.style.MetricAffectingSpan
34
+ import android.util.Base64
35
+ import android.util.TypedValue
36
+ import android.view.MotionEvent
37
+ import android.view.View
38
+ import android.view.ViewGroup
39
+ import android.view.accessibility.AccessibilityNodeInfo
40
+ import android.widget.FrameLayout
41
+ import android.widget.ImageView
42
+ import android.widget.ProgressBar
43
+ import android.widget.TextView
44
+ import com.facebook.react.common.assets.ReactFontManager
45
+ import java.lang.ref.WeakReference
46
+ import java.net.HttpURLConnection
47
+ import java.net.URL
48
+ import java.net.URLConnection
49
+ import java.util.concurrent.Executors
50
+ import java.util.concurrent.Future
51
+ import java.util.concurrent.atomic.AtomicBoolean
52
+ import java.util.concurrent.atomic.AtomicReference
53
+ import kotlin.math.abs
54
+ import kotlin.math.ceil
55
+ import kotlin.math.floor
56
+ import kotlin.math.max
57
+ import kotlin.math.min
58
+ import kotlin.math.roundToInt
59
+
60
+ // The card geometry of the layouts this replaces, in dp.
61
+ private object ToastMetrics {
62
+ const val CARD_PADDING_HORIZONTAL = 16f
63
+ const val CARD_PADDING_VERTICAL = 12f
64
+ const val CARD_RADIUS = 8f
65
+ const val CARD_ELEVATION = 7f
66
+ const val MESSAGE_ICON_GAP = 8f
67
+ /** The status icon sits this far under the top of its box. */
68
+ const val MESSAGE_ICON_PADDING_TOP = 2f
69
+ const val MESSAGE_TEXT_GAP = 4f
70
+ const val NOTIFICATION_GAP = 8f
71
+ const val NOTIFICATION_TEXT_GAP = 2f
72
+ const val ACTIONS_GAP = 8f
73
+ const val ACTIONS_PADDING_TOP = 12f
74
+ const val ACTIONS_PADDING_END = 2f
75
+ const val ACTIONS_PADDING_BOTTOM = 2f
76
+ }
77
+
78
+ private const val IMAGE_POOL_THREADS = 4
79
+ private const val IMAGE_TIMEOUT_MS = 5_000
80
+
81
+ private val imageExecutor = Executors.newFixedThreadPool(IMAGE_POOL_THREADS) { runnable ->
82
+ Thread(runnable, "onekey-toast-image").apply { isDaemon = true }
83
+ }
84
+ private val mainHandler = Handler(Looper.getMainLooper())
85
+
86
+ private fun fetchBitmap(
87
+ uri: String,
88
+ cancelled: AtomicBoolean,
89
+ connectionRef: AtomicReference<URLConnection?>,
90
+ targetRef: WeakReference<ImageView>,
91
+ ) {
92
+ if (cancelled.get() || Thread.currentThread().isInterrupted) return
93
+ val bitmap = runCatching {
94
+ if (uri.startsWith("data:")) {
95
+ val bytes = Base64.decode(uri.substringAfter(","), Base64.DEFAULT)
96
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
97
+ } else {
98
+ val connection = URL(uri).openConnection().apply {
99
+ connectTimeout = IMAGE_TIMEOUT_MS
100
+ readTimeout = IMAGE_TIMEOUT_MS
101
+ }
102
+ connectionRef.set(connection)
103
+ try {
104
+ if (cancelled.get() || Thread.currentThread().isInterrupted) {
105
+ (connection as? HttpURLConnection)?.disconnect()
106
+ null
107
+ } else {
108
+ connection.getInputStream().use(BitmapFactory::decodeStream)
109
+ }
110
+ } finally {
111
+ connectionRef.compareAndSet(connection, null)
112
+ }
113
+ }
114
+ }.getOrNull()
115
+ if (!cancelled.get() && !Thread.currentThread().isInterrupted) {
116
+ mainHandler.post {
117
+ if (!cancelled.get()) {
118
+ targetRef.get()?.setImageBitmap(bitmap)
119
+ }
120
+ }
121
+ }
122
+ }
123
+
124
+ private fun Context.dp(value: Float): Int = (value * resources.displayMetrics.density).roundToInt()
125
+
126
+ /**
127
+ * React Native draws text unhinted at subpixel positions and rounds a font
128
+ * size up to whole pixels; the advances, and so the line breaks, follow.
129
+ */
130
+ private fun TextView.matchReactNativeText(fontSize: Float) {
131
+ paintFlags = paintFlags or Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG
132
+ setTextSize(TypedValue.COMPLEX_UNIT_PX, ceil(fontSize * resources.displayMetrics.density))
133
+ includeFontPadding = false
134
+ hyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE
135
+ breakStrategy = Layout.BREAK_STRATEGY_HIGH_QUALITY
136
+ }
137
+
138
+ private fun exactly(size: Int) = View.MeasureSpec.makeMeasureSpec(size, View.MeasureSpec.EXACTLY)
139
+
140
+ /** Gives every line the same height, with the glyphs centred in it. */
141
+ private class FixedLineHeightSpan(private val height: Int) : LineHeightSpan {
142
+ override fun chooseHeight(
143
+ text: CharSequence?,
144
+ start: Int,
145
+ end: Int,
146
+ spanstartv: Int,
147
+ lineHeight: Int,
148
+ fm: Paint.FontMetricsInt,
149
+ ) {
150
+ val leading = height - (fm.descent - fm.ascent)
151
+ fm.ascent -= ceil(leading / 2f).toInt()
152
+ fm.descent += floor(leading / 2f).toInt()
153
+ // Interior line boxes keep their own top/bottom so tall glyphs may overlap.
154
+ if (start == 0) fm.top = fm.ascent
155
+ if (end == text?.length) fm.bottom = fm.descent
156
+ }
157
+ }
158
+
159
+ private class TypefaceSpan(private val typeface: Typeface) : MetricAffectingSpan() {
160
+ override fun updateDrawState(paint: TextPaint) {
161
+ paint.typeface = typeface
162
+ }
163
+
164
+ override fun updateMeasureState(paint: TextPaint) {
165
+ paint.typeface = typeface
166
+ }
167
+ }
168
+
169
+ internal object ToastFont {
170
+ /**
171
+ * The face for a weight: a per-weight font name when the typeface ships one
172
+ * (resolved from `assets/fonts`), the family at that weight otherwise.
173
+ */
174
+ fun make(context: Context, family: String?, faces: Map<String, String>, weight: String): Typeface {
175
+ val assets = context.assets
176
+ faces[weight]?.let { name ->
177
+ return ReactFontManager.getInstance().getTypeface(name, Typeface.NORMAL, assets)
178
+ }
179
+ val numeric = weight.toIntOrNull() ?: 400
180
+ if (!family.isNullOrEmpty()) {
181
+ return ReactFontManager.getInstance().getTypeface(family, numeric, false, assets)
182
+ }
183
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
184
+ Typeface.create(Typeface.DEFAULT, numeric, false)
185
+ } else {
186
+ Typeface.create(Typeface.DEFAULT, if (numeric >= 600) Typeface.BOLD else Typeface.NORMAL)
187
+ }
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Named icons come from the image package's process-wide registry. It is
193
+ * reached reflectively so this module needs no dependency on it; without the
194
+ * registry the icon stays blank. The image package's consumer R8 rules keep
195
+ * `OneKeyNamedSVG.INSTANCE`, `request` and `cancel` unrenamed for this lookup;
196
+ * its own startup provider sets the cache directory.
197
+ */
198
+ private object ToastNamedIcon {
199
+ private val registry: Any? by lazy {
200
+ runCatching {
201
+ Class.forName("com.margelo.nitro.onekeyimage.OneKeyNamedSVG").getField("INSTANCE").get(null)
202
+ }.getOrNull()
203
+ }
204
+ private val request by lazy {
205
+ registry?.javaClass?.methods?.firstOrNull { it.name == "request" && it.parameterTypes.size == 8 }
206
+ }
207
+ private val cancel by lazy {
208
+ registry?.javaClass?.methods?.firstOrNull { it.name == "cancel" && it.parameterTypes.size == 1 }
209
+ }
210
+
211
+ fun request(
212
+ owner: Any,
213
+ context: Context,
214
+ name: String,
215
+ color: String,
216
+ width: Int,
217
+ height: Int,
218
+ scale: Float,
219
+ complete: (Bitmap?) -> Unit,
220
+ ) {
221
+ val target = registry
222
+ val method = request
223
+ if (target == null || method == null) {
224
+ complete(null)
225
+ return
226
+ }
227
+ val appContext = context.applicationContext ?: context
228
+ runCatching {
229
+ val callback: (Bitmap?) -> Unit = { bitmap -> mainHandler.post { complete(bitmap) } }
230
+ method.invoke(target, owner, appContext.assets as AssetManager, name, color, width, height, scale, callback)
231
+ }.onFailure { complete(null) }
232
+ }
233
+
234
+ fun cancel(owner: Any) {
235
+ val target = registry ?: return
236
+ runCatching { cancel?.invoke(target, owner) }
237
+ }
238
+ }
239
+
240
+ @SuppressLint("ViewConstructor")
241
+ internal class ToastIconView(context: Context, val icon: ToastIcon) : FrameLayout(context) {
242
+ private val owner = Any()
243
+ private val imageView = ImageView(context)
244
+ /** The size the named icon was last drawn at; it renders at its frame. */
245
+ private var requestedSize: Pair<Int, Int>? = null
246
+ private var imageFuture: Future<*>? = null
247
+ private var cancelled = AtomicBoolean(false)
248
+ private val activeConnection = AtomicReference<URLConnection?>(null)
249
+
250
+ init {
251
+ when (icon) {
252
+ is ToastIcon.Spinner -> {
253
+ val spinner = ProgressBar(context)
254
+ spinner.isIndeterminate = true
255
+ spinner.indeterminateTintList = ColorStateList.valueOf(icon.color)
256
+ addView(spinner, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
257
+ }
258
+ is ToastIcon.Image -> {
259
+ imageView.scaleType = ImageView.ScaleType.CENTER_CROP
260
+ if (icon.radius > 0) {
261
+ clipToOutline = true
262
+ background = GradientDrawable().apply {
263
+ setColor(Color.TRANSPARENT)
264
+ cornerRadius = context.dp(icon.radius).toFloat()
265
+ }
266
+ }
267
+ addView(imageView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
268
+ load(icon.uri)
269
+ }
270
+ is ToastIcon.Named -> {
271
+ imageView.scaleType = ImageView.ScaleType.FIT_CENTER
272
+ addView(imageView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
273
+ }
274
+ }
275
+ }
276
+
277
+ override fun onAttachedToWindow() {
278
+ super.onAttachedToWindow()
279
+ if (icon is ToastIcon.Image && cancelled.get() && imageView.drawable == null) {
280
+ load(icon.uri)
281
+ }
282
+ requestIcon()
283
+ }
284
+
285
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
286
+ super.onSizeChanged(w, h, oldw, oldh)
287
+ requestIcon()
288
+ }
289
+
290
+ private fun requestIcon() {
291
+ val named = icon as? ToastIcon.Named ?: return
292
+ if (!isAttachedToWindow || width <= 0 || height <= 0) return
293
+ val size = width to height
294
+ if (requestedSize == size) return
295
+ requestedSize = size
296
+ ToastNamedIcon.cancel(owner)
297
+ ToastNamedIcon.request(
298
+ owner, context, named.name, named.colorString, width, height, resources.displayMetrics.density,
299
+ ) { bitmap -> imageView.setImageBitmap(bitmap) }
300
+ }
301
+
302
+ fun cancelLoad() {
303
+ ToastNamedIcon.cancel(owner)
304
+ requestedSize = null
305
+ cancelled.set(true)
306
+ imageFuture?.cancel(true)
307
+ imageFuture = null
308
+ (activeConnection.getAndSet(null) as? HttpURLConnection)?.let { conn ->
309
+ Thread { runCatching { conn.disconnect() } }.apply { isDaemon = true }.start()
310
+ }
311
+ }
312
+
313
+ override fun onDetachedFromWindow() {
314
+ cancelLoad()
315
+ super.onDetachedFromWindow()
316
+ }
317
+
318
+ private fun load(uri: String) {
319
+ cancelLoad()
320
+ val token = AtomicBoolean(false)
321
+ cancelled = token
322
+ val targetRef = WeakReference(imageView)
323
+ val connectionRef = activeConnection
324
+ imageFuture = imageExecutor.submit {
325
+ fetchBitmap(uri, token, connectionRef, targetRef)
326
+ }
327
+ }
328
+ }
329
+
330
+ /** Marks a run React Native would underline; [ToastTextView] draws it. */
331
+ private class ToastUnderline
332
+
333
+ /**
334
+ * Draws underlines the way React Native's text does: a stroke of the font's
335
+ * underline thickness at baseline + thickness + 1px, in the run's colour.
336
+ * The platform underline sits elsewhere and is drawn thinner.
337
+ */
338
+ private class ToastTextView(context: Context) : TextView(context) {
339
+ private val decorationPaint = Paint()
340
+
341
+ override fun onDraw(canvas: Canvas) {
342
+ super.onDraw(canvas)
343
+ val layout = layout ?: return
344
+ val spanned = layout.text as? Spanned ?: return
345
+ val marks = spanned.getSpans(0, spanned.length, ToastUnderline::class.java)
346
+ if (marks.isEmpty()) return
347
+ val paint = layout.paint
348
+ val thickness = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
349
+ paint.underlineThickness
350
+ } else {
351
+ paint.fontMetrics.descent * 0.1f
352
+ }
353
+ canvas.save()
354
+ canvas.translate(totalPaddingLeft.toFloat(), totalPaddingTop.toFloat())
355
+ for (mark in marks) {
356
+ val start = spanned.getSpanStart(mark)
357
+ val end = spanned.getSpanEnd(mark)
358
+ val foreground = spanned.getSpans(start, start + 1, ForegroundColorSpan::class.java)
359
+ decorationPaint.set(paint)
360
+ decorationPaint.color = foreground.lastOrNull()?.foregroundColor ?: currentTextColor
361
+ decorationPaint.strokeWidth = thickness
362
+ decorationPaint.style = Paint.Style.STROKE
363
+ decorationPaint.isAntiAlias = true
364
+ val startLine = layout.getLineForOffset(start)
365
+ val endLine = layout.getLineForOffset(end)
366
+ for (line in startLine..endLine) {
367
+ val y = layout.getLineBaseline(line) + thickness + 1f
368
+ val x1 = if (line == startLine) layout.getPrimaryHorizontal(start) else layout.getLineLeft(line)
369
+ val x2 = if (line == endLine) layout.getPrimaryHorizontal(end) else layout.getLineRight(line)
370
+ canvas.drawLine(min(x1, x2), y, max(x1, x2), y, decorationPaint)
371
+ }
372
+ }
373
+ canvas.restore()
374
+ }
375
+ }
376
+
377
+ /**
378
+ * The background React Native gives a rounded view with a border: the fill
379
+ * is inset by 0.8px so the border can overlap it.
380
+ */
381
+ private class ToastPillDrawable(private val inset: Float) : Drawable() {
382
+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
383
+ private val rect = RectF()
384
+ var radius = 0f
385
+ set(value) {
386
+ field = value
387
+ invalidateSelf()
388
+ }
389
+
390
+ fun setColor(color: Int) {
391
+ paint.color = color
392
+ invalidateSelf()
393
+ }
394
+
395
+ override fun draw(canvas: Canvas) {
396
+ rect.set(bounds)
397
+ rect.inset(inset, inset)
398
+ canvas.drawRoundRect(rect, radius, radius, paint)
399
+ }
400
+
401
+ override fun setAlpha(alpha: Int) = Unit
402
+
403
+ override fun setColorFilter(colorFilter: ColorFilter?) = Unit
404
+
405
+ @Deprecated("Deprecated in Java")
406
+ override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
407
+ }
408
+
409
+ private fun makeParagraph(
410
+ context: Context,
411
+ text: ToastText,
412
+ runs: List<ToastTextRun>,
413
+ onLink: (String) -> Unit,
414
+ ): TextView {
415
+ val density = context.resources.displayMetrics.density
416
+ val view = ToastTextView(context)
417
+ view.matchReactNativeText(text.fontSize)
418
+ view.setTextColor(text.color)
419
+ view.typeface = ToastFont.make(context, text.fontFamily, text.fontFaces, text.fontWeight)
420
+ if (text.letterSpacing != 0f) {
421
+ view.letterSpacing = text.letterSpacing / text.fontSize
422
+ }
423
+ if (text.tabularNumbers) {
424
+ view.fontFeatureSettings = "'tnum'"
425
+ }
426
+ if (text.numberOfLines > 0) {
427
+ view.maxLines = text.numberOfLines
428
+ view.ellipsize = TextUtils.TruncateAt.END
429
+ }
430
+ val builder = SpannableStringBuilder()
431
+ var hasLink = false
432
+ for (run in runs) {
433
+ val start = builder.length
434
+ builder.append(run.text)
435
+ val end = builder.length
436
+ if (start == end) continue
437
+ val flags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
438
+ run.link?.let { link ->
439
+ hasLink = true
440
+ builder.setSpan(
441
+ object : ClickableSpan() {
442
+ override fun onClick(widget: View) = onLink(link)
443
+
444
+ // The run keeps its own colour and underline.
445
+ override fun updateDrawState(paint: TextPaint) = Unit
446
+ },
447
+ start, end, flags,
448
+ )
449
+ }
450
+ run.color?.let { builder.setSpan(ForegroundColorSpan(it), start, end, flags) }
451
+ run.fontWeight?.let {
452
+ builder.setSpan(
453
+ TypefaceSpan(ToastFont.make(context, text.fontFamily, text.fontFaces, it)), start, end, flags,
454
+ )
455
+ }
456
+ run.fontSize?.let {
457
+ builder.setSpan(AbsoluteSizeSpan(ceil(it * density).toInt()), start, end, flags)
458
+ }
459
+ if (run.underline) builder.setSpan(ToastUnderline(), start, end, flags)
460
+ }
461
+ if (builder.isNotEmpty()) {
462
+ builder.setSpan(
463
+ // React Native rounds a line height up to whole pixels.
464
+ FixedLineHeightSpan(ceil(text.lineHeight * density).toInt()),
465
+ 0, builder.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE,
466
+ )
467
+ }
468
+ view.text = builder
469
+ if (hasLink) {
470
+ view.movementMethod = LinkMovementMethod.getInstance()
471
+ view.highlightColor = Color.TRANSPARENT
472
+ }
473
+ return view
474
+ }
475
+
476
+ /**
477
+ * The pixel-grid rounding of the layout engine the replaced cards were laid
478
+ * out with (Yoga): a node's offset from its parent is rounded half up, text
479
+ * offsets are floored, and a size is the difference of the rounded absolute
480
+ * edges. Matching it keeps every edge on the same pixel as before.
481
+ */
482
+ private object PixelGrid {
483
+ private fun same(a: Double, b: Double) = abs(a - b) < 0.0001
484
+
485
+ fun snap(value: Double, forceCeil: Boolean = false, forceFloor: Boolean = false): Double {
486
+ var fraction = value % 1.0
487
+ if (fraction < 0) fraction += 1.0
488
+ return when {
489
+ same(fraction, 0.0) -> value - fraction
490
+ same(fraction, 1.0) -> value - fraction + 1.0
491
+ forceCeil -> value - fraction + 1.0
492
+ forceFloor -> value - fraction
493
+ else -> value - fraction + if (fraction > 0.5 || same(fraction, 0.5)) 1.0 else 0.0
494
+ }
495
+ }
496
+
497
+ fun isFractional(value: Double): Boolean {
498
+ val fraction = value % 1.0
499
+ return !same(fraction, 0.0) && !same(fraction, 1.0)
500
+ }
501
+ }
502
+
503
+ /**
504
+ * A node of the replaced layout: its unrounded absolute origin and its drawn
505
+ * origin relative to the card, both in px.
506
+ */
507
+ private class Node(val absX: Double, val absY: Double, val x: Int, val y: Int) {
508
+ fun child(relX: Double, relY: Double, text: Boolean = false) = Node(
509
+ absX + relX,
510
+ absY + relY,
511
+ x + PixelGrid.snap(relX, forceFloor = text).toInt(),
512
+ y + PixelGrid.snap(relY, forceFloor = text).toInt(),
513
+ )
514
+
515
+ fun width(size: Double, text: Boolean = false): Int = extent(absX, size, text)
516
+
517
+ fun height(size: Double, text: Boolean = false): Int = extent(absY, size, text)
518
+
519
+ fun frame(width: Double, height: Double, text: Boolean = false) =
520
+ Rect(x, y, x + width(width, text), y + height(height, text))
521
+
522
+ private fun extent(origin: Double, size: Double, text: Boolean): Int {
523
+ val fractional = PixelGrid.isFractional(size)
524
+ val end = PixelGrid.snap(origin + size, forceCeil = text && fractional, forceFloor = text && !fractional)
525
+ return (end - PixelGrid.snap(origin, forceFloor = text)).toInt()
526
+ }
527
+ }
528
+
529
+ private fun View.layoutAt(frame: Rect, originX: Int = 0, originY: Int = 0) {
530
+ measure(exactly(frame.width()), exactly(frame.height()))
531
+ layout(frame.left - originX, frame.top - originY, frame.right - originX, frame.bottom - originY)
532
+ }
533
+
534
+ @SuppressLint("ViewConstructor")
535
+ private class ToastActionButton(context: Context, val action: ToastAction) : ViewGroup(context) {
536
+ private val surface = ToastPillDrawable(if (action.borderWidth > 0) 0.8f else 0f)
537
+ val label = TextView(context)
538
+ val iconView = action.icon?.let { ToastIconView(context, it) }
539
+ /** Child frames in the card's coordinates; the card lays the button out. */
540
+ var frame = Rect()
541
+ var labelFrame = Rect()
542
+ var iconFrame = Rect()
543
+
544
+ init {
545
+ surface.setColor(action.backgroundColor)
546
+ background = surface
547
+ isClickable = !action.disabled
548
+ isEnabled = !action.disabled
549
+ alpha = if (action.disabled) action.disabledOpacity else 1f
550
+ contentDescription = action.label
551
+ action.testID?.let { tag = it }
552
+ val density = resources.displayMetrics.density
553
+ label.matchReactNativeText(action.fontSize)
554
+ label.setTextColor(action.color)
555
+ label.typeface = ToastFont.make(context, action.fontFamily, action.fontFaces, action.fontWeight)
556
+ label.text = SpannableStringBuilder(action.label).apply {
557
+ setSpan(
558
+ FixedLineHeightSpan(ceil(action.lineHeight * density).toInt()),
559
+ 0, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE,
560
+ )
561
+ }
562
+ label.maxLines = 1
563
+ iconView?.let(::addView)
564
+ addView(label)
565
+ }
566
+
567
+ /** The label's natural width and height in px. */
568
+ fun measureLabel(): Pair<Int, Int> {
569
+ label.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
570
+ return label.measuredWidth to label.measuredHeight
571
+ }
572
+
573
+ @SuppressLint("ClickableViewAccessibility")
574
+ override fun onTouchEvent(event: MotionEvent): Boolean {
575
+ if (isEnabled) {
576
+ when (event.actionMasked) {
577
+ MotionEvent.ACTION_DOWN -> surface.setColor(action.pressedBackgroundColor ?: action.backgroundColor)
578
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> surface.setColor(action.backgroundColor)
579
+ }
580
+ }
581
+ return super.onTouchEvent(event)
582
+ }
583
+
584
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
585
+ setMeasuredDimension(frame.width(), frame.height())
586
+ }
587
+
588
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
589
+ surface.radius = minOf(action.borderRadius * resources.displayMetrics.density, (bottom - top) / 2f)
590
+ label.layoutAt(labelFrame, frame.left, frame.top)
591
+ iconView?.layoutAt(iconFrame, frame.left, frame.top)
592
+ }
593
+ }
594
+
595
+ /** One toast card, drawn with Android views from a spec. */
596
+ @SuppressLint("ViewConstructor")
597
+ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) {
598
+ var spec: ToastSpec? = null
599
+ private set
600
+ var onAction: ((String) -> Unit)? = null
601
+ var onLink: ((String) -> Unit)? = null
602
+ var onPress: (() -> Unit)? = null
603
+ /** Width of the content box in dp; the card adds its padding around it. */
604
+ var contentWidth = 0f
605
+ /** Tallest the content box grows, in dp; zero leaves it unbounded. */
606
+ var contentMaxHeight = 0f
607
+ /** The card's unrounded position in the window, in px; rounding follows it. */
608
+ var originX = 0.0
609
+ var originY = 0.0
610
+
611
+ private val surface = GradientDrawable()
612
+ private var iconView: ToastIconView? = null
613
+ private var badge: View? = null
614
+ private var imageView: ToastIconView? = null
615
+ private var titles: List<TextView> = emptyList()
616
+ private var messages: List<TextView> = emptyList()
617
+ private var buttons: List<ToastActionButton> = emptyList()
618
+ private val frames = HashMap<View, Rect>()
619
+ private var size = Rect()
620
+
621
+ init {
622
+ surface.cornerRadius = context.dp(ToastMetrics.CARD_RADIUS).toFloat()
623
+ background = surface
624
+ elevation = context.dp(ToastMetrics.CARD_ELEVATION).toFloat()
625
+ clipChildren = true
626
+ clipToPadding = true
627
+ }
628
+
629
+ fun cancelLoads() {
630
+ iconView?.cancelLoad()
631
+ imageView?.cancelLoad()
632
+ buttons.forEach { it.iconView?.cancelLoad() }
633
+ }
634
+
635
+ fun apply(spec: ToastSpec, cardColor: Int) {
636
+ this.spec = spec
637
+ surface.setColor(cardColor)
638
+ spec.testID?.let { tag = it }
639
+ isClickable = spec.pressable
640
+ isFocusable = spec.pressable
641
+ importantForAccessibility = if (spec.pressable) {
642
+ IMPORTANT_FOR_ACCESSIBILITY_YES
643
+ } else {
644
+ IMPORTANT_FOR_ACCESSIBILITY_AUTO
645
+ }
646
+ cancelLoads()
647
+ removeAllViews()
648
+ val link: (String) -> Unit = { onLink?.invoke(it) }
649
+ badge = if (spec.isNotification) {
650
+ View(context).also { view ->
651
+ view.background = GradientDrawable().apply {
652
+ shape = GradientDrawable.OVAL
653
+ setColor(spec.badgeColor)
654
+ }
655
+ addView(view)
656
+ }
657
+ } else {
658
+ null
659
+ }
660
+ iconView = spec.icon?.let { ToastIconView(context, it).also(::addView) }
661
+ imageView = spec.image?.let { ToastIconView(context, it).also(::addView) }
662
+ titles = spec.title?.let { text ->
663
+ text.paragraphs.map { makeParagraph(context, text, it, link).also(::addView) }
664
+ }.orEmpty()
665
+ messages = spec.message?.let { text ->
666
+ text.paragraphs.map { makeParagraph(context, text, it, link).also(::addView) }
667
+ }.orEmpty()
668
+ buttons = spec.actions.map { action ->
669
+ ToastActionButton(context, action).also { button ->
670
+ button.setOnClickListener { onAction?.invoke(action.id) }
671
+ addView(button)
672
+ }
673
+ }
674
+ requestLayout()
675
+ }
676
+
677
+ /** What TalkBack reads when the card appears. */
678
+ val announcement: String
679
+ get() = (titles + messages).map { it.text.toString() }.filter { it.isNotEmpty() }.joinToString(". ")
680
+
681
+ override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) {
682
+ super.onInitializeAccessibilityNodeInfo(info)
683
+ if (spec?.pressable == true) {
684
+ info.isClickable = true
685
+ info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK)
686
+ if (info.contentDescription.isNullOrEmpty()) {
687
+ info.contentDescription = announcement
688
+ }
689
+ }
690
+ }
691
+
692
+ override fun performAccessibilityAction(action: Int, arguments: Bundle?): Boolean {
693
+ if (action == AccessibilityNodeInfo.ACTION_CLICK && spec?.pressable == true) {
694
+ onPress?.invoke()
695
+ return true
696
+ }
697
+ return super.performAccessibilityAction(action, arguments)
698
+ }
699
+
700
+ override fun performClick(): Boolean {
701
+ super.performClick()
702
+ if (spec?.pressable == true) {
703
+ onPress?.invoke()
704
+ return true
705
+ }
706
+ return false
707
+ }
708
+
709
+ private val density: Double get() = resources.displayMetrics.density.toDouble()
710
+
711
+ private fun px(dp: Float): Double = dp * density
712
+
713
+ /** Lays text out at its frame's width; returns the height it takes, in px. */
714
+ private fun textHeight(view: TextView, width: Int): Int {
715
+ if (view.text.isEmpty()) return 0
716
+ view.measure(exactly(width), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
717
+ return view.measuredHeight
718
+ }
719
+
720
+ /**
721
+ * Stacks text views in [parent] from [top] down; returns their total height.
722
+ * Each view is a text node of its own.
723
+ */
724
+ private fun placeParagraphs(views: List<TextView>, parent: Node, width: Double, top: Double = 0.0): Double {
725
+ var y = 0.0
726
+ for (view in views) {
727
+ val node = parent.child(0.0, top + y, text = true)
728
+ val drawnWidth = node.width(width, text = true)
729
+ val height = textHeight(view, drawnWidth).toDouble()
730
+ frames[view] = node.frame(width, height, text = true)
731
+ y += height
732
+ }
733
+ return y
734
+ }
735
+
736
+ /**
737
+ * Places the action row with [row] as its origin; returns the row's height.
738
+ * The row is as wide as [width] and keeps [paddingEnd] clear at its end.
739
+ */
740
+ private fun placeActions(row: Node, width: Double, paddingEnd: Float, paddingBottom: Float): Double {
741
+ if (buttons.isEmpty()) return 0.0
742
+ val gap = px(ToastMetrics.ACTIONS_GAP)
743
+ val sizes = buttons.map { button ->
744
+ val action = button.action
745
+ val (labelWidth, labelHeight) = button.measureLabel()
746
+ val iconSize = action.icon?.let { px(it.size) } ?: 0.0
747
+ val iconExtent = if (action.icon != null) iconSize + px(action.iconGap) else 0.0
748
+ val contentHeight = max(labelHeight.toDouble(), iconSize)
749
+ val insetX = px(action.paddingHorizontal + action.borderWidth)
750
+ val insetY = px(action.paddingVertical + action.borderWidth)
751
+ doubleArrayOf(labelWidth + iconExtent + 2 * insetX, contentHeight + 2 * insetY)
752
+ }
753
+ val extents = buttons.mapIndexed { index, button ->
754
+ sizes[index][0] + 2 * px(button.action.marginHorizontal)
755
+ }
756
+ val rowWidth = extents.sum() + gap * (buttons.size - 1)
757
+ var cursor = if (spec?.actionsAlignLeft == true) 0.0 else width - px(paddingEnd) - rowWidth
758
+ val paddingTop = px(ToastMetrics.ACTIONS_PADDING_TOP)
759
+ var rowHeight = 0.0
760
+ buttons.forEachIndexed { index, button ->
761
+ val action = button.action
762
+ val (buttonWidth, buttonHeight) = sizes[index].let { it[0] to it[1] }
763
+ val marginX = px(action.marginHorizontal)
764
+ val marginY = px(action.marginVertical)
765
+ val node = row.child(cursor + marginX, paddingTop + marginY)
766
+ button.frame = node.frame(buttonWidth, buttonHeight)
767
+ frames[button] = button.frame
768
+ val insetX = px(action.paddingHorizontal + action.borderWidth)
769
+ val insetY = px(action.paddingVertical + action.borderWidth)
770
+ val contentHeight = buttonHeight - 2 * insetY
771
+ var labelX = insetX
772
+ button.iconView?.let {
773
+ val iconSize = px(action.icon!!.size)
774
+ button.iconFrame = node.child(insetX, insetY + (contentHeight - iconSize) / 2).frame(iconSize, iconSize)
775
+ labelX += iconSize + px(action.iconGap)
776
+ }
777
+ val labelHeight = button.label.measuredHeight.toDouble()
778
+ button.labelFrame = node.child(labelX, insetY + (contentHeight - labelHeight) / 2, text = true)
779
+ .frame(button.label.measuredWidth.toDouble(), labelHeight, text = true)
780
+ rowHeight = max(rowHeight, buttonHeight + 2 * marginY)
781
+ cursor += extents[index] + gap
782
+ }
783
+ return paddingTop + rowHeight + px(paddingBottom)
784
+ }
785
+
786
+ /** Lays the content box out from [content]; returns its height in px. */
787
+ private fun placeContent(spec: ToastSpec, content: Node, width: Double): Double {
788
+ if (spec.isNotification) {
789
+ val badgeSize = px(spec.badgeSize)
790
+ val badgeNode = content.child(0.0, 0.0)
791
+ badge?.let { frames[it] = badgeNode.frame(badgeSize, badgeSize) }
792
+ iconView?.let { view ->
793
+ val size = px(view.icon.size)
794
+ frames[view] = badgeNode.child((badgeSize - size) / 2, (badgeSize - size) / 2).frame(size, size)
795
+ }
796
+ val gap = px(ToastMetrics.NOTIFICATION_GAP)
797
+ val imageSize = spec.image?.let { px(it.size) } ?: 0.0
798
+ imageView?.let { frames[it] = content.child(width - imageSize, 0.0).frame(imageSize, imageSize) }
799
+ val columnX = badgeSize + gap
800
+ val columnWidth = max(width - columnX - (if (spec.image != null) imageSize + gap else 0.0), 0.0)
801
+ val column = content.child(columnX, 0.0)
802
+ val textGap = px(ToastMetrics.NOTIFICATION_TEXT_GAP)
803
+ var y = 0.0
804
+ (titles + messages).forEachIndexed { index, view ->
805
+ if (index > 0) y += textGap
806
+ y += placeParagraphs(listOf(view), column, columnWidth, top = y)
807
+ }
808
+ if (buttons.isNotEmpty()) {
809
+ y += textGap
810
+ y += placeActions(column.child(0.0, y), columnWidth, 0f, 0f)
811
+ }
812
+ return maxOf(y, badgeSize, imageSize)
813
+ }
814
+ val icon = spec.icon
815
+ val columnX = icon?.let { px(it.size) + px(ToastMetrics.MESSAGE_ICON_GAP) } ?: 0.0
816
+ iconView?.let { view ->
817
+ val size = px(view.icon.size)
818
+ frames[view] = content.child(0.0, px(ToastMetrics.MESSAGE_ICON_PADDING_TOP)).frame(size, size)
819
+ }
820
+ val columnWidth = max(width - columnX, 0.0)
821
+ val column = content.child(columnX, 0.0)
822
+ val gap = px(ToastMetrics.MESSAGE_TEXT_GAP)
823
+ var y = 0.0
824
+ var hasBlock = false
825
+ for (block in listOf(titles, messages)) {
826
+ if (block.isEmpty()) continue
827
+ if (hasBlock) y += gap
828
+ hasBlock = true
829
+ y += placeParagraphs(block, column.child(0.0, y), columnWidth)
830
+ }
831
+ if (buttons.isNotEmpty()) {
832
+ if (hasBlock) y += gap
833
+ y += placeActions(
834
+ column.child(0.0, y), columnWidth, ToastMetrics.ACTIONS_PADDING_END, ToastMetrics.ACTIONS_PADDING_BOTTOM,
835
+ )
836
+ }
837
+ val iconBox = icon?.let { px(it.size + ToastMetrics.MESSAGE_ICON_PADDING_TOP) } ?: 0.0
838
+ return max(y, iconBox)
839
+ }
840
+
841
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
842
+ frames.clear()
843
+ val spec = spec
844
+ val card = Node(originX, originY, 0, 0)
845
+ val width = px(contentWidth)
846
+ var height = 0.0
847
+ if (spec != null) {
848
+ val content = card.child(px(ToastMetrics.CARD_PADDING_HORIZONTAL), px(ToastMetrics.CARD_PADDING_VERTICAL))
849
+ height = placeContent(spec, content, width)
850
+ if (contentMaxHeight > 0) height = min(height, px(contentMaxHeight))
851
+ }
852
+ size = card.frame(
853
+ width + 2 * px(ToastMetrics.CARD_PADDING_HORIZONTAL),
854
+ height + 2 * px(ToastMetrics.CARD_PADDING_VERTICAL),
855
+ )
856
+ setMeasuredDimension(size.width(), size.height())
857
+ }
858
+
859
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
860
+ for ((view, frame) in frames) {
861
+ if (view is ToastActionButton) {
862
+ view.measure(exactly(frame.width()), exactly(frame.height()))
863
+ view.layout(frame.left, frame.top, frame.right, frame.bottom)
864
+ } else {
865
+ view.layoutAt(frame)
866
+ }
867
+ }
868
+ }
869
+ }