@onekeyfe/react-native-native-overlay 6.8.0-3 → 6.8.0-5

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