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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/README.md +139 -48
  2. package/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerManager.kt +15 -0
  3. package/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerView.kt +315 -59
  4. package/android/src/main/java/com/onekey/bottomtabs/BottomTabsView.kt +426 -53
  5. package/android/src/main/java/com/onekey/bottomtabs/BottomTabsViewManager.kt +6 -5
  6. package/android/src/main/java/com/onekey/bottomtabs/FloatingTabBarStyle.kt +22 -6
  7. package/android/src/main/java/com/onekey/bottomtabs/events/TabDoublePressEvent.kt +7 -1
  8. package/docs/SPEC.md +228 -30
  9. package/ios/RCTBottomTabsComponentView.mm +4 -1
  10. package/ios/RCTBottomTabsContainerView.swift +263 -15
  11. package/ios/RCTBottomTabsDrawerComponentView.mm +24 -0
  12. package/ios/RCTBottomTabsDrawerContainerView.swift +358 -51
  13. package/ios/tests/BottomTabsDrawerReduceMotionTests.swift +291 -0
  14. package/lib/module/BottomTabs.js +85 -58
  15. package/lib/module/BottomTabsDrawerNativeComponent.ts +3 -0
  16. package/lib/module/BottomTabsNativeComponent.ts +6 -1
  17. package/lib/module/index.js +1 -0
  18. package/lib/typescript/src/BottomTabs.d.ts +23 -2
  19. package/lib/typescript/src/BottomTabsDrawerNativeComponent.d.ts +5 -0
  20. package/lib/typescript/src/BottomTabsNativeComponent.d.ts +5 -1
  21. package/lib/typescript/src/index.d.ts +1 -0
  22. package/package.json +1 -1
  23. package/react-native-bottom-tabs.podspec +6 -0
  24. package/src/BottomTabs.tsx +94 -44
  25. package/src/BottomTabsDrawerNativeComponent.ts +3 -0
  26. package/src/BottomTabsNativeComponent.ts +6 -1
  27. package/src/index.tsx +1 -0
@@ -1,16 +1,22 @@
1
1
  package com.onekey.bottomtabs
2
2
 
3
- import android.animation.Animator
4
- import android.animation.AnimatorListenerAdapter
3
+ import android.animation.TimeAnimator
5
4
  import android.animation.ValueAnimator
6
5
  import android.app.Activity
7
6
  import android.content.Context
8
7
  import android.content.ContextWrapper
8
+ import android.content.res.Configuration
9
9
  import android.graphics.Canvas
10
10
  import android.graphics.Color
11
+ import android.graphics.LinearGradient
11
12
  import android.graphics.Matrix
13
+ import android.graphics.Paint
12
14
  import android.graphics.Path
15
+ import android.graphics.RadialGradient
13
16
  import android.graphics.RectF
17
+ import android.graphics.Shader
18
+ import android.os.Build
19
+ import android.provider.Settings
14
20
  import android.view.HapticFeedbackConstants
15
21
  import android.view.MotionEvent
16
22
  import android.view.VelocityTracker
@@ -19,7 +25,6 @@ import android.view.ViewConfiguration
19
25
  import android.view.ViewGroup
20
26
  import android.view.SurfaceView
21
27
  import android.view.TextureView
22
- import android.view.animation.LinearInterpolator
23
28
  import android.widget.FrameLayout
24
29
  import android.widget.AbsSeekBar
25
30
  import android.widget.EditText
@@ -35,18 +40,38 @@ import com.facebook.react.uimanager.PointerEvents
35
40
  import com.facebook.react.uimanager.ReactPointerEventsView
36
41
  import com.facebook.react.uimanager.events.NativeGestureUtil
37
42
  import kotlin.math.abs
43
+ import kotlin.math.cos
38
44
  import kotlin.math.exp
45
+ import kotlin.math.max
46
+ import kotlin.math.min
39
47
  import kotlin.math.roundToInt
48
+ import kotlin.math.sin
49
+ import kotlin.math.sqrt
40
50
  import java.lang.ref.WeakReference
