@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,574 @@
1
+ package com.onekey.nativeoverlay
2
+
3
+ import android.animation.ValueAnimator
4
+ import android.annotation.SuppressLint
5
+ import android.app.Activity
6
+ import android.content.Context
7
+ import android.os.Build
8
+ import android.os.Handler
9
+ import android.os.Looper
10
+ import android.os.SystemClock
11
+ import android.view.MotionEvent
12
+ import android.view.VelocityTracker
13
+ import android.view.View
14
+ import android.view.ViewGroup
15
+ import android.view.animation.PathInterpolator
16
+ import android.widget.FrameLayout
17
+ import androidx.core.view.ViewCompat
18
+ import androidx.core.view.WindowInsetsCompat
19
+ import com.facebook.react.bridge.Arguments
20
+ import com.facebook.react.bridge.WritableMap
21
+ import com.facebook.react.uimanager.ThemedReactContext
22
+ import com.facebook.react.uimanager.events.Event
23
+ import kotlin.math.abs
24
+ import kotlin.math.max
25
+ import kotlin.math.min
26
+ import kotlin.math.roundToInt
27
+
28
+ // The motion and gesture constants of the toaster this replaces, in dp / ms.
29
+ private object ToasterMetrics {
30
+ /** The first toast sits this far under the top inset. */
31
+ const val TOP_OFFSET = 16f
32
+ const val GUTTER = 8f
33
+ const val ANIMATION_MS = 300L
34
+ const val OBSTRUCTION_MS = 220L
35
+ /** A dismissed card is reported closed when the previous renderer unmounted it. */
36
+ const val REMOVE_DELAY_MS = 1000L
37
+ const val ENTER_OVERSHOOT = 50f
38
+ const val FALLBACK_HEIGHT = 50f
39
+ const val SWIPE_START = 10f
40
+ const val SWIPE_DISTANCE = 32f
41
+ const val SWIPE_FLICK_DISTANCE = 12f
42
+ const val SWIPE_FLICK_VELOCITY = 600f
43
+ /** Dragging against the dismiss direction moves the card a quarter as far. */
44
+ const val SWIPE_RESISTANCE = 4f
45
+ const val FALLBACK_MARGIN = 64f
46
+ const val FALLBACK_MAX_PAGE_WIDTH = 640f
47
+ const val LANE_MAX_WIDTH = 360f
48
+ const val LANE_MARGIN = 32.0
49
+ const val CARD_PADDING_HORIZONTAL = 16f
50
+ }
51
+
52
+ /** Rounds half up, the way the replaced layout placed a node in its parent. */
53
+ private fun snapHalfUp(value: Double): Int = kotlin.math.floor(value + 0.5 + 1e-4).toInt()
54
+
55
+ /** Quadratic ease-in-out, the timing curve of the animations this replaces. */
56
+ private val toastInterpolator = PathInterpolator(0.455f, 0.03f, 0.515f, 0.955f)
57
+
58
+ internal class NativeOverlayToastEvent(
59
+ surfaceId: Int,
60
+ viewTag: Int,
61
+ private val toastId: String,
62
+ private val generation: Int,
63
+ private val type: String,
64
+ private val value: String,
65
+ ) : Event<NativeOverlayToastEvent>(surfaceId, viewTag) {
66
+ override fun getEventName(): String = NAME
67
+
68
+ // Every toast event must reach JS; never coalesce them.
69
+ override fun canCoalesce(): Boolean = false
70
+
71
+ override fun getEventData(): WritableMap = Arguments.createMap().apply {
72
+ putString("toastId", toastId)
73
+ putInt("generation", generation)
74
+ putString("type", type)
75
+ putString("value", value)
76
+ }
77
+
78
+ companion object {
79
+ const val NAME = "topToastEvent"
80
+ }
81
+ }
82
+
83
+ /** Hosts one card: forwards presses and vertical drags to the presenter. */
84
+ @SuppressLint("ViewConstructor")
85
+ private class ToastSlot(context: Context, val card: NativeOverlayToastCardView) : FrameLayout(context) {
86
+ var onPressChanged: ((Boolean) -> Unit)? = null
87
+ var onDrag: ((Float) -> Unit)? = null
88
+ var onRelease: ((translationY: Float, translationX: Float, velocityY: Float, cancelled: Boolean) -> Unit)? = null
89
+ var onTap: (() -> Unit)? = null
90
+
91
+ private var downX = 0f
92
+ private var downY = 0f
93
+ private var dragging = false
94
+ private var tracker: VelocityTracker? = null
95
+
96
+ init {
97
+ clipChildren = false
98
+ clipToPadding = false
99
+ addView(card, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))
100
+ }
101
+
102
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean {
103
+ when (event.actionMasked) {
104
+ MotionEvent.ACTION_DOWN -> onPressChanged?.invoke(true)
105
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> onPressChanged?.invoke(false)
106
+ }
107
+ return super.dispatchTouchEvent(event)
108
+ }
109
+
110
+ private fun track(event: MotionEvent) {
111
+ val current = tracker ?: VelocityTracker.obtain().also { tracker = it }
112
+ current.addMovement(event)
113
+ }
114
+
115
+ override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
116
+ when (event.actionMasked) {
117
+ MotionEvent.ACTION_DOWN -> {
118
+ downX = event.rawX
119
+ downY = event.rawY
120
+ dragging = false
121
+ tracker?.recycle()
122
+ tracker = null
123
+ track(event)
124
+ }
125
+ MotionEvent.ACTION_MOVE -> {
126
+ track(event)
127
+ val dy = event.rawY - downY
128
+ val dx = event.rawX - downX
129
+ val slop = ToasterMetrics.SWIPE_START * resources.displayMetrics.density
130
+ if (!dragging && abs(dy) > slop && abs(dy) > abs(dx)) {
131
+ dragging = true
132
+ parent?.requestDisallowInterceptTouchEvent(true)
133
+ }
134
+ }
135
+ }
136
+ return dragging
137
+ }
138
+
139
+ @SuppressLint("ClickableViewAccessibility")
140
+ override fun onTouchEvent(event: MotionEvent): Boolean {
141
+ when (event.actionMasked) {
142
+ MotionEvent.ACTION_MOVE -> {
143
+ track(event)
144
+ val dy = event.rawY - downY
145
+ val dx = event.rawX - downX
146
+ val slop = ToasterMetrics.SWIPE_START * resources.displayMetrics.density
147
+ if (!dragging && abs(dy) > slop && abs(dy) > abs(dx)) dragging = true
148
+ if (dragging) onDrag?.invoke(dy)
149
+ }
150
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
151
+ track(event)
152
+ val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL
153
+ if (dragging) {
154
+ tracker?.computeCurrentVelocity(1000)
155
+ onRelease?.invoke(event.rawY - downY, event.rawX - downX, tracker?.yVelocity ?: 0f, cancelled)
156
+ } else if (!cancelled) {
157
+ onTap?.invoke()
158
+ }
159
+ dragging = false
160
+ tracker?.recycle()
161
+ tracker = null
162
+ }
163
+ }
164
+ // Claim the gesture so a press on the card's own surface can become a drag.
165
+ return true
166
+ }
167
+
168
+ override fun performClick(): Boolean {
169
+ super.performClick()
170
+ onTap?.invoke()
171
+ return true
172
+ }
173
+ }
174
+
175
+ private class ToastEntry(val id: String, var item: ToastItem, val slot: ToastSlot) {
176
+ var leaving = false
177
+ var reason = "programmatic"
178
+ /** Milliseconds of lifetime left, counted while not paused. */
179
+ var remaining: Long? = null
180
+ var startedAt = 0L
181
+ var timer: Runnable? = null
182
+ var removal: Runnable? = null
183
+ var entered = false
184
+ var dragStart = 0f
185
+ }
186
+
187
+ /**
188
+ * Draws the message toasts in the activity's `toast` overlay layer: stacking,
189
+ * timers, swipe and motion all live here, on the main thread.
190
+ */
191
+ internal class NativeOverlayToastPresenter(private val hostView: View) {
192
+ var onEvent: ((id: String, generation: Int, type: String, value: String) -> Unit)? = null
193
+
194
+ private val handler = Handler(Looper.getMainLooper())
195
+ private val context: Context get() = hostView.context
196
+ private val density: Float get() = context.resources.displayMetrics.density
197
+ /** Rides under whatever hangs from the top of the window. */
198
+ private var stage: FrameLayout? = null
199
+ private var entries = mutableListOf<ToastEntry>() // newest first
200
+ private var config = ToasterConfig()
201
+ private var pressed = 0
202
+ private var obstructionShift = 0f
203
+
204
+ private val reduceMotion: Boolean
205
+ get() = config.respectReducedMotion &&
206
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
207
+ !ValueAnimator.areAnimatorsEnabled()
208
+
209
+ private fun dp(value: Float): Int = (value * density).roundToInt()
210
+
211
+ private val activity: Activity?
212
+ get() = (context as? ThemedReactContext)?.currentActivity
213
+
214
+ // region Sync
215
+
216
+ fun sync(items: List<ToastItem>, next: ToasterConfig) {
217
+ val configChanged = next.cardColor != config.cardColor
218
+ config = next
219
+ val present = items.map { it.spec.id }.toSet()
220
+ // Cards the list no longer knows leave without ceremony.
221
+ entries.filter { it.id !in present }.forEach { remove(it, report = false) }
222
+ // Oldest first, so each new card joins in front of the previous one.
223
+ for (item in items.asReversed()) {
224
+ var entry = entries.firstOrNull { it.id == item.spec.id }
225
+ if (entry != null && entry.leaving && item.visible) {
226
+ // Shown again while the previous card was leaving.
227
+ remove(entry, report = false)
228
+ entry = null
229
+ }
230
+ if (entry == null) {
231
+ if (item.visible) add(item) else onEvent?.invoke(item.spec.id, item.generation, "close", "programmatic")
232
+ continue
233
+ }
234
+ if (entry.item.revision != item.revision || configChanged) {
235
+ entry.slot.card.apply(item.spec, config.cardColor)
236
+ }
237
+ if (entry.item.generation != item.generation) {
238
+ // Shown again: the toast starts its lifetime over.
239
+ cancelTimer(entry)
240
+ entry.remaining = lifetime(item.spec)
241
+ }
242
+ entry.item = item
243
+ if (!item.visible) dismiss(entry, "programmatic", report = false)
244
+ }
245
+ layout(animated = true)
246
+ syncTimers()
247
+ }
248
+
249
+ fun invalidate() {
250
+ entries.forEach { entry ->
251
+ cancelTimer(entry)
252
+ entry.removal?.let(handler::removeCallbacks)
253
+ entry.slot.card.cancelLoads()
254
+ }
255
+ entries.clear()
256
+ releaseStage()
257
+ }
258
+
259
+ private fun lifetime(spec: ToastSpec): Long? =
260
+ if (spec.duration >= 0) spec.duration.toLong() else null
261
+
262
+ // endregion
263
+
264
+ // region Stage
265
+
266
+ private fun ensureStage(): FrameLayout? {
267
+ stage?.let { if (it.parent != null) return it }
268
+ val activity = activity ?: return null
269
+ val layer = stage ?: FrameLayout(context).apply {
270
+ clipChildren = false
271
+ clipToPadding = false
272
+ addOnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
273
+ if (right - left != oldRight - oldLeft || bottom - top != oldBottom - oldTop) {
274
+ // A new window size moves every card; wait for the layout pass to end.
275
+ handler.post { layout(animated = false) }
276
+ }
277
+ }
278
+ }
279
+ stage = layer
280
+ NativeOverlayHost.of(activity).attachToastLayer(layer)
281
+ ViewCompat.setOnApplyWindowInsetsListener(layer) { _, insets ->
282
+ handler.post { layout(animated = true) }
283
+ insets
284
+ }
285
+ return layer
286
+ }
287
+
288
+ private fun releaseStage() {
289
+ val layer = stage ?: return
290
+ layer.removeAllViews()
291
+ activity?.let { NativeOverlayHost.of(it).detachToastLayer(layer) }
292
+ ?: (layer.parent as? ViewGroup)?.removeView(layer)
293
+ obstructionShift = 0f
294
+ layer.translationY = 0f
295
+ }
296
+
297
+ /** The host joined a window: draw the toasts that were waiting for one. */
298
+ fun hostAttached() {
299
+ if (entries.isEmpty()) return
300
+ val layer = ensureStage() ?: return
301
+ entries.asReversed().filter { it.slot.parent == null }.forEach { attach(it, layer) }
302
+ layout(animated = true)
303
+ syncTimers()
304
+ }
305
+
306
+ // endregion
307
+
308
+ // region Cards
309
+
310
+ private fun add(item: ToastItem) {
311
+ val card = NativeOverlayToastCardView(context)
312
+ val slot = ToastSlot(context, card)
313
+ val entry = ToastEntry(item.spec.id, item, slot)
314
+ entry.remaining = lifetime(item.spec)
315
+ card.onAction = { actionId -> if (!entry.leaving) onEvent?.invoke(entry.id, entry.item.generation, "action", actionId) }
316
+ card.onLink = { link -> if (!entry.leaving) onEvent?.invoke(entry.id, entry.item.generation, "link", link) }
317
+ card.apply(item.spec, config.cardColor)
318
+ slot.onPressChanged = { down ->
319
+ pressed = if (down) pressed + 1 else max(0, pressed - 1)
320
+ syncTimers()
321
+ }
322
+ slot.onDrag = { translation ->
323
+ if (!entry.leaving) {
324
+ // Toasts land at the top, so the dismiss direction is up.
325
+ card.translationY =
326
+ if (translation <= 0) translation else translation / ToasterMetrics.SWIPE_RESISTANCE
327
+ }
328
+ }
329
+ slot.onRelease = { translationY, translationX, velocityY, cancelled ->
330
+ if (!entry.leaving) {
331
+ val distance = -translationY / density
332
+ val velocity = -velocityY / density
333
+ val dismissed = !cancelled && translationY < 0 && abs(translationY) > abs(translationX) &&
334
+ (distance >= ToasterMetrics.SWIPE_DISTANCE ||
335
+ (distance >= ToasterMetrics.SWIPE_FLICK_DISTANCE && velocity >= ToasterMetrics.SWIPE_FLICK_VELOCITY))
336
+ if (dismissed) dismiss(entry, "swipe", report = true) else settle(card)
337
+ }
338
+ }
339
+ val press = {
340
+ if (!entry.leaving && entry.item.spec.pressable) {
341
+ onEvent?.invoke(entry.id, entry.item.generation, "press", "")
342
+ }
343
+ }
344
+ card.onPress = press
345
+ slot.onTap = press
346
+ entries.add(0, entry)
347
+ ensureStage()?.let { attach(entry, it) }
348
+ }
349
+
350
+ private fun attach(entry: ToastEntry, layer: FrameLayout) {
351
+ entry.slot.alpha = 0f
352
+ layer.addView(
353
+ entry.slot,
354
+ FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT),
355
+ )
356
+ if (layer.importantForAccessibility != View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
357
+ entry.slot.announceForAccessibility(entry.slot.card.announcement)
358
+ }
359
+ }
360
+
361
+ private fun settle(card: View) {
362
+ if (reduceMotion) {
363
+ card.translationY = 0f
364
+ return
365
+ }
366
+ card.animate().translationY(0f).setDuration(ToasterMetrics.ANIMATION_MS)
367
+ .setInterpolator(toastInterpolator).start()
368
+ }
369
+
370
+ private fun dismiss(entry: ToastEntry, reason: String, report: Boolean) {
371
+ if (entry.leaving) return
372
+ entry.leaving = true
373
+ entry.reason = reason
374
+ cancelTimer(entry)
375
+ if (report) onEvent?.invoke(entry.id, entry.item.generation, "dismiss", reason)
376
+ val removal = Runnable {
377
+ remove(entry, report = true)
378
+ layout(animated = true)
379
+ }
380
+ entry.removal = removal
381
+ handler.postDelayed(removal, ToasterMetrics.REMOVE_DELAY_MS)
382
+ layout(animated = true)
383
+ }
384
+
385
+ private fun remove(entry: ToastEntry, report: Boolean) {
386
+ cancelTimer(entry)
387
+ entry.removal?.let(handler::removeCallbacks)
388
+ entry.slot.card.cancelLoads()
389
+ entry.slot.animate().cancel()
390
+ (entry.slot.parent as? ViewGroup)?.removeView(entry.slot)
391
+ entries.remove(entry)
392
+ if (report) onEvent?.invoke(entry.id, entry.item.generation, "close", entry.reason)
393
+ if (entries.isEmpty()) {
394
+ pressed = 0
395
+ releaseStage()
396
+ }
397
+ }
398
+
399
+ // endregion
400
+
401
+ // region Layout
402
+
403
+ private fun computeObstructionShift(layer: View, topInset: Int, bottomInset: Int): Float {
404
+ if (config.topObstruction <= 0f) return 0f
405
+ val toastTop = topInset + dp(ToasterMetrics.TOP_OFFSET)
406
+ val usableBottom = layer.height - bottomInset
407
+ val top = min(
408
+ dp(config.topObstruction + config.topObstructionGap),
409
+ usableBottom - dp(config.topObstructionRoom),
410
+ )
411
+ return max(0, top - toastTop).toFloat()
412
+ }
413
+
414
+ private fun layout(animated: Boolean) {
415
+ val layer = stage ?: return
416
+ if (entries.isEmpty() || layer.width == 0) return
417
+ val insets = ViewCompat.getRootWindowInsets(layer)
418
+ val bars = insets?.getInsets(
419
+ WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout(),
420
+ )
421
+ val ime = insets?.getInsets(WindowInsetsCompat.Type.ime())
422
+ val topInset = bars?.top ?: 0
423
+ // The keyboard's top edge while it is up, the system bar's otherwise.
424
+ val bottomInset = max(bars?.bottom ?: 0, ime?.bottom ?: 0)
425
+ val animate = animated && !reduceMotion
426
+
427
+ val shift = computeObstructionShift(layer, topInset, bottomInset)
428
+ if (shift != obstructionShift) {
429
+ obstructionShift = shift
430
+ if (animate) {
431
+ layer.animate().translationY(shift).setDuration(ToasterMetrics.OBSTRUCTION_MS)
432
+ .setInterpolator(toastInterpolator).start()
433
+ } else {
434
+ layer.animate().cancel()
435
+ layer.translationY = shift
436
+ }
437
+ }
438
+
439
+ val contentWidth = config.contentWidth
440
+ ?: (min(layer.width / density, ToasterMetrics.FALLBACK_MAX_PAGE_WIDTH) - ToasterMetrics.FALLBACK_MARGIN)
441
+ val contentMaxHeight = config.contentMaxHeight ?: 0f
442
+ val top = topInset + dp(ToasterMetrics.TOP_OFFSET)
443
+ val left = bars?.left ?: 0
444
+ val right = bars?.right ?: 0
445
+ // The replaced toaster centred a lane of at most 360dp and centred the
446
+ // card in it; both offsets were rounded on their own.
447
+ val available = (layer.width - left - right).toDouble()
448
+ val lane = min(available / density - ToasterMetrics.LANE_MARGIN, ToasterMetrics.LANE_MAX_WIDTH.toDouble())
449
+ val laneLeft = (available - lane * density) / 2
450
+ val cardOffset = (lane - (contentWidth + 2 * ToasterMetrics.CARD_PADDING_HORIZONTAL)) * density / 2
451
+ val originX = left + laneLeft + cardOffset
452
+ val drawnX = left + snapHalfUp(laneLeft) + snapHalfUp(cardOffset)
453
+ val originY = topInset + (ToasterMetrics.TOP_OFFSET * density).toDouble()
454
+ // Oldest at the top, newest under it: a toast keeps its place when a newer
455
+ // one arrives and moves up when an older one leaves.
456
+ var offset = 0
457
+ for (entry in entries.asReversed()) {
458
+ val slot = entry.slot
459
+ val card = slot.card
460
+ if (card.contentWidth != contentWidth || card.contentMaxHeight != contentMaxHeight ||
461
+ card.originX != originX || card.originY != originY
462
+ ) {
463
+ card.contentWidth = contentWidth
464
+ card.contentMaxHeight = contentMaxHeight
465
+ card.originX = originX
466
+ card.originY = originY
467
+ card.requestLayout()
468
+ }
469
+ slot.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
470
+ val height = slot.measuredHeight
471
+ // Where the card rests before it enters and after it leaves.
472
+ val hidden = -(if (height > 0) height else dp(ToasterMetrics.FALLBACK_HEIGHT)) -
473
+ topInset - dp(ToasterMetrics.ENTER_OVERSHOOT)
474
+ val targetY = (top + if (entry.leaving) hidden else offset).toFloat()
475
+ val targetAlpha = if (entry.leaving) 0f else 1f
476
+ if (!entry.leaving) offset += height + dp(ToasterMetrics.GUTTER)
477
+ slot.translationX = drawnX.toFloat()
478
+ if (!entry.entered) {
479
+ entry.entered = true
480
+ slot.translationY = (top + hidden).toFloat()
481
+ }
482
+ if (animate) {
483
+ slot.animate().translationY(targetY).alpha(targetAlpha)
484
+ .setDuration(ToasterMetrics.ANIMATION_MS).setInterpolator(toastInterpolator).start()
485
+ } else {
486
+ slot.animate().cancel()
487
+ slot.translationY = targetY
488
+ slot.alpha = targetAlpha
489
+ }
490
+ }
491
+ }
492
+
493
+ // endregion
494
+
495
+ // region Timers
496
+
497
+ private fun cancelTimer(entry: ToastEntry) {
498
+ entry.timer?.let(handler::removeCallbacks)
499
+ entry.timer = null
500
+ }
501
+
502
+ private fun syncTimers() {
503
+ val paused = pressed > 0
504
+ val now = SystemClock.uptimeMillis()
505
+ for (entry in entries) {
506
+ if (entry.leaving) continue
507
+ val remaining = entry.remaining ?: continue
508
+ if (paused) {
509
+ if (entry.timer != null) {
510
+ entry.remaining = max(0L, remaining - (now - entry.startedAt))
511
+ cancelTimer(entry)
512
+ }
513
+ continue
514
+ }
515
+ if (entry.timer != null) continue
516
+ entry.startedAt = now
517
+ val timer = Runnable {
518
+ entry.timer = null
519
+ dismiss(entry, "timeout", report = true)
520
+ }
521
+ entry.timer = timer
522
+ handler.postDelayed(timer, max(remaining, 0L))
523
+ }
524
+ }
525
+
526
+ // endregion
527
+ }
528
+
529
+ /**
530
+ * The zero-size host mounted by `OverlayToastHost`. It only carries the toast
531
+ * list and settings across the bridge; the cards are drawn in the activity's
532
+ * `toast` overlay layer.
533
+ */
534
+ @SuppressLint("ViewConstructor")
535
+ class NativeOverlayToasterView(context: ThemedReactContext) : View(context) {
536
+ var onToastEvent: ((id: String, generation: Int, type: String, value: String) -> Unit)? = null
537
+
538
+ private val presenter = NativeOverlayToastPresenter(this).also { presenter ->
539
+ presenter.onEvent = { id, generation, type, value -> onToastEvent?.invoke(id, generation, type, value) }
540
+ }
541
+ private var toasts: String? = null
542
+ private var config: String? = null
543
+ private var dirty = false
544
+
545
+ fun setToasts(value: String?) {
546
+ if (value != toasts) {
547
+ toasts = value
548
+ dirty = true
549
+ }
550
+ }
551
+
552
+ fun setConfig(value: String?) {
553
+ if (value != config) {
554
+ config = value
555
+ dirty = true
556
+ }
557
+ }
558
+
559
+ /** Called once per props transaction. */
560
+ fun commit() {
561
+ if (!dirty) return
562
+ dirty = false
563
+ presenter.sync(ToastItem.parseList(toasts), ToasterConfig.parse(config))
564
+ }
565
+
566
+ override fun onAttachedToWindow() {
567
+ super.onAttachedToWindow()
568
+ presenter.hostAttached()
569
+ }
570
+
571
+ fun invalidateHost() {
572
+ presenter.invalidate()
573
+ }
574
+ }
@@ -0,0 +1,54 @@
1
+ package com.onekey.nativeoverlay
2
+
3
+ import com.facebook.react.module.annotations.ReactModule
4
+ import com.facebook.react.uimanager.SimpleViewManager
5
+ import com.facebook.react.uimanager.ThemedReactContext
6
+ import com.facebook.react.uimanager.UIManagerHelper
7
+ import com.facebook.react.uimanager.ViewManagerDelegate
8
+ import com.facebook.react.viewmanagers.RNCNativeOverlayToasterManagerDelegate
9
+ import com.facebook.react.viewmanagers.RNCNativeOverlayToasterManagerInterface
10
+
11
+ /** No React children: the toast cards are drawn natively from the props. */
12
+ @ReactModule(name = NativeOverlayToasterViewManager.NAME)
13
+ class NativeOverlayToasterViewManager :
14
+ SimpleViewManager<NativeOverlayToasterView>(),
15
+ RNCNativeOverlayToasterManagerInterface<NativeOverlayToasterView> {
16
+ private val delegate =
17
+ RNCNativeOverlayToasterManagerDelegate<NativeOverlayToasterView, NativeOverlayToasterViewManager>(this)
18
+
19
+ override fun getName(): String = NAME
20
+
21
+ override fun getDelegate(): ViewManagerDelegate<NativeOverlayToasterView> = delegate
22
+
23
+ override fun createViewInstance(context: ThemedReactContext): NativeOverlayToasterView {
24
+ val view = NativeOverlayToasterView(context)
25
+ view.onToastEvent = { id, generation, type, value ->
26
+ UIManagerHelper.getEventDispatcherForReactTag(context, view.id)?.dispatchEvent(
27
+ NativeOverlayToastEvent(UIManagerHelper.getSurfaceId(context), view.id, id, generation, type, value),
28
+ )
29
+ }
30
+ return view
31
+ }
32
+
33
+ override fun onAfterUpdateTransaction(view: NativeOverlayToasterView) {
34
+ super.onAfterUpdateTransaction(view)
35
+ view.commit()
36
+ }
37
+
38
+ override fun onDropViewInstance(view: NativeOverlayToasterView) {
39
+ view.invalidateHost()
40
+ super.onDropViewInstance(view)
41
+ }
42
+
43
+ override fun setToasts(view: NativeOverlayToasterView, value: String?) {
44
+ view.setToasts(value)
45
+ }
46
+
47
+ override fun setConfig(view: NativeOverlayToasterView, value: String?) {
48
+ view.setConfig(value)
49
+ }
50
+
51
+ companion object {
52
+ const val NAME = "RNCNativeOverlayToaster"
53
+ }
54
+ }