41
51
 
52
+ // Shared with iOS: measured frame by frame from the reference recording.
53
+ private const val MENU_WIDTH_FRACTION = .8f
54
+ private const val PAGE_CORNER_RADIUS_DP = 62f
55
+ private const val MENU_MIN_SCALE = .97f
56
+ private const val SPRING_FREQUENCY = 25.5f
57
+ private const val SPRING_DAMPING = .84f
58
+ private const val PAGE_SHADOW_SIGMA_DP = 18f
59
+ private val PAGE_HAIRLINE_COLOR = Color.argb(43, 255, 255, 255)
60
+
42
61
  private class DrawerContent(context: Context) : FrameLayout(context), ReactPointerEventsView {
43
62
  override var pointerEvents = PointerEvents.AUTO
44
63
  }
45
64
 
46
65
  private class DrawerForeground(context: Context) : FrameLayout(context) {
47
66
  var cornerRadius = 0f
67
+ var hairlineColor = Color.TRANSPARENT
48
68
  private val path = Path()
49
69
  private val rect = RectF()
70
+ // Centered on the clip edge, so one physical pixel shows inside, like a layer border.
71
+ private val hairline = Paint(Paint.ANTI_ALIAS_FLAG).apply {
72
+ style = Paint.Style.STROKE
73
+ strokeWidth = 2f
74
+ }
50
75
  override fun dispatchDraw(canvas: Canvas) {
51
76
  val save = canvas.save()
52
77
  rect.set(0f, 0f, width.toFloat(), height.toFloat())
@@ -55,6 +80,10 @@ private class DrawerForeground(context: Context) : FrameLayout(context) {
55
80
  path.addRoundRect(rect, floatArrayOf(r, r, 0f, 0f, 0f, 0f, r, r), Path.Direction.CW)
56
81
  canvas.clipPath(path)
57
82
  super.dispatchDraw(canvas)
83
+ if (Color.alpha(hairlineColor) > 0) {
84
+ hairline.color = hairlineColor
85
+ canvas.drawPath(path, hairline)
86
+ }
58
87
  canvas.restoreToCount(save)
59
88
  }
60
89
  }
@@ -62,31 +91,78 @@ private class DrawerForeground(context: Context) : FrameLayout(context) {
62
91
  /** React owns two stable slots; translation, input and settling stay on the UI thread. */
63
92
  class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
64
93
  private val menu = DrawerContent(context)
65
- private val menuShade = View(context)
66
94
  private val foreground = DrawerForeground(context)
67
95
  private val content = DrawerContent(context)
68
96
  private val dim = View(context)
69
97
  private val slots = mutableListOf<View>()
70
98
  var onDrawerOpenChange: ((Boolean) -> Unit)? = null
99
+ var onDrawerProgress: ((Float) -> Unit)? = null
71
100
  var swipeEnabled = false
72
101
  var drawerHapticFeedbackEnabled = false
73
102
  var bottomBarHeight = 0f
103
+ /** "light" or "dark" forces that palette; anything else follows the configuration's night mode. */
104
+ var colorScheme = "system"
105
+ set(value) {
106
+ if (field == value) return
107
+ field = value
108
+ applyAppearance()
109
+ setProgress(appliedValue, appliedOvershoot)
110
+ }
111
+ var progressEventsEnabled = false
112
+ set(value) {
113
+ if (field == value) return
114
+ field = value
115
+ // A new subscriber starts from the current position.
116
+ reportedProgress = -1f
117
+ if (value) reportProgress()
118
+ }
74
119
  private var drawerEnabled = false
75
120
  private var requestedOpen = false
76
121
  private var stableOpen = false
77
122
  private var progress = 0f
78
- private var animator: ValueAnimator? = null
123
+ // The last requested position, kept so a layout pass mid-settle does not
124
+ // clip the spring's overshoot back to fully open.
125
+ private var appliedValue = 0f
126
+ private var appliedOvershoot = false
127
+ private var reportedProgress = -1f
128
+ private var animator: TimeAnimator? = null
79
129
  private var animationTarget = false
80
130
  private var animationUser = false
131
+ private var animationFrom = 0f
132
+ private var animationVelocity = 0f
133
+ private var animationDuration = 0f
134
+ // Running speed of the current animation, for handing off to a retarget.
135
+ private var trackedValue = 0f
136
+ private var trackedTime = 0f
137
+ private var trackedVelocity = 0f
138
+ private var dark = false
139
+ private var scrimMaxAlpha = .58f
140
+ private var pageShadowOpacity = 0f
141
+ private val shadowPaint = Paint()
142
+ private var shadowEdge: Shader? = null
143
+ private var shadowTopCorner: Shader? = null
144
+ private var shadowBottomCorner: Shader? = null
145
+ private var shadowRadius = -1f
146
+ private var shadowHeight = -1
147
+ private var shadowOpacity = -1f
81
148
  private var downX = 0f
82
149
  private var downY = 0f
83
150
  private var downProgress = 0f
84
151
  private var gestureReturnOpen = false
85
152
  private var eligible = false
153
+ // The touch started inside the open menu, where only a leftward drag moves it.
154
+ private var downInMenu = false
155
+ // The state a user's release or tap has already confirmed with a haptic,
156
+ // so the transition plays it once, when it is decided rather than landed.
157
+ private var hapticTarget: Boolean? = null
86
158
  private var touchedView: WeakReference<View>? = null
87
159
  private val touchMatrix = Matrix()
88
160
  private val touchPoint = FloatArray(2)
89
161
  private var dragging = false
162
+ // A native gesture start sent to React (by a drag, or by a rightward swipe
163
+ // in the menu that only cancels the row's touch), owed its end however the
164
+ // touch stops. React's pointer dispatcher drops input until it gets one.
165
+ private var nativeGestureStarted = false
90
166
  private var tracker: VelocityTracker? = null
91
167
  private var lastNativeEvent: MotionEvent? = null
92
168
  private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
@@ -97,31 +173,48 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
97
173
  private val backCallback = object : OnBackPressedCallback(false) {
98
174
  override fun handleOnBackPressed() { closeFromUser() }
99
175
  }
176
+ private val menuWidth get() = width * MENU_WIDTH_FRACTION
100
177
 
101
178
  init {
102
179
  clipChildren = true
103
- menuShade.setBackgroundColor(Color.BLACK)
104
- menuShade.isEnabled = false
105
- menuShade.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
106
- dim.setBackgroundColor(Color.rgb(28, 28, 28))
107
180
  dim.contentDescription = "Close menu"
108
181
  dim.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES
109
182
  dim.setOnClickListener { closeFromUser() }
110
- menu.addView(menuShade, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
111
183
  foreground.addView(content, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
112
184
  foreground.addView(dim, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
113
185
  super.addView(menu, LayoutParams(0, LayoutParams.MATCH_PARENT))
114
186
  super.addView(foreground, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
115
187
  initialized = true
188
+ applyAppearance()
116
189
  setProgress(0f)
117
190
  }
118
191
 
192
+ private fun applyAppearance() {
193
+ dark = when (colorScheme) {
194
+ "dark" -> true
195
+ "light" -> false
196
+ else -> (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
197
+ }
198
+ // The page washes toward white in light mode and toward gray in dark mode.
199
+ dim.setBackgroundColor(if (dark) Color.rgb(36, 36, 36) else Color.WHITE)
200
+ scrimMaxAlpha = if (dark) .58f else .5f
201
+ pageShadowOpacity = if (dark) 0f else .16f
202
+ }
203
+
204
+ override fun onConfigurationChanged(newConfig: Configuration?) {
205
+ super.onConfigurationChanged(newConfig)
206
+ if (colorScheme == "light" || colorScheme == "dark") return
207
+ applyAppearance()
208
+ setProgress(appliedValue, appliedOvershoot)
209
+ }
210
+
119
211
  fun setDrawerEnabled(value: Boolean) {
120
212
  if (drawerEnabled == value) return
121
213
  cancelTouch()
122
214
  stopAnimation()
123
215
  drawerEnabled = value
124
216
  stableOpen = false
217
+ hapticTarget = null
125
218
  setProgress(0f)
126
219
  if (value && requestedOpen) settle(true, 0f, false)
127
220
  }
@@ -160,18 +253,18 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
160
253
 
161
254
  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
162
255
  super.onMeasure(widthMeasureSpec, heightMeasureSpec)
163
- menu.measure(MeasureSpec.makeMeasureSpec((measuredWidth * .78f).roundToInt(), MeasureSpec.EXACTLY),
256
+ menu.measure(MeasureSpec.makeMeasureSpec((measuredWidth * MENU_WIDTH_FRACTION).roundToInt(), MeasureSpec.EXACTLY),
164
257
  MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY))
165
258
  }
166
259
 
167
260
  override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
168
261
  layoutSlots()
169
- setProgress(progress)
262
+ setProgress(appliedValue, appliedOvershoot)
170
263
  }
171
264
 
172
265
  private fun layoutSlots() {
173
266
  val exactHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
174
- val menuWidth = (width * .78f).roundToInt()
267
+ val menuWidth = (width * MENU_WIDTH_FRACTION).roundToInt()
175
268
  menu.measure(MeasureSpec.makeMeasureSpec(menuWidth, MeasureSpec.EXACTLY), exactHeight)
176
269
  foreground.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), exactHeight)
177
270
  menu.layout(0, 0, menuWidth, height)
@@ -204,8 +297,11 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
204
297
  touchedView = touchedViewAt(this, event.x, event.y)?.let(::WeakReference)
205
298
  val systemLeft = ViewCompat.getRootWindowInsets(this)
206
299
  ?.getInsets(WindowInsetsCompat.Type.systemGestures())?.left ?: 0
300
+ downInMenu = progress > 0f && event.x < menuWidth * progress
301
+ // While open, the page beside the menu and the menu itself both take
302
+ // the drag; controls inside the menu keep theirs.
207
303
  eligible = drawerEnabled && event.y < height - bottomBarHeight * density &&
208
- (if (progress > 0f) event.x >= width * .78f * progress
304
+ (if (progress > 0f) !downInMenu || !touchPathHasExclusiveControl()
209
305
  else swipeEnabled && event.x >= systemLeft && !touchPathHasExclusiveControl())
210
306
  if (eligible) tracker = VelocityTracker.obtain().also { it.addMovement(event) }
211
307
  }
@@ -230,14 +326,20 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
230
326
  eligible = false
231
327
  return false
232
328
  }
329
+ // Inside the open menu only a leftward drag moves it, which closes it.
330
+ // A rightward one is still a swipe, not a tap on the row under it.
331
+ if (abs(dx) > touchSlop && abs(dx) > abs(dy) && downInMenu && dx > 0f) {
332
+ eligible = false
333
+ startNativeGesture(event)
334
+ return false
335
+ }
233
336
  if (abs(dx) > touchSlop && abs(dx) > abs(dy) && (progress > 0f || dx > 0f)) {
234
337
  gestureReturnOpen = if (animator != null && !animationUser) animationTarget else stableOpen
235
338
  stopAnimation()
236
339
  downProgress = progress
237
340
  dragging = true
238
341
  parent?.requestDisallowInterceptTouchEvent(true)
239
- NativeGestureUtil.notifyNativeGestureStarted(this, event)
240
- rememberNativeEvent(event)
342
+ startNativeGesture(event)
241
343
  return true
242
344
  }
243
345
  }
@@ -328,14 +430,14 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
328
430
  rememberNativeEvent(event)
329
431
  tracker?.addMovement(event)
330
432
  when (event.actionMasked) {
331
- MotionEvent.ACTION_MOVE -> setProgress(downProgress + (event.x - downX) / maxOf(1f, width * .78f))
433
+ MotionEvent.ACTION_MOVE -> setProgress(downProgress + (event.x - downX) / maxOf(1f, menuWidth))
332
434
  MotionEvent.ACTION_UP -> {
333
- setProgress(downProgress + (event.x - downX) / maxOf(1f, width * .78f))
435
+ setProgress(downProgress + (event.x - downX) / maxOf(1f, menuWidth))
334
436
  tracker?.computeCurrentVelocity(1000)
335
- val velocity = ((tracker?.xVelocity ?: 0f) / maxOf(1f, width * .78f)).coerceIn(-8f, 8f)
437
+ val velocity = ((tracker?.xVelocity ?: 0f) / maxOf(1f, menuWidth)).coerceIn(-12f, 12f)
336
438
  val target = progress + velocity * .12f >= .5f
337
439
  cancelTouch()
338
- settle(target, velocity, true)
440
+ settle(target, velocity, true, tween = false)
339
441
  }
340
442
  MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> {
341
443
  cancelTouch()
@@ -350,11 +452,18 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
350
452
  lastNativeEvent = MotionEvent.obtain(event)
351
453
  }
352
454
 
455
+ private fun startNativeGesture(event: MotionEvent) {
456
+ NativeGestureUtil.notifyNativeGestureStarted(this, event)
457
+ nativeGestureStarted = true
458
+ rememberNativeEvent(event)
459
+ }
460
+
353
461
  private fun cancelTouch() {
354
- if (dragging) {
462
+ if (nativeGestureStarted) {
355
463
  lastNativeEvent?.let { NativeGestureUtil.notifyNativeGestureEnded(this, it) }
356
- parent?.requestDisallowInterceptTouchEvent(false)
357
464
  }
465
+ if (dragging) parent?.requestDisallowInterceptTouchEvent(false)
466
+ nativeGestureStarted = false
358
467
  dragging = false
359
468
  eligible = false
360
469
  touchedView = null
@@ -369,74 +478,220 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
369
478
  settle(false, 0f, true)
370
479
  }
371
480
 
372
- private fun setProgress(value: Float) {
373
- progress = (if (drawerEnabled) value else 0f).coerceIn(0f, 1f)
374
- foreground.translationX = width * .78f * progress
375
- foreground.cornerRadius = 64f * density * progress
481
+ private fun setProgress(value: Float, overshoot: Boolean = false) {
482
+ appliedValue = value
483
+ appliedOvershoot = overshoot
484
+ val raw = if (drawerEnabled) value else 0f
485
+ progress = raw.coerceIn(0f, 1f)
486
+ val visible = progress > 0f
487
+ // Only the settle spring may carry the page a few pixels past open.
488
+ val travel = if (overshoot) raw.coerceIn(0f, 1.03f) else progress
489
+ foreground.translationX = menuWidth * travel
490
+ // Rounds in over the first 10% so screens with other corner radii never pop.
491
+ foreground.cornerRadius = PAGE_CORNER_RADIUS_DP * density * min(1f, progress / .1f)
492
+ foreground.hairlineColor = if (visible && dark) PAGE_HAIRLINE_COLOR else Color.TRANSPARENT
376
493
  foreground.invalidate()
377
- dim.alpha = .7f * progress
378
- dim.visibility = if (progress > 0f) VISIBLE else INVISIBLE
379
- dim.isEnabled = progress > 0f
380
- content.pointerEvents = if (progress > 0f) PointerEvents.NONE else PointerEvents.AUTO
381
- content.importantForAccessibility = if (progress > 0f) IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
494
+ // The page shadow is drawn by this host, beneath the foreground.
495
+ invalidate()
496
+ dim.alpha = scrimMaxAlpha * progress
497
+ dim.visibility = if (visible) VISIBLE else INVISIBLE
498
+ dim.isEnabled = visible
499
+ content.pointerEvents = if (visible) PointerEvents.NONE else PointerEvents.AUTO
500
+ content.importantForAccessibility = if (visible) IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
382
501
  else IMPORTANT_FOR_ACCESSIBILITY_AUTO
383
- menu.translationX = -.12f * width * .78f * (1f - progress)
384
- menuShade.alpha = .12f * (1f - progress)
385
- menu.visibility = if (progress > 0f) VISIBLE else INVISIBLE
386
- menu.pointerEvents = if (progress > 0f) PointerEvents.AUTO else PointerEvents.NONE
387
- menu.importantForAccessibility = if (progress > 0f) IMPORTANT_FOR_ACCESSIBILITY_AUTO
502
+ // The menu grows from its left-center edge and fades in over whatever is
503
+ // behind the host, fully visible by 60% open.
504
+ val minScale = if (animationsEnabled()) MENU_MIN_SCALE else 1f
505
+ val scale = minScale + (1f - minScale) * progress
506
+ menu.pivotX = 0f
507
+ menu.pivotY = menu.height / 2f
508
+ menu.scaleX = scale
509
+ menu.scaleY = scale
510
+ menu.alpha = min(1f, progress / .6f)
511
+ // A partially transparent menu composites from one cached layer per frame.
512
+ val layer = if (menu.alpha > 0f && menu.alpha < 1f) LAYER_TYPE_HARDWARE else LAYER_TYPE_NONE
513
+ if (menu.layerType != layer) menu.setLayerType(layer, null)
514
+ menu.visibility = if (visible) VISIBLE else INVISIBLE
515
+ menu.pointerEvents = if (visible) PointerEvents.AUTO else PointerEvents.NONE
516
+ menu.importantForAccessibility = if (visible) IMPORTANT_FOR_ACCESSIBILITY_AUTO
388
517
  else IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
389
518
  updateBackCallback()
519
+ reportProgress()
390
520
  }
391
521
 
392
- private fun settle(open: Boolean, velocity: Float, user: Boolean) {
393
- stopAnimation()
522
+ private fun reportProgress() {
523
+ if (!progressEventsEnabled) return
524
+ if (progress != reportedProgress && (abs(progress - reportedProgress) >= .002f || progress == 0f || progress == 1f)) {
525
+ reportedProgress = progress
526
+ onDrawerProgress?.invoke(progress)
527
+ }
528
+ }
529
+
530
+ override fun drawChild(canvas: Canvas, child: View, drawingTime: Long): Boolean {
531
+ if (child === foreground && progress > 0f && pageShadowOpacity > 0f) drawPageShadow(canvas)
532
+ return super.drawChild(canvas, child, drawingTime)
533
+ }
534
+
535
+ // A Gaussian shadow (no offset) around the page's left edge and corners,
536
+ // matching the iOS layer shadow without an offscreen blur.
537
+ private fun drawPageShadow(canvas: Canvas) {
538
+ val sigma = PAGE_SHADOW_SIGMA_DP * density
539
+ val extent = sigma * 3f
540
+ val r = foreground.cornerRadius
541
+ if (r != shadowRadius || height != shadowHeight || pageShadowOpacity != shadowOpacity) {
542
+ shadowRadius = r
543
+ shadowHeight = height
544
+ shadowOpacity = pageShadowOpacity
545
+ val stops = 8
546
+ val positions = FloatArray(stops) { it / (stops - 1f) }
547
+ // Outermost stop first: alpha at distance d outside the edge.
548
+ val edgeColors = IntArray(stops) { shadowColor(extent * (1f - positions[it]), sigma) }
549
+ shadowEdge = LinearGradient(-extent, 0f, 0f, 0f, edgeColors, positions, Shader.TileMode.CLAMP)
550
+ val outer = r + extent
551
+ val cornerPositions = FloatArray(stops) { (r + extent * it / (stops - 1f)) / outer }
552
+ val cornerColors = IntArray(stops) { shadowColor(extent * it / (stops - 1f), sigma) }
553
+ shadowTopCorner = RadialGradient(r, r, outer, cornerColors, cornerPositions, Shader.TileMode.CLAMP)
554
+ shadowBottomCorner = RadialGradient(r, height - r, outer, cornerColors, cornerPositions, Shader.TileMode.CLAMP)
555
+ }
556
+ val save = canvas.save()
557
+ canvas.translate(foreground.left + foreground.translationX, foreground.top.toFloat())
558
+ shadowPaint.shader = shadowEdge
559
+ canvas.drawRect(-extent, r, 0f, height - r, shadowPaint)
560
+ if (r > 0f) {
561
+ shadowPaint.shader = shadowTopCorner
562
+ canvas.drawRect(-extent, -extent, r, r, shadowPaint)
563
+ shadowPaint.shader = shadowBottomCorner
564
+ canvas.drawRect(-extent, height - r, r, height + extent, shadowPaint)
565
+ }
566
+ canvas.restoreToCount(save)
567
+ }
568
+
569
+ private fun shadowColor(distance: Float, sigma: Float): Int {
570
+ val z = distance / sigma
571
+ // 1 - Φ(z), the share of a Gaussian blur that spills past an edge.
572
+ val t = 1f / (1f + .2316419f * z)
573
+ val tail = .3989423f * exp(-z * z / 2f) *
574
+ t * (.31938153f + t * (-.356563782f + t * (1.781477937f + t * (-1.821255978f + t * 1.330274429f))))
575
+ return Color.argb((pageShadowOpacity * tail * 255f).roundToInt().coerceIn(0, 255), 0, 0, 0)
576
+ }
577
+
578
+ private fun animationsEnabled(): Boolean =
579
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) ValueAnimator.areAnimatorsEnabled()
580
+ else Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) != 0f
581
+
582
+ // cubic-bezier(0.55, 0.6, 0.2, 1), fitted to the reference tap open and close.
583
+ private fun pageCurve(x: Float): Float {
584
+ fun bezier(t: Float, p1: Float, p2: Float): Float {
585
+ val u = 1f - t
586
+ return 3f * u * u * t * p1 + 3f * u * t * t * p2 + t * t * t
587
+ }
588
+ var low = 0f
589
+ var high = 1f
590
+ repeat(24) {
591
+ val mid = (low + high) / 2f
592
+ if (bezier(mid, .55f, .2f) < x) low = mid else high = mid
593
+ }
594
+ return bezier((low + high) / 2f, .6f, 1f)
595
+ }
596
+
597
+ // Taps and programmatic changes ease over a fixed time; a released drag
598
+ // keeps its finger velocity through a slightly underdamped spring.
599
+ private fun settle(open: Boolean, velocity: Float, user: Boolean, tween: Boolean = true) {
394
600
  val target = drawerEnabled && open
601
+ // The haptic marks the decision: it plays as a user's release or tap
602
+ // commits to the other state, not when the drawer lands there.
603
+ if (user && target != stableOpen && hapticTarget != target) {
604
+ hapticTarget = target
605
+ if (drawerHapticFeedbackEnabled) performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK)
606
+ }
607
+ // An animation already heading there keeps running; the newer request
608
+ // still decides whether its completion is a user event.
609
+ if (animator != null && animationTarget == target) {
610
+ animationUser = user
611
+ return
612
+ }
613
+ // Reversing mid-flight continues from the page's on-screen position and
614
+ // speed, so the motion bends instead of stopping dead.
615
+ val retarget = animator != null
616
+ val from = if (retarget) appliedValue else progress
617
+ val carried = if (retarget) trackedVelocity else velocity
618
+ stopAnimation()
395
619
  if (width == 0 || !isAttachedToWindow) {
396
620
  stableOpen = target
621
+ hapticTarget = null
397
622
  setProgress(if (target) 1f else 0f)
398
623
  return
399
624
  }
400
- if (progress == if (target) 1f else 0f) {
625
+ if (!retarget && progress == if (target) 1f else 0f) {
626
+ finish(target, user)
627
+ return
628
+ }
629
+ // With system animations removed, the drawer lands without moving.
630
+ if (!animationsEnabled()) {
401
631
  finish(target, user)
402
632
  return
403
633
  }
404
- val end = if (target) 1f else 0f
405
- val a = progress - end
406
- val b = velocity.coerceIn(-8f, 8f) + 22f * a
634
+ animationFrom = from
635
+ animationVelocity = carried.coerceIn(-12f, 12f)
407
636
  animationTarget = target
408
637
  animationUser = user
409
- val next = ValueAnimator.ofFloat(0f, .5f)
410
- next.duration = 500
411
- next.interpolator = LinearInterpolator()
412
- next.addUpdateListener {
413
- val time = it.animatedValue as Float
414
- setProgress(end + (a + b * time) * exp(-22f * time))
415
- }
416
- next.addListener(object : AnimatorListenerAdapter() {
417
- override fun onAnimationEnd(animation: Animator) {
418
- if (animator !== animation) return
419
- animator = null
420
- finish(target, user)
421
- }
422
- })
638
+ // Closing runs about 20% shorter than opening.
639
+ val fullDuration = if (target) .36f else .29f
640
+ animationDuration = if (tween && !retarget) max(.12f, fullDuration * abs((if (target) 1f else 0f) - from)) else 0f
641
+ trackedValue = from
642
+ trackedTime = 0f
643
+ trackedVelocity = animationVelocity
644
+ val next = TimeAnimator()
645
+ next.setTimeListener { animation, totalTime, _ -> tick(animation, totalTime / 1000f) }
423
646
  animator = next
424
647
  next.start()
425
648
  }
426
649
 
650
+ private fun tick(animation: TimeAnimator, elapsed: Float) {
651
+ if (animator !== animation) return
652
+ val end = if (animationTarget) 1f else 0f
653
+ val spring = animationDuration == 0f
654
+ val value: Float
655
+ var tweenDone = false
656
+ if (!spring) {
657
+ val x = min(1f, elapsed / animationDuration)
658
+ value = animationFrom + (end - animationFrom) * pageCurve(x)
659
+ tweenDone = x >= 1f
660
+ } else {
661
+ val w = SPRING_FREQUENCY
662
+ val z = SPRING_DAMPING
663
+ val a = animationFrom - end
664
+ val wd = w * sqrt(1f - z * z)
665
+ val decay = exp(-z * w * elapsed)
666
+ value = end + decay * (a * cos(wd * elapsed) + (animationVelocity + z * w * a) / wd * sin(wd * elapsed))
667
+ }
668
+ if (elapsed > trackedTime) trackedVelocity = (value - trackedValue) / (elapsed - trackedTime)
669
+ trackedValue = value
670
+ trackedTime = elapsed
671
+ setProgress(value, spring)
672
+ // A spring ends once it is visually at rest, not after a fixed time.
673
+ val done = if (spring) (abs(value - end) < .0005f && abs(trackedVelocity) < .02f) || elapsed >= .6f
674
+ else tweenDone
675
+ if (done) {
676
+ val target = animationTarget
677
+ val user = animationUser
678
+ stopAnimation()
679
+ finish(target, user)
680
+ }
681
+ }
682
+
427
683
  private fun finish(target: Boolean, user: Boolean) {
428
684
  val changed = stableOpen != target
429
685
  stableOpen = target
686
+ hapticTarget = null
430
687
  setProgress(if (target) 1f else 0f)
431
688
  if (user && (changed || target != requestedOpen)) {
432
- if (drawerHapticFeedbackEnabled && changed) performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK)
433
689
  onDrawerOpenChange?.invoke(target)
434
690
  }
435
691
  }
436
692
 
437
693
  private fun stopAnimation() {
438
- animator?.removeAllListeners()
439
- animator?.removeAllUpdateListeners()
694
+ animator?.setTimeListener(null)
440
695
  animator?.cancel()
441
696
  animator = null
442
697
  }
@@ -489,6 +744,7 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) {
489
744
  detached = true
490
745
  cancelTouch()
491
746
  stopAnimation()
747
+ hapticTarget = null
492
748
  backCallback.remove()
493
749
  backRegistered = false
494
750
  setProgress(if (stableOpen && drawerEnabled) 1f else 0f)