From b51d937515c018c4354d72a135b4c33ff906173b Mon Sep 17 00:00:00 2001 From: Franco Date: Sat, 14 Nov 2026 16:56:40 +0800 Subject: [PATCH 1/5] feat(bottom-tabs): retune drawer motion, add opt-in progress events - Retune the native left drawer on iOS and Android to a reference recording: 80% travel, a 62pt corner that rounds in over the first 10%, a light wash (white) or dark wash (gray) over the page, a soft page shadow in light mode and a hairline edge in dark mode, and a menu that scales from 0.97 about its left edge while fading in. - Taps and prop changes ease with cubic-bezier(.55, .6, .2, 1) (0.36s open, 0.29s close); released drags settle on a lightly underdamped spring that keeps the finger velocity; reversing mid-flight keeps the current speed. - Reduce Motion cross-fades on iOS; Android lands immediately when system animations are off. - Add onDrawerProgress (sent only while a handler is set), drawerHostComponent and the BottomTabsDrawerNative export so a UI-thread handler can follow the drawer, plus drawerColorScheme for apps whose theme can differ from the platform appearance. - Update the spec, wrapper tests and Android native tests. --- .../__tests__/BottomTabs.drawer.test.tsx | 31 +- .../bottomtabs/BottomTabsDrawerManager.kt | 15 + .../onekey/bottomtabs/BottomTabsDrawerView.kt | 330 +++++++++++++++--- .../react-native-bottom-tabs/docs/SPEC.md | 93 ++++- .../ios/RCTBottomTabsDrawerComponentView.mm | 15 + .../RCTBottomTabsDrawerContainerView.swift | 262 +++++++++++--- .../android/BottomTabsDrawerTest.kt | 64 +++- .../src/BottomTabs.tsx | 28 +- .../src/BottomTabsDrawerNativeComponent.ts | 3 + .../react-native-bottom-tabs/src/index.tsx | 1 + 10 files changed, 716 insertions(+), 126 deletions(-) diff --git a/example/react-native/__tests__/BottomTabs.drawer.test.tsx b/example/react-native/__tests__/BottomTabs.drawer.test.tsx index bb2fbedb3..0cec0cc3e 100644 --- a/example/react-native/__tests__/BottomTabs.drawer.test.tsx +++ b/example/react-native/__tests__/BottomTabs.drawer.test.tsx @@ -72,7 +72,7 @@ describe('native drawer slots', () => { expect(drawer.props.enabled).toBe(false); }); - it('forwards only the settled boolean, with native progress absent from the API', async () => { + it('forwards only the settled boolean, with native progress off unless requested', async () => { const onChange = jest.fn(); await act(() => { renderer = ReactTestRenderer.create( @@ -90,11 +90,40 @@ describe('native drawer slots', () => { const drawer = renderer!.root.findByType('NativeDrawer' as any); expect(drawer.props.hapticFeedbackEnabled).toBe(true); expect(drawer.props.swipeEnabled).toBe(true); + expect(drawer.props.progressEventsEnabled).toBe(false); + expect(drawer.props.onDrawerProgress).toBeUndefined(); + expect(drawer.props.colorScheme).toBeUndefined(); act(() => drawer.props.onDrawerOpenChange({ nativeEvent: { open: true } })); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange).toHaveBeenCalledWith(true); }); + it('passes progress handlers, a replacement host and the color scheme to native as is', async () => { + const onProgress = jest.fn(); + const Host = (props: React.PropsWithChildren) => ( + {props.children} + ); + await act(() => { + renderer = ReactTestRenderer.create( + } + onIndexChange={() => {}} + renderDrawerContent={menu} + onDrawerProgress={onProgress} + drawerHostComponent={Host as any} + drawerColorScheme="dark" + />, + ); + }); + expect(renderer!.root.findAllByType('NativeDrawer' as any)).toHaveLength(0); + const host = renderer!.root.findByType(Host); + expect(host.props.progressEventsEnabled).toBe(true); + expect(host.props.onDrawerProgress).toBe(onProgress); + expect(host.props.colorScheme).toBe('dark'); + expect(renderer!.root.findByProps({ testID: 'menu-content' })).toBeTruthy(); + }); + it('Web omits the menu and returns only the foreground', async () => { await act(() => { renderer = ReactTestRenderer.create( diff --git a/native-views/react-native-bottom-tabs/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerManager.kt b/native-views/react-native-bottom-tabs/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerManager.kt index decccaac7..88b829c10 100644 --- a/native-views/react-native-bottom-tabs/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerManager.kt +++ b/native-views/react-native-bottom-tabs/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerManager.kt @@ -23,6 +23,11 @@ class BottomTabsDrawerManager : ViewGroupManager(), DrawerOpenChangeEvent(UIManagerHelper.getSurfaceId(context), view.id, open), ) } + view.onDrawerProgress = { progress -> + UIManagerHelper.getEventDispatcherForReactTag(context, view.id)?.dispatchEvent( + DrawerProgressEvent(UIManagerHelper.getSurfaceId(context), view.id, progress), + ) + } return view } @@ -36,6 +41,7 @@ class BottomTabsDrawerManager : ViewGroupManager(), override fun needsCustomLayoutForChildren() = true override fun onDropViewInstance(view: BottomTabsDrawerView) { view.onDrawerOpenChange = null + view.onDrawerProgress = null view.dispose() super.onDropViewInstance(view) } @@ -45,6 +51,8 @@ class BottomTabsDrawerManager : ViewGroupManager(), override fun setSwipeEnabled(view: BottomTabsDrawerView, value: Boolean) { view.swipeEnabled = value } override fun setHapticFeedbackEnabled(view: BottomTabsDrawerView, value: Boolean) { view.drawerHapticFeedbackEnabled = value } override fun setBottomBarHeight(view: BottomTabsDrawerView, value: Double) { view.bottomBarHeight = value.toFloat() } + override fun setColorScheme(view: BottomTabsDrawerView, value: String?) { view.colorScheme = value ?: "system" } + override fun setProgressEventsEnabled(view: BottomTabsDrawerView, value: Boolean) { view.progressEventsEnabled = value } } private class DrawerOpenChangeEvent(surfaceId: Int, tag: Int, private val open: Boolean) : @@ -53,3 +61,10 @@ private class DrawerOpenChangeEvent(surfaceId: Int, tag: Int, private val open: override fun canCoalesce() = false override fun getEventData() = Arguments.createMap().apply { putBoolean("open", open) } } + +// Coalescable: a JS listener only needs the latest position per frame. +private class DrawerProgressEvent(surfaceId: Int, tag: Int, private val progress: Float) : + Event(surfaceId, tag) { + override fun getEventName() = "onDrawerProgress" + override fun getEventData() = Arguments.createMap().apply { putDouble("progress", progress.toDouble()) } +} diff --git a/native-views/react-native-bottom-tabs/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerView.kt b/native-views/react-native-bottom-tabs/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerView.kt index 52368a0b4..87aa6e7b0 100644 --- a/native-views/react-native-bottom-tabs/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerView.kt +++ b/native-views/react-native-bottom-tabs/android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerView.kt @@ -1,16 +1,22 @@ package com.onekey.bottomtabs -import android.animation.Animator -import android.animation.AnimatorListenerAdapter +import android.animation.TimeAnimator import android.animation.ValueAnimator import android.app.Activity import android.content.Context import android.content.ContextWrapper +import android.content.res.Configuration import android.graphics.Canvas import android.graphics.Color +import android.graphics.LinearGradient import android.graphics.Matrix +import android.graphics.Paint import android.graphics.Path +import android.graphics.RadialGradient import android.graphics.RectF +import android.graphics.Shader +import android.os.Build +import android.provider.Settings import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.VelocityTracker @@ -19,7 +25,6 @@ import android.view.ViewConfiguration import android.view.ViewGroup import android.view.SurfaceView import android.view.TextureView -import android.view.animation.LinearInterpolator import android.widget.FrameLayout import android.widget.AbsSeekBar import android.widget.EditText @@ -35,18 +40,38 @@ import com.facebook.react.uimanager.PointerEvents import com.facebook.react.uimanager.ReactPointerEventsView import com.facebook.react.uimanager.events.NativeGestureUtil import kotlin.math.abs +import kotlin.math.cos import kotlin.math.exp +import kotlin.math.max +import kotlin.math.min import kotlin.math.roundToInt +import kotlin.math.sin +import kotlin.math.sqrt import java.lang.ref.WeakReference +// Shared with iOS: measured frame by frame from the reference recording. +private const val MENU_WIDTH_FRACTION = .8f +private const val PAGE_CORNER_RADIUS_DP = 62f +private const val MENU_MIN_SCALE = .97f +private const val SPRING_FREQUENCY = 25.5f +private const val SPRING_DAMPING = .84f +private const val PAGE_SHADOW_SIGMA_DP = 18f +private val PAGE_HAIRLINE_COLOR = Color.argb(43, 255, 255, 255) + private class DrawerContent(context: Context) : FrameLayout(context), ReactPointerEventsView { override var pointerEvents = PointerEvents.AUTO } private class DrawerForeground(context: Context) : FrameLayout(context) { var cornerRadius = 0f + var hairlineColor = Color.TRANSPARENT private val path = Path() private val rect = RectF() + // Centered on the clip edge, so one physical pixel shows inside, like a layer border. + private val hairline = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = 2f + } override fun dispatchDraw(canvas: Canvas) { val save = canvas.save() rect.set(0f, 0f, width.toFloat(), height.toFloat()) @@ -55,6 +80,10 @@ private class DrawerForeground(context: Context) : FrameLayout(context) { path.addRoundRect(rect, floatArrayOf(r, r, 0f, 0f, 0f, 0f, r, r), Path.Direction.CW) canvas.clipPath(path) super.dispatchDraw(canvas) + if (Color.alpha(hairlineColor) > 0) { + hairline.color = hairlineColor + canvas.drawPath(path, hairline) + } canvas.restoreToCount(save) } } @@ -62,22 +91,60 @@ private class DrawerForeground(context: Context) : FrameLayout(context) { /** React owns two stable slots; translation, input and settling stay on the UI thread. */ class BottomTabsDrawerView(context: Context) : FrameLayout(context) { private val menu = DrawerContent(context) - private val menuShade = View(context) private val foreground = DrawerForeground(context) private val content = DrawerContent(context) private val dim = View(context) private val slots = mutableListOf() var onDrawerOpenChange: ((Boolean) -> Unit)? = null + var onDrawerProgress: ((Float) -> Unit)? = null var swipeEnabled = false var drawerHapticFeedbackEnabled = false var bottomBarHeight = 0f + /** "light" or "dark" forces that palette; anything else follows the configuration's night mode. */ + var colorScheme = "system" + set(value) { + if (field == value) return + field = value + applyAppearance() + setProgress(appliedValue, appliedOvershoot) + } + var progressEventsEnabled = false + set(value) { + if (field == value) return + field = value + // A new subscriber starts from the current position. + reportedProgress = -1f + if (value) reportProgress() + } private var drawerEnabled = false private var requestedOpen = false private var stableOpen = false private var progress = 0f - private var animator: ValueAnimator? = null + // The last requested position, kept so a layout pass mid-settle does not + // clip the spring's overshoot back to fully open. + private var appliedValue = 0f + private var appliedOvershoot = false + private var reportedProgress = -1f + private var animator: TimeAnimator? = null private var animationTarget = false private var animationUser = false + private var animationFrom = 0f + private var animationVelocity = 0f + private var animationDuration = 0f + // Running speed of the current animation, for handing off to a retarget. + private var trackedValue = 0f + private var trackedTime = 0f + private var trackedVelocity = 0f + private var dark = false + private var scrimMaxAlpha = .58f + private var pageShadowOpacity = 0f + private val shadowPaint = Paint() + private var shadowEdge: Shader? = null + private var shadowTopCorner: Shader? = null + private var shadowBottomCorner: Shader? = null + private var shadowRadius = -1f + private var shadowHeight = -1 + private var shadowOpacity = -1f private var downX = 0f private var downY = 0f private var downProgress = 0f @@ -97,25 +164,41 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) { private val backCallback = object : OnBackPressedCallback(false) { override fun handleOnBackPressed() { closeFromUser() } } + private val menuWidth get() = width * MENU_WIDTH_FRACTION init { clipChildren = true - menuShade.setBackgroundColor(Color.BLACK) - menuShade.isEnabled = false - menuShade.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO - dim.setBackgroundColor(Color.rgb(28, 28, 28)) dim.contentDescription = "Close menu" dim.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES dim.setOnClickListener { closeFromUser() } - menu.addView(menuShade, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) foreground.addView(content, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) foreground.addView(dim, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) super.addView(menu, LayoutParams(0, LayoutParams.MATCH_PARENT)) super.addView(foreground, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) initialized = true + applyAppearance() setProgress(0f) } + private fun applyAppearance() { + dark = when (colorScheme) { + "dark" -> true + "light" -> false + else -> (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES + } + // The page washes toward white in light mode and toward gray in dark mode. + dim.setBackgroundColor(if (dark) Color.rgb(36, 36, 36) else Color.WHITE) + scrimMaxAlpha = if (dark) .58f else .5f + pageShadowOpacity = if (dark) 0f else .16f + } + + override fun onConfigurationChanged(newConfig: Configuration?) { + super.onConfigurationChanged(newConfig) + if (colorScheme == "light" || colorScheme == "dark") return + applyAppearance() + setProgress(appliedValue, appliedOvershoot) + } + fun setDrawerEnabled(value: Boolean) { if (drawerEnabled == value) return cancelTouch() @@ -160,18 +243,18 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) - menu.measure(MeasureSpec.makeMeasureSpec((measuredWidth * .78f).roundToInt(), MeasureSpec.EXACTLY), + menu.measure(MeasureSpec.makeMeasureSpec((measuredWidth * MENU_WIDTH_FRACTION).roundToInt(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY)) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { layoutSlots() - setProgress(progress) + setProgress(appliedValue, appliedOvershoot) } private fun layoutSlots() { val exactHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) - val menuWidth = (width * .78f).roundToInt() + val menuWidth = (width * MENU_WIDTH_FRACTION).roundToInt() menu.measure(MeasureSpec.makeMeasureSpec(menuWidth, MeasureSpec.EXACTLY), exactHeight) foreground.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), exactHeight) menu.layout(0, 0, menuWidth, height) @@ -205,7 +288,7 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) { val systemLeft = ViewCompat.getRootWindowInsets(this) ?.getInsets(WindowInsetsCompat.Type.systemGestures())?.left ?: 0 eligible = drawerEnabled && event.y < height - bottomBarHeight * density && - (if (progress > 0f) event.x >= width * .78f * progress + (if (progress > 0f) event.x >= menuWidth * progress else swipeEnabled && event.x >= systemLeft && !touchPathHasExclusiveControl()) if (eligible) tracker = VelocityTracker.obtain().also { it.addMovement(event) } } @@ -328,14 +411,14 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) { rememberNativeEvent(event) tracker?.addMovement(event) when (event.actionMasked) { - MotionEvent.ACTION_MOVE -> setProgress(downProgress + (event.x - downX) / maxOf(1f, width * .78f)) + MotionEvent.ACTION_MOVE -> setProgress(downProgress + (event.x - downX) / maxOf(1f, menuWidth)) MotionEvent.ACTION_UP -> { - setProgress(downProgress + (event.x - downX) / maxOf(1f, width * .78f)) + setProgress(downProgress + (event.x - downX) / maxOf(1f, menuWidth)) tracker?.computeCurrentVelocity(1000) - val velocity = ((tracker?.xVelocity ?: 0f) / maxOf(1f, width * .78f)).coerceIn(-8f, 8f) + val velocity = ((tracker?.xVelocity ?: 0f) / maxOf(1f, menuWidth)).coerceIn(-12f, 12f) val target = progress + velocity * .12f >= .5f cancelTouch() - settle(target, velocity, true) + settle(target, velocity, true, tween = false) } MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> { cancelTouch() @@ -369,61 +452,201 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) { settle(false, 0f, true) } - private fun setProgress(value: Float) { - progress = (if (drawerEnabled) value else 0f).coerceIn(0f, 1f) - foreground.translationX = width * .78f * progress - foreground.cornerRadius = 64f * density * progress + private fun setProgress(value: Float, overshoot: Boolean = false) { + appliedValue = value + appliedOvershoot = overshoot + val raw = if (drawerEnabled) value else 0f + progress = raw.coerceIn(0f, 1f) + val visible = progress > 0f + // Only the settle spring may carry the page a few pixels past open. + val travel = if (overshoot) raw.coerceIn(0f, 1.03f) else progress + foreground.translationX = menuWidth * travel + // Rounds in over the first 10% so screens with other corner radii never pop. + foreground.cornerRadius = PAGE_CORNER_RADIUS_DP * density * min(1f, progress / .1f) + foreground.hairlineColor = if (visible && dark) PAGE_HAIRLINE_COLOR else Color.TRANSPARENT foreground.invalidate() - dim.alpha = .7f * progress - dim.visibility = if (progress > 0f) VISIBLE else INVISIBLE - dim.isEnabled = progress > 0f - content.pointerEvents = if (progress > 0f) PointerEvents.NONE else PointerEvents.AUTO - content.importantForAccessibility = if (progress > 0f) IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + // The page shadow is drawn by this host, beneath the foreground. + invalidate() + dim.alpha = scrimMaxAlpha * progress + dim.visibility = if (visible) VISIBLE else INVISIBLE + dim.isEnabled = visible + content.pointerEvents = if (visible) PointerEvents.NONE else PointerEvents.AUTO + content.importantForAccessibility = if (visible) IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS else IMPORTANT_FOR_ACCESSIBILITY_AUTO - menu.translationX = -.12f * width * .78f * (1f - progress) - menuShade.alpha = .12f * (1f - progress) - menu.visibility = if (progress > 0f) VISIBLE else INVISIBLE - menu.pointerEvents = if (progress > 0f) PointerEvents.AUTO else PointerEvents.NONE - menu.importantForAccessibility = if (progress > 0f) IMPORTANT_FOR_ACCESSIBILITY_AUTO + // The menu grows from its left-center edge and fades in over whatever is + // behind the host, fully visible by 60% open. + val minScale = if (animationsEnabled()) MENU_MIN_SCALE else 1f + val scale = minScale + (1f - minScale) * progress + menu.pivotX = 0f + menu.pivotY = menu.height / 2f + menu.scaleX = scale + menu.scaleY = scale + menu.alpha = min(1f, progress / .6f) + // A partially transparent menu composites from one cached layer per frame. + val layer = if (menu.alpha > 0f && menu.alpha < 1f) LAYER_TYPE_HARDWARE else LAYER_TYPE_NONE + if (menu.layerType != layer) menu.setLayerType(layer, null) + menu.visibility = if (visible) VISIBLE else INVISIBLE + menu.pointerEvents = if (visible) PointerEvents.AUTO else PointerEvents.NONE + menu.importantForAccessibility = if (visible) IMPORTANT_FOR_ACCESSIBILITY_AUTO else IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS updateBackCallback() + reportProgress() } - private fun settle(open: Boolean, velocity: Float, user: Boolean) { - stopAnimation() + private fun reportProgress() { + if (!progressEventsEnabled) return + if (progress != reportedProgress && (abs(progress - reportedProgress) >= .002f || progress == 0f || progress == 1f)) { + reportedProgress = progress + onDrawerProgress?.invoke(progress) + } + } + + override fun drawChild(canvas: Canvas, child: View, drawingTime: Long): Boolean { + if (child === foreground && progress > 0f && pageShadowOpacity > 0f) drawPageShadow(canvas) + return super.drawChild(canvas, child, drawingTime) + } + + // A Gaussian shadow (no offset) around the page's left edge and corners, + // matching the iOS layer shadow without an offscreen blur. + private fun drawPageShadow(canvas: Canvas) { + val sigma = PAGE_SHADOW_SIGMA_DP * density + val extent = sigma * 3f + val r = foreground.cornerRadius + if (r != shadowRadius || height != shadowHeight || pageShadowOpacity != shadowOpacity) { + shadowRadius = r + shadowHeight = height + shadowOpacity = pageShadowOpacity + val stops = 8 + val positions = FloatArray(stops) { it / (stops - 1f) } + // Outermost stop first: alpha at distance d outside the edge. + val edgeColors = IntArray(stops) { shadowColor(extent * (1f - positions[it]), sigma) } + shadowEdge = LinearGradient(-extent, 0f, 0f, 0f, edgeColors, positions, Shader.TileMode.CLAMP) + val outer = r + extent + val cornerPositions = FloatArray(stops) { (r + extent * it / (stops - 1f)) / outer } + val cornerColors = IntArray(stops) { shadowColor(extent * it / (stops - 1f), sigma) } + shadowTopCorner = RadialGradient(r, r, outer, cornerColors, cornerPositions, Shader.TileMode.CLAMP) + shadowBottomCorner = RadialGradient(r, height - r, outer, cornerColors, cornerPositions, Shader.TileMode.CLAMP) + } + val save = canvas.save() + canvas.translate(foreground.left + foreground.translationX, foreground.top.toFloat()) + shadowPaint.shader = shadowEdge + canvas.drawRect(-extent, r, 0f, height - r, shadowPaint) + if (r > 0f) { + shadowPaint.shader = shadowTopCorner + canvas.drawRect(-extent, -extent, r, r, shadowPaint) + shadowPaint.shader = shadowBottomCorner + canvas.drawRect(-extent, height - r, r, height + extent, shadowPaint) + } + canvas.restoreToCount(save) + } + + private fun shadowColor(distance: Float, sigma: Float): Int { + val z = distance / sigma + // 1 - Φ(z), the share of a Gaussian blur that spills past an edge. + val t = 1f / (1f + .2316419f * z) + val tail = .3989423f * exp(-z * z / 2f) * + t * (.31938153f + t * (-.356563782f + t * (1.781477937f + t * (-1.821255978f + t * 1.330274429f)))) + return Color.argb((pageShadowOpacity * tail * 255f).roundToInt().coerceIn(0, 255), 0, 0, 0) + } + + private fun animationsEnabled(): Boolean = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) ValueAnimator.areAnimatorsEnabled() + else Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) != 0f + + // cubic-bezier(0.55, 0.6, 0.2, 1), fitted to the reference tap open and close. + private fun pageCurve(x: Float): Float { + fun bezier(t: Float, p1: Float, p2: Float): Float { + val u = 1f - t + return 3f * u * u * t * p1 + 3f * u * t * t * p2 + t * t * t + } + var low = 0f + var high = 1f + repeat(24) { + val mid = (low + high) / 2f + if (bezier(mid, .55f, .2f) < x) low = mid else high = mid + } + return bezier((low + high) / 2f, .6f, 1f) + } + + // Taps and programmatic changes ease over a fixed time; a released drag + // keeps its finger velocity through a slightly underdamped spring. + private fun settle(open: Boolean, velocity: Float, user: Boolean, tween: Boolean = true) { val target = drawerEnabled && open + // An animation already heading there keeps running; the newer request + // still decides whether its completion is a user event. + if (animator != null && animationTarget == target) { + animationUser = user + return + } + // Reversing mid-flight continues from the page's on-screen position and + // speed, so the motion bends instead of stopping dead. + val retarget = animator != null + val from = if (retarget) appliedValue else progress + val carried = if (retarget) trackedVelocity else velocity + stopAnimation() if (width == 0 || !isAttachedToWindow) { stableOpen = target setProgress(if (target) 1f else 0f) return } - if (progress == if (target) 1f else 0f) { + if (!retarget && progress == if (target) 1f else 0f) { finish(target, user) return } - val end = if (target) 1f else 0f - val a = progress - end - val b = velocity.coerceIn(-8f, 8f) + 22f * a + // With system animations removed, the drawer lands without moving. + if (!animationsEnabled()) { + finish(target, user) + return + } + animationFrom = from + animationVelocity = carried.coerceIn(-12f, 12f) animationTarget = target animationUser = user - val next = ValueAnimator.ofFloat(0f, .5f) - next.duration = 500 - next.interpolator = LinearInterpolator() - next.addUpdateListener { - val time = it.animatedValue as Float - setProgress(end + (a + b * time) * exp(-22f * time)) - } - next.addListener(object : AnimatorListenerAdapter() { - override fun onAnimationEnd(animation: Animator) { - if (animator !== animation) return - animator = null - finish(target, user) - } - }) + // Closing runs about 20% shorter than opening. + val fullDuration = if (target) .36f else .29f + animationDuration = if (tween && !retarget) max(.12f, fullDuration * abs((if (target) 1f else 0f) - from)) else 0f + trackedValue = from + trackedTime = 0f + trackedVelocity = animationVelocity + val next = TimeAnimator() + next.setTimeListener { animation, totalTime, _ -> tick(animation, totalTime / 1000f) } animator = next next.start() } + private fun tick(animation: TimeAnimator, elapsed: Float) { + if (animator !== animation) return + val end = if (animationTarget) 1f else 0f + val spring = animationDuration == 0f + val value: Float + var tweenDone = false + if (!spring) { + val x = min(1f, elapsed / animationDuration) + value = animationFrom + (end - animationFrom) * pageCurve(x) + tweenDone = x >= 1f + } else { + val w = SPRING_FREQUENCY + val z = SPRING_DAMPING + val a = animationFrom - end + val wd = w * sqrt(1f - z * z) + val decay = exp(-z * w * elapsed) + value = end + decay * (a * cos(wd * elapsed) + (animationVelocity + z * w * a) / wd * sin(wd * elapsed)) + } + if (elapsed > trackedTime) trackedVelocity = (value - trackedValue) / (elapsed - trackedTime) + trackedValue = value + trackedTime = elapsed + setProgress(value, spring) + // A spring ends once it is visually at rest, not after a fixed time. + val done = if (spring) (abs(value - end) < .0005f && abs(trackedVelocity) < .02f) || elapsed >= .6f + else tweenDone + if (done) { + val target = animationTarget + val user = animationUser + stopAnimation() + finish(target, user) + } + } + private fun finish(target: Boolean, user: Boolean) { val changed = stableOpen != target stableOpen = target @@ -435,8 +658,7 @@ class BottomTabsDrawerView(context: Context) : FrameLayout(context) { } private fun stopAnimation() { - animator?.removeAllListeners() - animator?.removeAllUpdateListeners() + animator?.setTimeListener(null) animator?.cancel() animator = null } diff --git a/native-views/react-native-bottom-tabs/docs/SPEC.md b/native-views/react-native-bottom-tabs/docs/SPEC.md index 3406cd07c..ef7a89c37 100644 --- a/native-views/react-native-bottom-tabs/docs/SPEC.md +++ b/native-views/react-native-bottom-tabs/docs/SPEC.md @@ -74,6 +74,11 @@ The static Home example also passed a focused TypeScript check. Detailed iOS runtime evidence is recorded separately; physical-device and exact reference-video acceptance remain pending. +Reference-recording motion revision: implemented on iOS and Android. iOS is +runtime verified in the consumer app on an iPhone 17 simulator; Android is +source-complete with updated native tests that still need an emulator run (see +Conformance below). + `renderDrawerContent?: () => React.ReactNode` supplies an optional menu slot. `drawerOpen?: boolean` defaults to false and requests its stable open state. `onDrawerOpenChange?: (open: boolean) => void` reports a completed user transition; @@ -86,8 +91,24 @@ screen). Existing `hapticFeedbackEnabled` enables one light native haptic after a completed user transition changes the stable state. Programmatic updates and cancelled gestures do not vibrate. +`onDrawerProgress?: (event) => void` receives `{ progress }`, the displayed +progress clamped to [0, 1], while the drawer moves. Native emits it only while +a handler is set (the wrapper derives the internal `progressEventsEnabled` prop +from the handler's presence), at most once per frame, when progress changed by +at least .002, and always on reaching 0 or 1. Enabling it emits the current +value once, so a new subscriber starts in sync. The handler is passed to the +host unchanged, so `drawerHostComponent?` (default: the native host) can be an +animated wrapper such as `Animated.createAnimatedComponent(BottomTabsDrawerNative)` +whose worklet handler consumes the event on the UI thread. The package does +not depend on Reanimated; `BottomTabsDrawerNative` is exported for this use. +`drawerColorScheme?: "light" | "dark"` selects the page palette below; when +omitted the internal `colorScheme` prop is `"system"` and follows the iOS trait +collection or the Android configuration's night mode. Pass the app theme when +it can differ from those (an app-level iOS window style override is followed +without it). + The drawer is physically left on both iOS and Android, including RTL. Its width -is 78 percent of the host. The foreground is the full tab container, including +is 80 percent of the host. The foreground is the full tab container, including the native tab bar and an optional custom JS bar. It keeps its full width and height while moving right, without scaling, scene reparenting or remounting. The native host and two slots remain mounted when the drawer is disabled or its @@ -96,12 +117,19 @@ an event, and passes foreground input through. Web omits the drawer host/menu and passes the existing tab content through; it implements no drawer gestures. The existing tab view's other Web support is unchanged. -For normalized progress `p` in [0, 1], foreground translation is `.78 * width * p`, -its left circular corner radius is `64 * p` points/dp and its neutral gray -dim surface (RGB 28/28/28) has opacity `.7 * p`. -The menu translates from `-.12 * drawerWidth` to zero; a black menu shade fades -from .12 to zero. These are initial reference-video tuning values, not a claim -of pixel-perfect parity. Closed menus are hidden from touch/accessibility; +For normalized progress `p` in [0, 1], foreground translation is `.8 * width * p` +and its left circular corner radius is `62 * min(1, p / .1)` points/dp, so +screens with other display corners never show a radius jump. The dim surface +washes the page linearly: white at `.5 * p` in the light palette, RGB 36/36/36 +at `.58 * p` in the dark palette. In the light palette the page also casts a +black shadow under its left edge and corners, opacity .16, Gaussian sigma 18 +points/dp, no offset; in the dark palette it instead draws a one-physical-pixel +white edge at 17 percent opacity. The menu scales from .97 to 1 about its +left-center edge (1 throughout when motion is reduced, see below) and its +opacity is `min(1, p / .6)`. The host itself is transparent, so whatever lies +behind it shows through the fading menu and its scaled-down margins. +These values were measured frame by frame from the reference recording. +Closed menus are hidden from touch/accessibility; while visible, the foreground is blocked by a native dim surface. Tapping that surface closes the drawer. iOS accessibility escape and Android Back close an open drawer; the dim surface exposes an accessible close action. @@ -153,27 +181,45 @@ Vertical gestures fail before taking ownership. Active touches interrupted by a second finger, system cancellation, disabling, detach or a newer prop update cannot later emit an event. Cancellation returns to the previous stable state, or resumes an external target whose programmatic animation the gesture interrupted. -No gesture progress crosses the JS bridge. - -Both platforms settle on their UI thread with the same critically damped curve: -`p(t) = target + (a + b*t) * exp(-22*t)`, where `a = p0-target`, -`b = v0 + 22*a`, and normalized velocity `v0` is clamped to [-8, 8] per second. -Presentation is clamped to [0, 1], and the transition ends at or before 500 ms. -Release targets open when `p + v0*.12 >= .5`. A newer animation or touch starts -from the current displayed progress and cancels the previous completion. +Gesture progress crosses the JS bridge only through the opt-in `onDrawerProgress`. + +Both platforms settle on their UI thread with the same curves. A tap, dim +close, Back/escape or prop change starting from rest eases with +cubic-bezier(.55, .6, .2, 1) over `max(.12, D * |target - p0|)` seconds, where D +is .36 to open and .29 to close. A released drag settles on a spring with +natural frequency 25.5 rad/s and damping ratio .84, starting from its normalized +finger velocity `v0` clamped to [-12, 12] per second; release targets open when +`p + v0*.12 >= .5`. Only this spring may carry the page past open, by at most +3 percent of the drawer width; reported progress and touch/accessibility state +stay clamped to [0, 1]. The spring ends once within .0005 of its target and +slower than .02 per second, or at 600 ms. A request for a different target +while animating continues from the displayed progress with its current +velocity on the spring; a request for the same target keeps the running +animation and only replaces whether its completion is a user transition. A +touch starts from the current displayed progress and cancels the previous +completion. When the system asks for less motion (iOS Reduce Motion; Android +with animator duration scale 0), the menu does not scale. On iOS a tap, +close or prop change from rest then cross-fades from a snapshot to the final +state over 200 ms instead of moving, and a released drag settles critically +damped (damping ratio 1). Android has no separate reduced-motion setting and +lands such transitions immediately. Resize snaps a pending settlement to its target, emitting its user event once if appropriate; an active drag follows the same cancellation rule. Detach cancels animations and callbacks; reattachment reapplies the latest external target. The host retains at most one display-link/animator, one touch -sequence, two React child slots, and native dim surfaces. It owns no snapshots, -workers, persistence, JS animation objects, RNGH or Reanimated dependency. +sequence, two React child slots, and native dim surfaces; on iOS one transient +snapshot during a reduced-motion cross-fade, removed when it ends; on Android +one hardware layer on the menu while its opacity is strictly between 0 and 1, +and three gradient shaders for the page shadow, rebuilt only when the corner +radius, height or palette changes. It owns no workers, persistence, JS +animation objects, RNGH or Reanimated dependency. Implementation boundaries: `src/BottomTabs.tsx` owns slots and settled callbacks; `src/BottomTabsDrawerNativeComponent.ts` defines the Fabric boundary; `ios/RCTBottomTabsDrawerContainerView.swift` and `android/src/main/java/com/onekey/bottomtabs/BottomTabsDrawerView.kt` own native input, layout, animation and cleanup. The iOS Fabric component and Android manager only forward children, -props and the settled event. Required acceptance includes both bar styles, +props, the settled event and the opt-in progress event. Required acceptance includes both bar styles, custom bars, content/vertical gestures, dim close, rapid reversal, cancellation, disable/remove-content, resize, detach, accessibility, RTL and bottom-bar gesture ownership, including a real pager, nested horizontal list and vertical @@ -181,6 +227,17 @@ scrolling in the complete Fabric example. Source checks and emulator checks do n device smoothness or exact reference-video fidelity. The Android native suite also exercises generated drawer prop forwarding in RTL, physical-left placement, and closing pans while opening swipes are disabled. +For the reference-recording revision it asserts the 80 percent travel, the +light and dark wash, the menu's final scale/opacity/layer, and that progress +events are opt-in, start in sync and end on the stable state; the wrapper tests +assert that progress stays off without a handler and that the handler, a +replacement host and the color scheme reach native unchanged. +Recorded evidence so far: on the iPhone 17 simulator (iOS 26) in the consumer +app, tap open/close timing, fling overshoot (about 2 points), smooth reversal, +the corner ramp, the reduced-motion cross-fade, the light/dark palettes and a +UI-thread Reanimated progress handler were compared frame by frame with the +reference recording. The Android suite has not yet been run for this revision; +physical-device smoothness on either platform remains unverified. The standalone `example/react-native/pages/BottomTabsHomeDrawerExample.tsx` reproduces Home’s wallet toolbar, balance/actions/banner shared header and diff --git a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerComponentView.mm b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerComponentView.mm index 76486412d..31817eb45 100644 --- a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerComponentView.mm +++ b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerComponentView.mm @@ -13,7 +13,10 @@ @protocol RNBottomTabsDrawerContainer @property(nonatomic) BOOL swipeEnabled; @property(nonatomic) BOOL hapticFeedbackEnabled; @property(nonatomic) double bottomBarHeight; +@property(nonatomic, copy) NSString *colorScheme; +@property(nonatomic) BOOL progressEventsEnabled; @property(nonatomic, copy) void (^onDrawerOpenChange)(BOOL open); +@property(nonatomic, copy) void (^onDrawerProgress)(double progress); - (void)insertChild:(UIView *)child atIndex:(NSInteger)index; - (void)removeChildAtIndex:(NSInteger)index; @end @@ -45,6 +48,12 @@ - (instancetype)initWithFrame:(CGRect)frame auto emitter = std::static_pointer_cast(strongSelf->_eventEmitter); if (emitter) emitter->onDrawerOpenChange({.open = (bool)open}); }; + _drawer.onDrawerProgress = ^(double progress) { + auto strongSelf = weakSelf; + if (!strongSelf) return; + auto emitter = std::static_pointer_cast(strongSelf->_eventEmitter); + if (emitter) emitter->onDrawerProgress({.progress = progress}); + }; } return self; } @@ -69,6 +78,12 @@ - (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const & if (next.hapticFeedbackEnabled != previous.hapticFeedbackEnabled) _drawer.hapticFeedbackEnabled = next.hapticFeedbackEnabled; if (next.bottomBarHeight != previous.bottomBarHeight) _drawer.bottomBarHeight = next.bottomBarHeight; + if (next.colorScheme != previous.colorScheme) { + _drawer.colorScheme = next.colorScheme == RNBottomTabsDrawerColorScheme::Light ? @"light" + : next.colorScheme == RNBottomTabsDrawerColorScheme::Dark ? @"dark" : @"system"; + } + if (next.progressEventsEnabled != previous.progressEventsEnabled) + _drawer.progressEventsEnabled = next.progressEventsEnabled; [super updateProps:props oldProps:oldProps]; } @end diff --git a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift index 57584d8ae..0efe6f321 100644 --- a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift +++ b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift @@ -23,11 +23,29 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat @objc var swipeEnabled = false @objc var hapticFeedbackEnabled = false @objc var bottomBarHeight: Double = 0 + /// "light" or "dark" forces that palette; anything else follows the trait collection. + @objc var colorScheme = "system" { + didSet { + guard colorScheme != oldValue else { return } + applyAppearance() + setProgress(appliedValue, overshoot: appliedOvershoot) + } + } + @objc var progressEventsEnabled = false { + didSet { + guard progressEventsEnabled != oldValue else { return } + // A new subscriber starts from the current position. + reportedProgress = -1 + if progressEventsEnabled { reportProgress() } + } + } @objc var onDrawerOpenChange: ((Bool) -> Void)? + @objc var onDrawerProgress: ((Double) -> Void)? private let menu = UIView() - private let menuShade = UIView() private let foreground = UIView() + // Clips the page to its rounded corners; the unclipped foreground casts the shadow. + private let pageClip = UIView() private let foregroundContent = UIView() private let dim = UIButton(type: .custom) private var slots: [UIView] = [] @@ -45,30 +63,80 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat private var animationTarget = false private var animationUser = false private var previousSize = CGSize.zero + private var animationDuration: CFTimeInterval = 0 + private var scrimMaxAlpha: CGFloat = 0.58 + private var pageShadowOpacity: Float = 0 + private var pageHairline = false + private var reportedProgress: CGFloat = -1 + // The last requested position, kept so a layout pass mid-settle does not + // clip the spring's overshoot back to fully open. + private var appliedValue: CGFloat = 0 + private var appliedOvershoot = false + // Running speed of the current animation, for handing off to a retarget. + private var trackedValue: CGFloat = 0 + private var trackedTime: CFTimeInterval = 0 + private var trackedVelocity: CGFloat = 0 + + // Measured frame by frame from the reference recording: the page travels + // 80% of the width, keeps a fixed display-like corner, washes toward the + // background linearly, and casts a soft shadow onto the menu below it (a + // hairline in dark mode). + private static let menuWidthFraction: CGFloat = 0.8 + private static let pageCornerRadius: CGFloat = 62 + private static let menuMinScale: CGFloat = 0.97 + // Released drags settle on a slightly underdamped spring: about 2pt of + // overshoot after a fling, none after a slow release. + private static let springFrequency: CGFloat = 25.5 + private static let springDamping: CGFloat = 0.84 + private var menuWidth: CGFloat { bounds.width * Self.menuWidthFraction } override init(frame: CGRect) { super.init(frame: frame) clipsToBounds = true addSubview(menu) - menuShade.backgroundColor = .black - menuShade.isUserInteractionEnabled = false - menu.addSubview(menuShade) addSubview(foreground) - foreground.addSubview(foregroundContent) - dim.backgroundColor = UIColor(white: 28.0 / 255.0, alpha: 1) + foreground.addSubview(pageClip) + pageClip.addSubview(foregroundContent) dim.accessibilityLabel = NSLocalizedString("Close menu", comment: "Close the tab drawer") dim.addTarget(self, action: #selector(closeFromUser), for: .touchUpInside) - foreground.addSubview(dim) - foreground.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner] - foreground.layer.cornerCurve = .circular - foreground.clipsToBounds = true + pageClip.addSubview(dim) + pageClip.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner] + pageClip.layer.cornerCurve = .circular + pageClip.clipsToBounds = true + foreground.layer.shadowColor = UIColor.black.cgColor + foreground.layer.shadowOffset = .zero + foreground.layer.shadowRadius = 18 + foreground.layer.shadowOpacity = 0 pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) pan.maximumNumberOfTouches = 1 pan.delegate = self addGestureRecognizer(pan) + applyAppearance() setProgress(0) } + private func applyAppearance() { + let dark: Bool + switch colorScheme { + case "dark": dark = true + case "light": dark = false + default: dark = traitCollection.userInterfaceStyle == .dark + } + // The page washes toward white in light mode and toward gray in dark mode. + dim.backgroundColor = dark ? UIColor(white: 36.0 / 255.0, alpha: 1) : .white + scrimMaxAlpha = dark ? 0.58 : 0.5 + pageShadowOpacity = dark ? 0 : 0.16 + pageHairline = dark + pageClip.layer.borderColor = UIColor(white: 1, alpha: 0.17).cgColor + } + + override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { + super.traitCollectionDidChange(previousTraitCollection) + guard traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else { return } + applyAppearance() + setProgress(appliedValue, overshoot: appliedOvershoot) + } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func insertChild(_ child: UIView, atIndex index: Int) { @@ -87,7 +155,6 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat for (index, child) in slots.enumerated() { (index == 0 ? menu : foregroundContent).insertSubview(child, at: 0) } - menu.bringSubviewToFront(menuShade) setNeedsLayout() } @@ -104,14 +171,19 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat } menu.transform = .identity foreground.transform = .identity - menu.frame = CGRect(x: 0, y: 0, width: bounds.width * 0.78, height: bounds.height) + menu.frame = CGRect(x: 0, y: 0, width: menuWidth, height: bounds.height) foreground.frame = bounds - foregroundContent.frame = foreground.bounds - dim.frame = foreground.bounds - menuShade.frame = menu.bounds + pageClip.frame = foreground.bounds + foregroundContent.frame = pageClip.bounds + dim.frame = pageClip.bounds + foreground.layer.shadowPath = UIBezierPath( + roundedRect: foreground.bounds, + byRoundingCorners: [.topLeft, .bottomLeft], + cornerRadii: CGSize(width: Self.pageCornerRadius, height: Self.pageCornerRadius) + ).cgPath if slots.count > 0 { slots[0].frame = menu.bounds } if slots.count > 1 { slots[1].frame = foreground.bounds } - setProgress(progress) + setProgress(appliedValue, overshoot: appliedOvershoot) } override func didMoveToWindow() { @@ -137,7 +209,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat guard start.y < bounds.height - CGFloat(max(0, bottomBarHeight)) else { return false } guard !isInsideNativeTabBar(touch.view) else { return false } touchTarget = touch.view - if progress > 0 { return start.x >= bounds.width * 0.78 * progress } + if progress > 0 { return start.x >= menuWidth * progress } return swipeEnabled && !touchPathContainsExclusiveControl() } @@ -150,7 +222,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat let start = CGPoint(x: location.x - translation.x, y: location.y - translation.y) guard start.y < bounds.height - CGFloat(max(0, bottomBarHeight)) else { return false } if progress > 0 { - return start.x >= bounds.width * 0.78 * progress + return start.x >= menuWidth * progress } return swipeEnabled && velocity.x > 0 && !touchPathCanScrollRight() } @@ -253,10 +325,10 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat settle(to: gestureReturnOpen, velocity: 0, user: false) return } - setProgress(gestureStartProgress + recognizer.translation(in: self).x / max(1, bounds.width * 0.78)) + setProgress(gestureStartProgress + recognizer.translation(in: self).x / max(1, menuWidth)) case .ended: - let velocity = min(8, max(-8, recognizer.velocity(in: self).x / max(1, bounds.width * 0.78))) - settle(to: progress + velocity * 0.12 >= 0.5, velocity: velocity, user: true) + let velocity = min(12, max(-12, recognizer.velocity(in: self).x / max(1, menuWidth))) + settle(to: progress + velocity * 0.12 >= 0.5, velocity: velocity, user: true, tween: false) case .cancelled, .failed: if !suppressCancellation { settle(to: gestureReturnOpen, velocity: 0, user: false) } default: break @@ -277,49 +349,153 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat settle(to: false, velocity: 0, user: true) } - private func setProgress(_ value: CGFloat) { - progress = min(1, max(0, enabled ? value : 0)) - foreground.transform = CGAffineTransform(translationX: bounds.width * 0.78 * progress, y: 0) - foreground.layer.cornerRadius = 64 * progress - dim.alpha = 0.7 * progress - dim.isHidden = progress == 0 - foregroundContent.isUserInteractionEnabled = progress == 0 - foregroundContent.accessibilityElementsHidden = progress > 0 - menu.transform = CGAffineTransform(translationX: -0.12 * bounds.width * 0.78 * (1 - progress), y: 0) - menuShade.alpha = 0.12 * (1 - progress) - menu.isHidden = progress == 0 - menu.accessibilityElementsHidden = progress == 0 + private func setProgress(_ value: CGFloat, overshoot: Bool = false) { + appliedValue = value + appliedOvershoot = overshoot + let raw = enabled ? value : 0 + progress = min(1, max(0, raw)) + let visible = progress > 0 + // Only the settle spring may carry the page a few points past open. + let travel = overshoot ? min(1.03, max(0, raw)) : progress + foreground.transform = CGAffineTransform(translationX: menuWidth * travel, y: 0) + // Rounds in over the first 10% so screens with other corner radii never pop. + pageClip.layer.cornerRadius = visible ? Self.pageCornerRadius * min(1, progress / 0.1) : 0 + pageClip.layer.borderWidth = visible && pageHairline ? 1 / max(1, traitCollection.displayScale) : 0 + foreground.layer.shadowOpacity = visible ? pageShadowOpacity : 0 + dim.alpha = scrimMaxAlpha * progress + dim.isHidden = !visible + foregroundContent.isUserInteractionEnabled = !visible + foregroundContent.accessibilityElementsHidden = visible + // The menu grows from its left-center edge and fades in over whatever is + // behind the host, fully visible by 60% open. + let minScale = UIAccessibility.isReduceMotionEnabled ? 1 : Self.menuMinScale + let scale = minScale + (1 - minScale) * progress + menu.transform = CGAffineTransform(translationX: -(1 - scale) * menu.bounds.width / 2, y: 0) + .scaledBy(x: scale, y: scale) + menu.alpha = min(1, progress / 0.6) + menu.isHidden = !visible + menu.accessibilityElementsHidden = !visible + reportProgress() + } + + private func reportProgress() { + guard progressEventsEnabled else { return } + if progress != reportedProgress && (abs(progress - reportedProgress) >= 0.002 || progress == 0 || progress == 1) { + reportedProgress = progress + onDrawerProgress?(Double(progress)) + } } - private func settle(to target: Bool, velocity: CGFloat, user: Bool) { + // cubic-bezier(0.55, 0.6, 0.2, 1), fitted to the reference tap open and close. + private static func pageCurve(_ x: CGFloat) -> CGFloat { + func bezier(_ t: CGFloat, _ p1: CGFloat, _ p2: CGFloat) -> CGFloat { + let u = 1 - t + return 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t + } + var low: CGFloat = 0 + var high: CGFloat = 1 + for _ in 0..<24 { + let mid = (low + high) / 2 + if bezier(mid, 0.55, 0.2) < x { low = mid } else { high = mid } + } + return bezier((low + high) / 2, 0.6, 1) + } + + // Taps and programmatic changes ease over a fixed time; a released drag + // keeps its finger velocity through a slightly underdamped spring. + private func settle(to requested: Bool, velocity: CGFloat, user: Bool, tween: Bool = true) { + let target = enabled && requested + // An animation already heading there keeps running; the newer request + // still decides whether its completion is a user event. + if displayLink != nil && animationTarget == target { + animationUser = user + return + } + // Reversing mid-flight continues from the page's on-screen position and + // speed, so the motion bends instead of stopping dead. + let retarget = displayLink != nil + let from = retarget ? appliedValue : progress + let carried = retarget ? trackedVelocity : velocity stopAnimation() - let target = enabled && target guard bounds.width > 0, window != nil else { stableOpen = target setProgress(target ? 1 : 0) return } - if progress == (target ? 1 : 0) { + if !retarget && progress == (target ? 1 : 0) { finish(target: target, user: user) return } - animationFrom = progress - animationVelocity = min(8, max(-8, velocity)) + if tween && !retarget && UIAccessibility.isReduceMotionEnabled && crossFade(to: target, user: user) { + return + } + animationFrom = from + animationVelocity = min(12, max(-12, carried)) animationTarget = target animationUser = user + // Closing runs about 20% shorter than opening. + let fullDuration: CGFloat = target ? 0.36 : 0.29 + animationDuration = tween && !retarget ? max(0.12, fullDuration * abs((target ? 1 : 0) - from)) : 0 animationStart = CACurrentMediaTime() + trackedValue = from + trackedTime = animationStart + trackedVelocity = animationVelocity let link = CADisplayLink(target: self, selector: #selector(tick)) link.add(to: .main, forMode: .common) displayLink = link } + // Reduce Motion: taps and programmatic changes cross-fade into place + // instead of sliding the whole page. + private func crossFade(to target: Bool, user: Bool) -> Bool { + guard let snapshot = snapshotView(afterScreenUpdates: false) else { return false } + snapshot.frame = bounds + snapshot.isUserInteractionEnabled = false + addSubview(snapshot) + finish(target: target, user: user) + UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseOut], animations: { + snapshot.alpha = 0 + }, completion: { _ in + snapshot.removeFromSuperview() + }) + return true + } + @objc private func tick() { - let elapsed = CGFloat(CACurrentMediaTime() - animationStart) + let now = CACurrentMediaTime() + let elapsed = CGFloat(now - animationStart) let target: CGFloat = animationTarget ? 1 : 0 - let a = animationFrom - target - let b = animationVelocity + 22 * a - setProgress(target + (a + b * elapsed) * exp(-22 * elapsed)) - if elapsed >= 0.5 { + let value: CGFloat + let isSpring = animationDuration == 0 + var tweenDone = false + if !isSpring { + let x = min(1, elapsed / CGFloat(animationDuration)) + value = animationFrom + (target - animationFrom) * Self.pageCurve(x) + tweenDone = x >= 1 + } else { + let w = Self.springFrequency + let a = animationFrom - target + if UIAccessibility.isReduceMotionEnabled { + // Critically damped: same speed, no bounce. + value = target + (a + (animationVelocity + w * a) * elapsed) * exp(-w * elapsed) + } else { + let z = Self.springDamping + let wd = w * sqrt(1 - z * z) + let decay = exp(-z * w * elapsed) + value = target + decay * (a * cos(wd * elapsed) + (animationVelocity + z * w * a) / wd * sin(wd * elapsed)) + } + } + if now > trackedTime { + trackedVelocity = (value - trackedValue) / CGFloat(now - trackedTime) + } + trackedValue = value + trackedTime = now + setProgress(value, overshoot: isSpring) + // A spring ends once it is visually at rest, not after a fixed time. + let done = isSpring + ? (abs(value - target) < 0.0005 && abs(trackedVelocity) < 0.02) || elapsed >= 0.6 + : tweenDone + if done { let target = animationTarget let user = animationUser stopAnimation() diff --git a/native-views/react-native-bottom-tabs/native-tests/android/BottomTabsDrawerTest.kt b/native-views/react-native-bottom-tabs/native-tests/android/BottomTabsDrawerTest.kt index 868f2f60f..8f01513a8 100644 --- a/native-views/react-native-bottom-tabs/native-tests/android/BottomTabsDrawerTest.kt +++ b/native-views/react-native-bottom-tabs/native-tests/android/BottomTabsDrawerTest.kt @@ -4,6 +4,7 @@ import coil3.asDrawable import android.content.Intent import android.content.Context import android.graphics.Color +import android.graphics.drawable.ColorDrawable import android.os.SystemClock import android.test.InstrumentationTestCase import android.view.MotionEvent @@ -71,6 +72,7 @@ class BottomTabsDrawerTest : InstrumentationTestCase() { drawer = BottomTabsDrawerView(activity) drawer.setDrawerEnabled(true) drawer.swipeEnabled = true + drawer.colorScheme = "light" drawer.addReactChild(View(activity).apply { setBackgroundColor(Color.DKGRAY) }, 0) main = FrameLayout(activity).apply { setBackgroundColor(Color.WHITE) @@ -98,13 +100,13 @@ class BottomTabsDrawerTest : InstrumentationTestCase() { assertEquals(1, root.ended) assertEquals(drawer.width, main.width) assertEquals(drawer.height, main.height) - assertEquals(drawer.width * .78f, drawer.getChildAt(1).translationX, 1f) - assertEquals(drawer.width * .78f, drawer.getReactChild(0).width.toFloat(), 1f) + assertEquals(drawer.width * .8f, drawer.getChildAt(1).translationX, 1f) + assertEquals(drawer.width * .8f, drawer.getReactChild(0).width.toFloat(), 1f) val dim = (drawer.getChildAt(1) as FrameLayout).getChildAt(1) assertEquals(drawer.width, dim.width) assertEquals(drawer.height, dim.height) assertEquals(View.VISIBLE, dim.visibility) - assertEquals(.7f, dim.alpha) + assertEquals(.5f, dim.alpha) // A prop echo has no second event or animation. drawer.setDrawerOpen(true) assertEquals(listOf(true), events) @@ -118,6 +120,52 @@ class BottomTabsDrawerTest : InstrumentationTestCase() { } } + fun testColorSchemeSelectsThePageWashAndTheMenuFinishesOpen() { + onMain { + drawer.colorScheme = "dark" + drawer.setDrawerOpen(true) + } + settle() + onMain { + val dim = (drawer.getChildAt(1) as FrameLayout).getChildAt(1) + assertEquals(.58f, dim.alpha, .001f) + assertEquals(Color.rgb(36, 36, 36), (dim.background as ColorDrawable).color) + drawer.colorScheme = "light" + assertEquals(.5f, dim.alpha, .001f) + assertEquals(Color.WHITE, (dim.background as ColorDrawable).color) + // The menu has scaled up from its left edge and faded fully in. + val menu = drawer.getChildAt(0) + assertEquals(1f, menu.alpha) + assertEquals(1f, menu.scaleX) + assertEquals(0f, menu.pivotX) + assertEquals(View.LAYER_TYPE_NONE, menu.layerType) + assertTrue(events.isEmpty()) + } + } + + fun testProgressEventsAreOptInAndEndOnTheStableState() { + val progress = mutableListOf() + onMain { + drawer.onDrawerProgress = { progress.add(it) } + drawer.setDrawerOpen(true) + } + settle() + onMain { + assertTrue(progress.isEmpty()) + drawer.progressEventsEnabled = true + // A new subscriber receives the current position at once. + assertEquals(listOf(1f), progress) + drawer.setDrawerOpen(false) + } + settle() + onMain { + assertTrue(progress.size > 2) + assertTrue(progress.all { it in 0f..1f }) + assertEquals(0f, progress.last()) + assertTrue(events.isEmpty()) + } + } + fun testVerticalBottomAndDisabledOpeningDoNotStealGestures() { onMain { drawer.bottomBarHeight = 100f @@ -140,7 +188,7 @@ class BottomTabsDrawerTest : InstrumentationTestCase() { settle() onMain { assertTrue(events.isEmpty()) - assertEquals(drawer.width * .78f, drawer.getChildAt(1).translationX, 1f) + assertEquals(drawer.width * .8f, drawer.getChildAt(1).translationX, 1f) assertSame(main, drawer.getReactChild(1)) drag(drawer.width * .95f, 150f, drawer.width * .25f, 150f) } @@ -177,7 +225,7 @@ class BottomTabsDrawerTest : InstrumentationTestCase() { settle() onMain { assertEquals(listOf(false), events) - assertEquals(drawer.width * .78f, drawer.getChildAt(1).translationX, 1f) + assertEquals(drawer.width * .8f, drawer.getChildAt(1).translationX, 1f) } } @@ -199,7 +247,7 @@ class BottomTabsDrawerTest : InstrumentationTestCase() { } settle() onMain { - assertEquals(drawer.width * .78f, drawer.getChildAt(1).translationX, 1f) + assertEquals(drawer.width * .8f, drawer.getChildAt(1).translationX, 1f) drawer.setDrawerEnabled(false) assertEquals(0f, drawer.getChildAt(1).translationX) assertSame(main, drawer.getReactChild(1)) @@ -212,7 +260,7 @@ class BottomTabsDrawerTest : InstrumentationTestCase() { drawer.layout(0, 0, drawer.width - 40, drawer.height - 20) assertEquals(listOf(true), events) assertSame(main, drawer.getReactChild(1)) - assertEquals(drawer.width * .78f, drawer.getChildAt(1).translationX, 1f) + assertEquals(drawer.width * .8f, drawer.getChildAt(1).translationX, 1f) } settle() onMain { assertEquals(listOf(true), events) } @@ -246,7 +294,7 @@ class BottomTabsDrawerTest : InstrumentationTestCase() { onMain { val after = IntArray(2) tabs.getLocationOnScreen(after) - assertEquals(drawer.width * .78f, (after[0] - before[0]).toFloat(), 1f) + assertEquals(drawer.width * .8f, (after[0] - before[0]).toFloat(), 1f) assertEquals(drawer.width, tabs.width) assertEquals(drawer.height, tabs.height) assertTrue(tabs.layoutHolder.height > 0) diff --git a/native-views/react-native-bottom-tabs/src/BottomTabs.tsx b/native-views/react-native-bottom-tabs/src/BottomTabs.tsx index f7ff8618c..527311012 100644 --- a/native-views/react-native-bottom-tabs/src/BottomTabs.tsx +++ b/native-views/react-native-bottom-tabs/src/BottomTabs.tsx @@ -128,6 +128,24 @@ interface Props { drawerSwipeEnabled?: boolean; /** Reports a completed user target so the external open state can follow it. */ onDrawerOpenChange?: (open: boolean) => void; + /** + * The drawer's visual progress (0 closed, 1 open) on every frame it moves. + * Passed to the drawer host as is, so a Reanimated handler can run it on the + * UI thread when `drawerHostComponent` is an animated component. Native sends + * no progress events without this handler. + */ + onDrawerProgress?: ( + event: NativeSyntheticEvent> + ) => void; + /** Host for the native drawer, e.g. `Animated.createAnimatedComponent(BottomTabsDrawerNative)`. */ + drawerHostComponent?: React.ComponentType< + React.ComponentProps + >; + /** + * Palette for the page's overlay, shadow and edge while the drawer is open. + * Defaults to the platform appearance; pass the app theme when it can differ. + */ + drawerColorScheme?: "light" | "dark"; /** * A tab bar style that adapts to each platform. * @@ -378,6 +396,9 @@ const BottomTabs = ({ drawerOpen = false, drawerSwipeEnabled = false, onDrawerOpenChange, + onDrawerProgress, + drawerHostComponent: DrawerHost = NativeBottomTabsDrawer, + drawerColorScheme, rippleColor, tabBarActiveTintColor: activeTintColor, tabBarInactiveTintColor: inactiveTintColor, @@ -607,16 +628,19 @@ const BottomTabs = ({ return ( - onDrawerOpenChange?.(event.nativeEvent.open) } + onDrawerProgress={onDrawerProgress} > {Platform.OS !== "web" ? renderDrawerContent?.() : null} @@ -722,7 +746,7 @@ const BottomTabs = ({ ) : null} - + ); }; diff --git a/native-views/react-native-bottom-tabs/src/BottomTabsDrawerNativeComponent.ts b/native-views/react-native-bottom-tabs/src/BottomTabsDrawerNativeComponent.ts index 919e885b8..772e9606a 100644 --- a/native-views/react-native-bottom-tabs/src/BottomTabsDrawerNativeComponent.ts +++ b/native-views/react-native-bottom-tabs/src/BottomTabsDrawerNativeComponent.ts @@ -11,7 +11,10 @@ export interface BottomTabsDrawerNativeProps extends ViewProps { swipeEnabled?: CodegenTypes.WithDefault; hapticFeedbackEnabled?: CodegenTypes.WithDefault; bottomBarHeight?: CodegenTypes.Double; + colorScheme?: CodegenTypes.WithDefault<"system" | "light" | "dark", "system">; + progressEventsEnabled?: CodegenTypes.WithDefault; onDrawerOpenChange?: CodegenTypes.DirectEventHandler>; + onDrawerProgress?: CodegenTypes.DirectEventHandler>; } export default codegenNativeComponent( diff --git a/native-views/react-native-bottom-tabs/src/index.tsx b/native-views/react-native-bottom-tabs/src/index.tsx index dc5e0ddee..64f49d33d 100644 --- a/native-views/react-native-bottom-tabs/src/index.tsx +++ b/native-views/react-native-bottom-tabs/src/index.tsx @@ -9,6 +9,7 @@ export default BottomTabs; * Utilities */ export { SceneMap } from './SceneMap'; +export { default as BottomTabsDrawerNative } from './BottomTabsDrawerNativeComponent'; export { useBottomTabBarHeight } from './utils/useBottomTabBarHeight'; export { BottomTabBarHeightContext } from './utils/BottomTabBarHeightContext'; From a01a28e1d93c0610c826cc087d9f9815b73f5226 Mon Sep 17 00:00:00 2001 From: Franco Date: Sat, 14 Nov 2026 17:30:25 +0800 Subject: [PATCH 2/5] fix(bottom-tabs): address drawer review findings - Lay out the React menu slot at 80% so menu content reaches the native drawer's edge. - Enable progress events one commit after mount, from a small host wrapper so the tabs do not re-render; iOS also re-sends the current position when Fabric attaches the event emitter after the first props. - Keep the iOS page shadow on the same corner radius while it rounds in. - Keep at most one Reduce Motion cross-fade snapshot and remove it on a drag, an animated settle, disabling, detach or resize. - Never carry the page past its target under Reduce Motion. --- .../__tests__/BottomTabs.drawer.test.tsx | 24 +++++++-- .../react-native-bottom-tabs/docs/SPEC.md | 30 ++++++++--- .../ios/RCTBottomTabsDrawerComponentView.mm | 9 ++++ .../RCTBottomTabsDrawerContainerView.swift | 51 ++++++++++++++++--- .../src/BottomTabs.tsx | 29 +++++++++-- 5 files changed, 118 insertions(+), 25 deletions(-) diff --git a/example/react-native/__tests__/BottomTabs.drawer.test.tsx b/example/react-native/__tests__/BottomTabs.drawer.test.tsx index 0cec0cc3e..e8fa790f4 100644 --- a/example/react-native/__tests__/BottomTabs.drawer.test.tsx +++ b/example/react-native/__tests__/BottomTabs.drawer.test.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import { Text, View } from 'react-native'; +import { StyleSheet, Text, View } from 'react-native'; import ReactTestRenderer, { act } from 'react-test-renderer'; jest.mock( @@ -90,6 +90,10 @@ describe('native drawer slots', () => { const drawer = renderer!.root.findByType('NativeDrawer' as any); expect(drawer.props.hapticFeedbackEnabled).toBe(true); expect(drawer.props.swipeEnabled).toBe(true); + // The menu slot lays out at the native drawer width. + expect( + StyleSheet.flatten((drawer.children[0] as any).props.style).width, + ).toBe('80%'); expect(drawer.props.progressEventsEnabled).toBe(false); expect(drawer.props.onDrawerProgress).toBeUndefined(); expect(drawer.props.colorScheme).toBeUndefined(); @@ -100,14 +104,19 @@ describe('native drawer slots', () => { it('passes progress handlers, a replacement host and the color scheme to native as is', async () => { const onProgress = jest.fn(); - const Host = (props: React.PropsWithChildren) => ( - {props.children} - ); + const renderScene = jest.fn(() => ); + const enabledByCommit: boolean[] = []; + const Host = ( + props: React.PropsWithChildren<{ progressEventsEnabled?: boolean }>, + ) => { + enabledByCommit.push(!!props.progressEventsEnabled); + return {props.children}; + }; await act(() => { renderer = ReactTestRenderer.create( } + renderScene={renderScene} onIndexChange={() => {}} renderDrawerContent={menu} onDrawerProgress={onProgress} @@ -118,7 +127,12 @@ describe('native drawer slots', () => { }); expect(renderer!.root.findAllByType('NativeDrawer' as any)).toHaveLength(0); const host = renderer!.root.findByType(Host); + // Off during the mount commit, so native's current-position event is + // sent once the host and its handler are attached. + expect(enabledByCommit).toEqual([false, true]); expect(host.props.progressEventsEnabled).toBe(true); + // That second commit re-renders only the host, not the tabs. + expect(renderScene).toHaveBeenCalledTimes(1); expect(host.props.onDrawerProgress).toBe(onProgress); expect(host.props.colorScheme).toBe('dark'); expect(renderer!.root.findByProps({ testID: 'menu-content' })).toBeTruthy(); diff --git a/native-views/react-native-bottom-tabs/docs/SPEC.md b/native-views/react-native-bottom-tabs/docs/SPEC.md index ef7a89c37..87d5a119c 100644 --- a/native-views/react-native-bottom-tabs/docs/SPEC.md +++ b/native-views/react-native-bottom-tabs/docs/SPEC.md @@ -96,7 +96,10 @@ progress clamped to [0, 1], while the drawer moves. Native emits it only while a handler is set (the wrapper derives the internal `progressEventsEnabled` prop from the handler's presence), at most once per frame, when progress changed by at least .002, and always on reaching 0 or 1. Enabling it emits the current -value once, so a new subscriber starts in sync. The handler is passed to the +value once, so a new subscriber starts in sync. The wrapper enables it one +commit after mount, once the host's event emitter and an animated host's +worklet handler are attached; on iOS the host also re-sends the current value +when Fabric attaches the event emitter after a mount's first props. The handler is passed to the host unchanged, so `drawerHostComponent?` (default: the native host) can be an animated wrapper such as `Animated.createAnimatedComponent(BottomTabsDrawerNative)` whose worklet handler consumes the event on the UI thread. The package does @@ -108,7 +111,8 @@ it can differ from those (an app-level iOS window style override is followed without it). The drawer is physically left on both iOS and Android, including RTL. Its width -is 80 percent of the host. The foreground is the full tab container, including +is 80 percent of the host, and the React menu slot is laid out at the same +80 percent so its descendants reach the menu's edge. The foreground is the full tab container, including the native tab bar and an optional custom JS bar. It keeps its full width and height while moving right, without scaling, scene reparenting or remounting. The native host and two slots remain mounted when the drawer is disabled or its @@ -123,7 +127,7 @@ screens with other display corners never show a radius jump. The dim surface washes the page linearly: white at `.5 * p` in the light palette, RGB 36/36/36 at `.58 * p` in the dark palette. In the light palette the page also casts a black shadow under its left edge and corners, opacity .16, Gaussian sigma 18 -points/dp, no offset; in the dark palette it instead draws a one-physical-pixel +points/dp, no offset, following the current corner radius; in the dark palette it instead draws a one-physical-pixel white edge at 17 percent opacity. The menu scales from .97 to 1 about its left-center edge (1 throughout when motion is reduced, see below) and its opacity is `min(1, p / .6)`. The host itself is transparent, so whatever lies @@ -201,8 +205,12 @@ completion. When the system asks for less motion (iOS Reduce Motion; Android with animator duration scale 0), the menu does not scale. On iOS a tap, close or prop change from rest then cross-fades from a snapshot to the final state over 200 ms instead of moving, and a released drag settles critically -damped (damping ratio 1). Android has no separate reduced-motion setting and -lands such transitions immediately. +damped (damping ratio 1) without travelling past its target. A newer +cross-fade replaces the previous snapshot (capturing it as currently shown); a +request for the target already being faded to leaves the fade running; a drag, +an animated settle, disabling, detach or a resize removes the snapshot. +Android has no separate reduced-motion setting and lands such transitions +immediately. Resize snaps a pending settlement to its target, emitting its user event once if appropriate; an active drag follows the same cancellation rule. Detach cancels animations and callbacks; reattachment reapplies the latest external target. @@ -230,13 +238,19 @@ physical-left placement, and closing pans while opening swipes are disabled. For the reference-recording revision it asserts the 80 percent travel, the light and dark wash, the menu's final scale/opacity/layer, and that progress events are opt-in, start in sync and end on the stable state; the wrapper tests -assert that progress stays off without a handler and that the handler, a -replacement host and the color scheme reach native unchanged. +assert that progress stays off without a handler and during the mount commit, +that the handler, a replacement host and the color scheme reach native +unchanged, and that the menu slot is 80 percent wide. Recorded evidence so far: on the iPhone 17 simulator (iOS 26) in the consumer app, tap open/close timing, fling overshoot (about 2 points), smooth reversal, the corner ramp, the reduced-motion cross-fade, the light/dark palettes and a UI-thread Reanimated progress handler were compared frame by frame with the -reference recording. The Android suite has not yet been run for this revision; +reference recording. After the review fixes, the same setup showed menu content +reaching 20 points from the 80 percent edge, the header avatar hidden at full +open through the deferred progress event, no travel past open on a +reduced-motion fling, and three toggles within 120 ms under Reduce Motion +cross-fading to the final state with no leftover image (snapshot replacement +itself is source-verified). The Android suite has not yet been run for this revision; physical-device smoothness on either platform remains unverified. The standalone `example/react-native/pages/BottomTabsHomeDrawerExample.tsx` diff --git a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerComponentView.mm b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerComponentView.mm index 31817eb45..e01cb2a42 100644 --- a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerComponentView.mm +++ b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerComponentView.mm @@ -19,6 +19,7 @@ @protocol RNBottomTabsDrawerContainer @property(nonatomic, copy) void (^onDrawerProgress)(double progress); - (void)insertChild:(UIView *)child atIndex:(NSInteger)index; - (void)removeChildAtIndex:(NSInteger)index; +- (void)resendProgress; @end using namespace facebook::react; @@ -68,6 +69,14 @@ - (void)unmountChildComponentView:(UIView *)child inde [_drawer removeChildAtIndex:index]; } +- (void)updateEventEmitter:(EventEmitter::Shared const &)eventEmitter +{ + [super updateEventEmitter:eventEmitter]; + // Fabric applies a mount's props before its emitter, so a position reported + // then never left native; send the current one now. + [_drawer resendProgress]; +} + - (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps { const auto &next = *std::static_pointer_cast(props); diff --git a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift index 0efe6f321..43fe87d70 100644 --- a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift +++ b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift @@ -8,6 +8,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat guard enabled != oldValue else { return } interruptGesture() stopAnimation() + removeFadeSnapshot() stableOpen = false setProgress(0) if enabled && open { settle(to: true, velocity: 0, user: false) } @@ -76,6 +77,9 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat private var trackedValue: CGFloat = 0 private var trackedTime: CFTimeInterval = 0 private var trackedVelocity: CGFloat = 0 + private var shadowPathRadius: CGFloat = -1 + // The single snapshot of an in-flight Reduce Motion cross-fade. + private var fadeSnapshot: UIView? // Measured frame by frame from the reference recording: the page travels // 80% of the width, keeps a fixed display-like corner, washes toward the @@ -166,6 +170,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat let user = displayLink != nil && animationUser && previousSize != .zero interruptGesture() stopAnimation() + removeFadeSnapshot() finish(target: enabled && (previousSize == .zero ? open : target), user: user) previousSize = bounds.size } @@ -176,11 +181,8 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat pageClip.frame = foreground.bounds foregroundContent.frame = pageClip.bounds dim.frame = pageClip.bounds - foreground.layer.shadowPath = UIBezierPath( - roundedRect: foreground.bounds, - byRoundingCorners: [.topLeft, .bottomLeft], - cornerRadii: CGSize(width: Self.pageCornerRadius, height: Self.pageCornerRadius) - ).cgPath + // Rebuilt for the new bounds by setProgress below. + shadowPathRadius = -1 if slots.count > 0 { slots[0].frame = menu.bounds } if slots.count > 1 { slots[1].frame = foreground.bounds } setProgress(appliedValue, overshoot: appliedOvershoot) @@ -191,6 +193,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat if window == nil { interruptGesture() stopAnimation() + removeFadeSnapshot() setProgress(stableOpen && enabled ? 1 : 0) } else if enabled && stableOpen != open { settle(to: open, velocity: 0, user: false) @@ -318,6 +321,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat case .began: gestureReturnOpen = displayLink != nil && !animationUser ? animationTarget : stableOpen stopAnimation() + removeFadeSnapshot() gestureStartProgress = progress case .changed: guard recognizer.numberOfTouches <= 1 else { @@ -359,7 +363,17 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat let travel = overshoot ? min(1.03, max(0, raw)) : progress foreground.transform = CGAffineTransform(translationX: menuWidth * travel, y: 0) // Rounds in over the first 10% so screens with other corner radii never pop. - pageClip.layer.cornerRadius = visible ? Self.pageCornerRadius * min(1, progress / 0.1) : 0 + let cornerRadius = visible ? Self.pageCornerRadius * min(1, progress / 0.1) : 0 + pageClip.layer.cornerRadius = cornerRadius + // The shadow follows the same corner while it rounds in. + if cornerRadius != shadowPathRadius { + shadowPathRadius = cornerRadius + foreground.layer.shadowPath = UIBezierPath( + roundedRect: foreground.bounds, + byRoundingCorners: [.topLeft, .bottomLeft], + cornerRadii: CGSize(width: cornerRadius, height: cornerRadius) + ).cgPath + } pageClip.layer.borderWidth = visible && pageHairline ? 1 / max(1, traitCollection.displayScale) : 0 foreground.layer.shadowOpacity = visible ? pageShadowOpacity : 0 dim.alpha = scrimMaxAlpha * progress @@ -378,6 +392,12 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat reportProgress() } + /// Sends the current position again, for an event emitter attached after it was reported. + @objc func resendProgress() { + reportedProgress = -1 + reportProgress() + } + private func reportProgress() { guard progressEventsEnabled else { return } if progress != reportedProgress && (abs(progress - reportedProgress) >= 0.002 || progress == 0 || progress == 1) { @@ -418,10 +438,12 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat let carried = retarget ? trackedVelocity : velocity stopAnimation() guard bounds.width > 0, window != nil else { + removeFadeSnapshot() stableOpen = target setProgress(target ? 1 : 0) return } + // Already at the target; a cross-fade landing there keeps fading. if !retarget && progress == (target ? 1 : 0) { finish(target: target, user: user) return @@ -429,6 +451,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat if tween && !retarget && UIAccessibility.isReduceMotionEnabled && crossFade(to: target, user: user) { return } + removeFadeSnapshot() animationFrom = from animationVelocity = min(12, max(-12, carried)) animationTarget = target @@ -448,19 +471,30 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat // Reduce Motion: taps and programmatic changes cross-fade into place // instead of sliding the whole page. private func crossFade(to target: Bool, user: Bool) -> Bool { + // Captures what is on screen, including any fade still in progress, which + // this one then replaces: the host keeps at most one snapshot. guard let snapshot = snapshotView(afterScreenUpdates: false) else { return false } + removeFadeSnapshot() snapshot.frame = bounds snapshot.isUserInteractionEnabled = false addSubview(snapshot) + fadeSnapshot = snapshot finish(target: target, user: user) UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseOut], animations: { snapshot.alpha = 0 - }, completion: { _ in + }, completion: { [weak self] _ in snapshot.removeFromSuperview() + if self?.fadeSnapshot === snapshot { self?.fadeSnapshot = nil } }) return true } + private func removeFadeSnapshot() { + fadeSnapshot?.layer.removeAllAnimations() + fadeSnapshot?.removeFromSuperview() + fadeSnapshot = nil + } + @objc private func tick() { let now = CACurrentMediaTime() let elapsed = CGFloat(now - animationStart) @@ -490,7 +524,8 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat } trackedValue = value trackedTime = now - setProgress(value, overshoot: isSpring) + // Reduce Motion never carries the page past its target. + setProgress(value, overshoot: isSpring && !UIAccessibility.isReduceMotionEnabled) // A spring ends once it is visually at rest, not after a fixed time. let done = isSpring ? (abs(value - target) < 0.0005 && abs(trackedVelocity) < 0.02) || elapsed >= 0.6 diff --git a/native-views/react-native-bottom-tabs/src/BottomTabs.tsx b/native-views/react-native-bottom-tabs/src/BottomTabs.tsx index 527311012..b0c35588d 100644 --- a/native-views/react-native-bottom-tabs/src/BottomTabs.tsx +++ b/native-views/react-native-bottom-tabs/src/BottomTabs.tsx @@ -386,6 +386,26 @@ const defaultGetIcon = ({ const ANDROID_MAX_TABS = 100; +type DrawerHostProps = React.ComponentProps; + +// Progress events start one commit after mount: during the mount itself the +// iOS event emitter and an animated host's worklet handler are not attached +// yet, so the current position native sends on enabling would be lost. The +// state lives here so that commit re-renders only the host, not the tabs. +function DrawerHostWithProgress({ + host: Host, + ...props +}: DrawerHostProps & { host: React.ComponentType }) { + const hasProgressHandler = props.onDrawerProgress != null; + const [mounted, setMounted] = React.useState(false); + React.useEffect(() => { + if (hasProgressHandler) setMounted(true); + }, [hasProgressHandler]); + return ( + + ); +} + const BottomTabs = ({ navigationState, renderScene, @@ -628,7 +648,8 @@ const BottomTabs = ({ return ( - ({ hapticFeedbackEnabled={hapticFeedbackEnabled} bottomBarHeight={tabBarHeight ?? 0} colorScheme={drawerColorScheme} - progressEventsEnabled={onDrawerProgress != null} onDrawerOpenChange={(event) => onDrawerOpenChange?.(event.nativeEvent.open) } @@ -746,7 +766,7 @@ const BottomTabs = ({ ) : null} - + ); }; @@ -759,7 +779,8 @@ const styles = StyleSheet.create({ }, drawerMenu: { position: "absolute", - width: "78%", + // Must match the native drawer width so menu descendants lay out to its edge. + width: "80%", height: "100%", }, screen: { From f402457cd80b3342828ba5dc56bcfbfd68e210ff Mon Sep 17 00:00:00 2001 From: Franco Date: Sat, 14 Nov 2026 17:53:44 +0800 Subject: [PATCH 3/5] fix(bottom-tabs): report Reduce Motion transitions when the fade ends A user tap or dim close under Reduce Motion now applies its final state behind the cross-fade snapshot and reports onDrawerOpenChange (and the haptic) when the 200 ms fade completes. A newer transition, disabling or detach discards the pending report; a drag or resize reports it at once; a newer non-user request for the same target cancels it. --- .../react-native-bottom-tabs/docs/SPEC.md | 6 ++- .../RCTBottomTabsDrawerContainerView.swift | 49 ++++++++++++++----- 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/native-views/react-native-bottom-tabs/docs/SPEC.md b/native-views/react-native-bottom-tabs/docs/SPEC.md index 87d5a119c..b00b97870 100644 --- a/native-views/react-native-bottom-tabs/docs/SPEC.md +++ b/native-views/react-native-bottom-tabs/docs/SPEC.md @@ -208,7 +208,11 @@ state over 200 ms instead of moving, and a released drag settles critically damped (damping ratio 1) without travelling past its target. A newer cross-fade replaces the previous snapshot (capturing it as currently shown); a request for the target already being faded to leaves the fade running; a drag, -an animated settle, disabling, detach or a resize removes the snapshot. +an animated settle, disabling, detach or a resize removes the snapshot. A user +transition that cross-fades reports `onDrawerOpenChange` and its haptic when +the fade ends, not when it starts. A newer transition, disabling or detach +discards that pending report; a drag or a resize reports it at once; a newer +non-user request for the same target cancels it. Android has no separate reduced-motion setting and lands such transitions immediately. Resize snaps a pending settlement to its target, emitting its user event once diff --git a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift index 43fe87d70..98311423d 100644 --- a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift +++ b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift @@ -78,8 +78,10 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat private var trackedTime: CFTimeInterval = 0 private var trackedVelocity: CGFloat = 0 private var shadowPathRadius: CGFloat = -1 - // The single snapshot of an in-flight Reduce Motion cross-fade. + // The single snapshot of an in-flight Reduce Motion cross-fade, and the + // user transition it reports once it ends. private var fadeSnapshot: UIView? + private var fadeCompletion: (target: Bool, changed: Bool)? // Measured frame by frame from the reference recording: the page travels // 80% of the width, keeps a fixed display-like corner, washes toward the @@ -170,7 +172,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat let user = displayLink != nil && animationUser && previousSize != .zero interruptGesture() stopAnimation() - removeFadeSnapshot() + removeFadeSnapshot(complete: true) finish(target: enabled && (previousSize == .zero ? open : target), user: user) previousSize = bounds.size } @@ -321,7 +323,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat case .began: gestureReturnOpen = displayLink != nil && !animationUser ? animationTarget : stableOpen stopAnimation() - removeFadeSnapshot() + removeFadeSnapshot(complete: true) gestureStartProgress = progress case .changed: guard recognizer.numberOfTouches <= 1 else { @@ -443,8 +445,13 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat setProgress(target ? 1 : 0) return } - // Already at the target; a cross-fade landing there keeps fading. if !retarget && progress == (target ? 1 : 0) { + // A cross-fade landing there keeps fading; a newer non-user request + // cancels its pending user completion. + if fadeSnapshot != nil { + if !user { fadeCompletion = nil } + return + } finish(target: target, user: user) return } @@ -479,17 +486,34 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat snapshot.isUserInteractionEnabled = false addSubview(snapshot) fadeSnapshot = snapshot - finish(target: target, user: user) + // The final state applies now, under the snapshot; a user transition + // completes (callback and haptic) only when the fade does. + let changed = stableOpen != target + stableOpen = target + setProgress(target ? 1 : 0) + fadeCompletion = user ? (target, changed) : nil UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseOut], animations: { snapshot.alpha = 0 }, completion: { [weak self] _ in snapshot.removeFromSuperview() - if self?.fadeSnapshot === snapshot { self?.fadeSnapshot = nil } + guard let self, self.fadeSnapshot === snapshot else { return } + self.fadeSnapshot = nil + self.completeFade() }) return true } - private func removeFadeSnapshot() { + private func completeFade() { + guard let pending = fadeCompletion else { return } + fadeCompletion = nil + reportCompletion(target: pending.target, changed: pending.changed) + } + + /// Drops the cross-fade snapshot. Its pending user completion is reported + /// first when `complete` is set (a drag or resize takes over), and discarded + /// otherwise (a newer transition, disabling or detach). + private func removeFadeSnapshot(complete: Bool = false) { + if complete { completeFade() } else { fadeCompletion = nil } fadeSnapshot?.layer.removeAllAnimations() fadeSnapshot?.removeFromSuperview() fadeSnapshot = nil @@ -542,10 +566,13 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat let changed = stableOpen != target stableOpen = target setProgress(target ? 1 : 0) - if user && (changed || target != open) { - if hapticFeedbackEnabled && changed { UIImpactFeedbackGenerator(style: .light).impactOccurred() } - onDrawerOpenChange?(target) - } + if user { reportCompletion(target: target, changed: changed) } + } + + private func reportCompletion(target: Bool, changed: Bool) { + guard changed || target != open else { return } + if hapticFeedbackEnabled && changed { UIImpactFeedbackGenerator(style: .light).impactOccurred() } + onDrawerOpenChange?(target) } private func stopAnimation() { From 8e172affc90748b92e183ab95969b176a2a3fa22 Mon Sep 17 00:00:00 2001 From: Franco Date: Sat, 14 Nov 2026 21:14:33 +0800 Subject: [PATCH 4/5] fix(bottom-tabs): let a drag take over a Reduce Motion fade A cross-fade now completes like a running settle: the stable state, the settled event and the haptic follow when it lands. A drag that begins during the fade drops it, so a stale close no longer echoes back as a prop and cancels the drag. Adds an iOS XCTest suite for the fade lifecycle, run hostless by the ui group of the native tests. --- example/react-native/ios/Podfile | 1 + example/react-native/ios/Podfile.lock | 29 ++- .../react-native-bottom-tabs/docs/SPEC.md | 26 ++- .../RCTBottomTabsDrawerContainerView.swift | 82 ++++--- .../BottomTabsDrawerReduceMotionTests.swift | 202 ++++++++++++++++++ .../react-native-bottom-tabs.podspec | 6 + scripts/ios-native-plan.mjs | 4 +- scripts/ios-native-plan.test.mjs | 2 + 8 files changed, 308 insertions(+), 44 deletions(-) create mode 100644 native-views/react-native-bottom-tabs/ios/tests/BottomTabsDrawerReduceMotionTests.swift diff --git a/example/react-native/ios/Podfile b/example/react-native/ios/Podfile index 19b3d7165..d18862131 100644 --- a/example/react-native/ios/Podfile +++ b/example/react-native/ios/Podfile @@ -47,6 +47,7 @@ target 'example' do pod 'react-native-pager-view', :path => '../../../node_modules/@onekeyfe/react-native-pager-view', :testspecs => ['Tests'] pod 'OneKeyTextInput', :path => '../../../node_modules/@onekeyfe/react-native-text-input', :testspecs => ['Tests'] pod 'react-native-native-list', :path => '../../../node_modules/@onekeyfe/react-native-native-list', :testspecs => ['Tests'] + pod 'react-native-bottom-tabs', :path => '../../../node_modules/@onekeyfe/react-native-bottom-tabs', :testspecs => ['Tests'] pod 'PerpDepthBar', :path => '../../../node_modules/@onekeyfe/react-native-perp-depth-bar', :testspecs => ['Tests'] pod 'ReactNativeBundleCrypto', :path => '../../../node_modules/@onekeyfe/react-native-bundle-crypto', :testspecs => ['Tests'] pod 'ReactNativeCaptureProtection', :path => '../../../node_modules/@onekeyfe/react-native-capture-protection', :testspecs => ['Tests'] diff --git a/example/react-native/ios/Podfile.lock b/example/react-native/ios/Podfile.lock index b297f1a0e..659000a90 100644 --- a/example/react-native/ios/Podfile.lock +++ b/example/react-native/ios/Podfile.lock @@ -1892,6 +1892,30 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga + - react-native-bottom-tabs/Tests (6.7.0-26): + - hermes-engine + - OneKeyImage + - RCTRequired + - RCTTypeSafety + - React-bridging + - React-Core + - React-Core-prebuilt + - React-cxxstableapi + - React-debug + - React-Fabric + - React-featureflags + - React-graphics + - React-ImageManager + - React-jsi + - React-NativeModulesApple + - React-RCTFabric + - React-renderercss + - React-rendererdebug + - React-utils + - ReactCodegen + - ReactCommon/turbomodule/core + - ReactNativeDependencies + - Yoga - react-native-native-list (6.7.0-26): - hermes-engine - NitroModules @@ -3311,6 +3335,7 @@ DEPENDENCIES: - React-microtasksnativemodule (from `../../../node_modules/react-native/ReactCommon/react/nativemodule/microtasks`) - React-mutationobservernativemodule (from `../../../node_modules/react-native/ReactCommon/react/nativemodule/mutationobserver`) - "react-native-bottom-tabs (from `../../../node_modules/@onekeyfe/react-native-bottom-tabs`)" + - "react-native-bottom-tabs/Tests (from `../../../node_modules/@onekeyfe/react-native-bottom-tabs`)" - "react-native-native-list (from `../../../node_modules/@onekeyfe/react-native-native-list`)" - "react-native-native-list/Tests (from `../../../node_modules/@onekeyfe/react-native-native-list`)" - "react-native-pager-view (from `../../../node_modules/@onekeyfe/react-native-pager-view`)" @@ -3739,7 +3764,7 @@ SPEC CHECKSUMS: React-Mapbuffer: a2dae4f2cb335ebb97f2240494d0c2bab84cd339 React-microtasksnativemodule: 8b3aaa5f3b907ecf071b105589868d9f027a448d React-mutationobservernativemodule: 11d77d3f7360578f07847843544ada23cc473049 - react-native-bottom-tabs: 31c6a231936155254baa3a09c6e76a1cae887fde + react-native-bottom-tabs: b42bb7227d2d7870a8ca66513bb44186fe76368f react-native-native-list: f7c9cacff8abdbd12e7405f5ff855098698dcb4b react-native-pager-view: 03d14fbd70b2e1edbdc6dda3ab3b9c213d1e6774 react-native-safe-area-context: 839ca66874035361e526a8bcb1bfe7c2076c5c0d @@ -3811,6 +3836,6 @@ SPEC CHECKSUMS: TcpSocket: c8d79a8794cc9848513718044ceee976d8bcf6f0 Yoga: d1c536142c5ff8ec8cd856ab2a7c227a1d875c8e -PODFILE CHECKSUM: 6dbd008521e902b8ae039b8440e066a762f0955e +PODFILE CHECKSUM: f3f249fd79ae24990015132b000a41da6eab78e2 COCOAPODS: 1.16.2 diff --git a/native-views/react-native-bottom-tabs/docs/SPEC.md b/native-views/react-native-bottom-tabs/docs/SPEC.md index b00b97870..2d46161ed 100644 --- a/native-views/react-native-bottom-tabs/docs/SPEC.md +++ b/native-views/react-native-bottom-tabs/docs/SPEC.md @@ -205,14 +205,16 @@ completion. When the system asks for less motion (iOS Reduce Motion; Android with animator duration scale 0), the menu does not scale. On iOS a tap, close or prop change from rest then cross-fades from a snapshot to the final state over 200 ms instead of moving, and a released drag settles critically -damped (damping ratio 1) without travelling past its target. A newer -cross-fade replaces the previous snapshot (capturing it as currently shown); a -request for the target already being faded to leaves the fade running; a drag, -an animated settle, disabling, detach or a resize removes the snapshot. A user -transition that cross-fades reports `onDrawerOpenChange` and its haptic when -the fade ends, not when it starts. A newer transition, disabling or detach -discards that pending report; a drag or a resize reports it at once; a newer -non-user request for the same target cancels it. +damped (damping ratio 1) without travelling past its target. A cross-fade is +an in-flight transition like an animation: its final state shows at once under +the snapshot, but the stable state, `onDrawerOpenChange` and the haptic follow +only when the fade ends. A newer cross-fade replaces the previous snapshot +(capturing it as currently shown). A request for the target already being +faded to leaves the fade running and only replaces whether its completion is a +user transition. A touch, an animated settle, a newer cross-fade, disabling or +detach removes the snapshot without completing it, as a touch does a running +animation, so a drag that begins during a faded close never receives that +close's prop echo; a resize completes it at once. Android has no separate reduced-motion setting and lands such transitions immediately. Resize snaps a pending settlement to its target, emitting its user event once @@ -244,7 +246,13 @@ light and dark wash, the menu's final scale/opacity/layer, and that progress events are opt-in, start in sync and end on the stable state; the wrapper tests assert that progress stays off without a handler and during the mount commit, that the handler, a replacement host and the color scheme reach native -unchanged, and that the menu slot is 80 percent wide. +unchanged, and that the menu slot is 80 percent wide. The iOS suite +`ios/tests/BottomTabsDrawerReduceMotionTests.swift` runs without an app host, +forcing Reduce Motion and supplying the fade snapshot through internal test +hooks. It asserts that a user close reports once, after the snapshot is gone; +that a drag taking over the fade drops the faded close and reports only its own +release; that a resize lands the fade at once; and that same-target and newer +requests, disabling and detach take over or drop the pending report. Recorded evidence so far: on the iPhone 17 simulator (iOS 26) in the consumer app, tap open/close timing, fling overshoot (about 2 points), smooth reversal, the corner ramp, the reduced-motion cross-fade, the light/dark palettes and a diff --git a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift index 98311423d..e1ee70b17 100644 --- a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift +++ b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift @@ -78,10 +78,16 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat private var trackedTime: CFTimeInterval = 0 private var trackedVelocity: CGFloat = 0 private var shadowPathRadius: CGFloat = -1 - // The single snapshot of an in-flight Reduce Motion cross-fade, and the - // user transition it reports once it ends. + // An in-flight Reduce Motion cross-fade: its one snapshot, the state it + // lands on and whether that is a user transition. Like a running settle, it + // updates `stableOpen` and reports only when it lands. private var fadeSnapshot: UIView? - private var fadeCompletion: (target: Bool, changed: Bool)? + private var fadeTarget = false + private var fadeUser = false + // Hooks for native tests: they set Reduce Motion, and run without an app + // host, where UIKit cannot snapshot a view. + var isReduceMotionEnabled: () -> Bool = { UIAccessibility.isReduceMotionEnabled } + var makeFadeSnapshot: (UIView) -> UIView? = { $0.snapshotView(afterScreenUpdates: false) } // Measured frame by frame from the reference recording: the page travels // 80% of the width, keeps a fixed display-like corner, washes toward the @@ -167,12 +173,13 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat override func layoutSubviews() { super.layoutSubviews() if previousSize != bounds.size { + // A cross-fade's image is of the old size, so it lands at once. + completeFade() let dragging = pan.state == .began || pan.state == .changed let target = displayLink != nil ? animationTarget : (dragging ? gestureReturnOpen : stableOpen) let user = displayLink != nil && animationUser && previousSize != .zero interruptGesture() stopAnimation() - removeFadeSnapshot(complete: true) finish(target: enabled && (previousSize == .zero ? open : target), user: user) previousSize = bounds.size } @@ -321,9 +328,18 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat @objc private func handlePan(_ recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: - gestureReturnOpen = displayLink != nil && !animationUser ? animationTarget : stableOpen + // The drag takes over a settle or cross-fade in flight and drops its + // completion. Cancelling returns to a programmatic target, else to the + // stable state. + if displayLink != nil && !animationUser { + gestureReturnOpen = animationTarget + } else if fadeSnapshot != nil && !fadeUser { + gestureReturnOpen = fadeTarget + } else { + gestureReturnOpen = stableOpen + } stopAnimation() - removeFadeSnapshot(complete: true) + removeFadeSnapshot() gestureStartProgress = progress case .changed: guard recognizer.numberOfTouches <= 1 else { @@ -384,7 +400,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat foregroundContent.accessibilityElementsHidden = visible // The menu grows from its left-center edge and fades in over whatever is // behind the host, fully visible by 60% open. - let minScale = UIAccessibility.isReduceMotionEnabled ? 1 : Self.menuMinScale + let minScale = isReduceMotionEnabled() ? 1 : Self.menuMinScale let scale = minScale + (1 - minScale) * progress menu.transform = CGAffineTransform(translationX: -(1 - scale) * menu.bounds.width / 2, y: 0) .scaledBy(x: scale, y: scale) @@ -446,16 +462,16 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat return } if !retarget && progress == (target ? 1 : 0) { - // A cross-fade landing there keeps fading; a newer non-user request - // cancels its pending user completion. + // A cross-fade landing there keeps fading; as for a running animation, + // the newer request decides whether its completion is a user event. if fadeSnapshot != nil { - if !user { fadeCompletion = nil } + fadeUser = user return } finish(target: target, user: user) return } - if tween && !retarget && UIAccessibility.isReduceMotionEnabled && crossFade(to: target, user: user) { + if tween && !retarget && isReduceMotionEnabled() && crossFade(to: target, user: user) { return } removeFadeSnapshot() @@ -480,43 +496,45 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat private func crossFade(to target: Bool, user: Bool) -> Bool { // Captures what is on screen, including any fade still in progress, which // this one then replaces: the host keeps at most one snapshot. - guard let snapshot = snapshotView(afterScreenUpdates: false) else { return false } + guard let snapshot = makeFadeSnapshot(self) else { return false } removeFadeSnapshot() snapshot.frame = bounds snapshot.isUserInteractionEnabled = false addSubview(snapshot) fadeSnapshot = snapshot - // The final state applies now, under the snapshot; a user transition - // completes (callback and haptic) only when the fade does. - let changed = stableOpen != target - stableOpen = target + fadeTarget = target + fadeUser = user + // The final state shows now, under the snapshot. The transition completes + // (stable state, callback and haptic) only when the fade does. setProgress(target ? 1 : 0) - fadeCompletion = user ? (target, changed) : nil UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseOut], animations: { snapshot.alpha = 0 }, completion: { [weak self] _ in snapshot.removeFromSuperview() guard let self, self.fadeSnapshot === snapshot else { return } - self.fadeSnapshot = nil self.completeFade() }) return true } + /// Lands an in-flight cross-fade on its target, as a settle's last frame does. private func completeFade() { - guard let pending = fadeCompletion else { return } - fadeCompletion = nil - reportCompletion(target: pending.target, changed: pending.changed) - } - - /// Drops the cross-fade snapshot. Its pending user completion is reported - /// first when `complete` is set (a drag or resize takes over), and discarded - /// otherwise (a newer transition, disabling or detach). - private func removeFadeSnapshot(complete: Bool = false) { - if complete { completeFade() } else { fadeCompletion = nil } - fadeSnapshot?.layer.removeAllAnimations() - fadeSnapshot?.removeFromSuperview() + guard fadeSnapshot != nil else { return } + let target = fadeTarget + let user = fadeUser + removeFadeSnapshot() + finish(target: target, user: user) + } + + /// Drops the cross-fade without landing it (a newer transition, a drag, + /// disabling or detach), so its completion is never reported. + private func removeFadeSnapshot() { + guard let snapshot = fadeSnapshot else { return } + // Cleared first, so the completion handler that removing the animation + // triggers does not land it. fadeSnapshot = nil + snapshot.layer.removeAllAnimations() + snapshot.removeFromSuperview() } @objc private func tick() { @@ -533,7 +551,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat } else { let w = Self.springFrequency let a = animationFrom - target - if UIAccessibility.isReduceMotionEnabled { + if isReduceMotionEnabled() { // Critically damped: same speed, no bounce. value = target + (a + (animationVelocity + w * a) * elapsed) * exp(-w * elapsed) } else { @@ -549,7 +567,7 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat trackedValue = value trackedTime = now // Reduce Motion never carries the page past its target. - setProgress(value, overshoot: isSpring && !UIAccessibility.isReduceMotionEnabled) + setProgress(value, overshoot: isSpring && !isReduceMotionEnabled()) // A spring ends once it is visually at rest, not after a fixed time. let done = isSpring ? (abs(value - target) < 0.0005 && abs(trackedVelocity) < 0.02) || elapsed >= 0.6 diff --git a/native-views/react-native-bottom-tabs/ios/tests/BottomTabsDrawerReduceMotionTests.swift b/native-views/react-native-bottom-tabs/ios/tests/BottomTabsDrawerReduceMotionTests.swift new file mode 100644 index 000000000..e2a6f5361 --- /dev/null +++ b/native-views/react-native-bottom-tabs/ios/tests/BottomTabsDrawerReduceMotionTests.swift @@ -0,0 +1,202 @@ +import UIKit +import XCTest +@testable import BottomTabsModule + +/// Reduce Motion cross-fades: when a faded transition reports, and what takes +/// it over. Runs without an app host. +@MainActor +final class BottomTabsDrawerReduceMotionTests: XCTestCase { + func testUserCloseReportsOnceWhenTheFadeEnds() throws { + let fixture = Fixture(open: true) + defer { fixture.close() } + + XCTAssertTrue(fixture.drawer.accessibilityPerformEscape()) + try fixture.requireFade() + XCTAssertEqual(fixture.progress, 0, "the final state shows under the snapshot") + XCTAssertEqual(fixture.events, [], "nothing is reported while the fade runs") + XCTAssertEqual(fixture.stableOpen, true) + + XCTAssertTrue(fixture.waitUntil { !fixture.isFading }) + XCTAssertEqual(fixture.events, [false]) + XCTAssertEqual(fixture.fadingAtEvent, [false], "the report waits for the snapshot to go") + XCTAssertEqual(fixture.stableOpen, false) + } + + func testDragTakingOverTheFadeDropsItsStaleClose() throws { + let fixture = Fixture(open: true) + defer { fixture.close() } + XCTAssertTrue(fixture.drawer.accessibilityPerformEscape()) + try fixture.requireFade() + + fixture.pan(.began) + XCTAssertFalse(fixture.isFading) + // A close reported here would echo back as `open = false` and cancel the drag. + XCTAssertEqual(fixture.events, []) + fixture.pan(.changed, dx: fixture.menuWidth * 0.9) + XCTAssertEqual(fixture.progress, 0.9, accuracy: 0.001) + fixture.pan(.ended) + XCTAssertTrue(fixture.waitUntil { !fixture.isAnimating }) + + XCTAssertEqual(fixture.progress, 1) + XCTAssertEqual(fixture.stableOpen, true) + XCTAssertEqual(fixture.events, [], "reopening lands on the state JS already has") + fixture.wait(0.3) + XCTAssertEqual(fixture.events, []) + } + + func testDragTakingOverTheFadeReportsItsOwnClose() throws { + let fixture = Fixture(open: true) + defer { fixture.close() } + XCTAssertTrue(fixture.drawer.accessibilityPerformEscape()) + try fixture.requireFade() + + fixture.pan(.began) + fixture.pan(.changed, dx: fixture.menuWidth * 0.2) + fixture.pan(.ended) + XCTAssertTrue(fixture.waitUntil { !fixture.isAnimating }) + + XCTAssertEqual(fixture.progress, 0) + XCTAssertEqual(fixture.events, [false]) + fixture.wait(0.3) + XCTAssertEqual(fixture.events, [false]) + } + + func testResizeLandsTheFadeAtOnce() throws { + let fixture = Fixture(open: true) + defer { fixture.close() } + XCTAssertTrue(fixture.drawer.accessibilityPerformEscape()) + try fixture.requireFade() + + fixture.drawer.frame.size.width = 420 + fixture.drawer.layoutIfNeeded() + XCTAssertFalse(fixture.isFading) + XCTAssertEqual(fixture.events, [false]) + XCTAssertEqual(fixture.stableOpen, false) + fixture.wait(0.3) + XCTAssertEqual(fixture.events, [false], "the replaced fade does not report again") + } + + func testNewerRequestsTakeOverTheFadeAndItsCompletion() throws { + let fixture = Fixture(open: true) + defer { fixture.close() } + XCTAssertTrue(fixture.drawer.accessibilityPerformEscape()) + try fixture.requireFade() + + // JS closes too: same target, so the landing is no longer a user event. + fixture.drawer.open = false + // JS reopens: a newer fade replaces the first, keeping one snapshot. + fixture.drawer.open = true + try fixture.requireFade() + XCTAssertEqual(fixture.drawer.subviews.count, 3) + XCTAssertEqual(fixture.progress, 1) + + XCTAssertTrue(fixture.waitUntil { !fixture.isFading }) + fixture.wait(0.3) + XCTAssertEqual(fixture.events, []) + XCTAssertEqual(fixture.stableOpen, true) + XCTAssertEqual(fixture.drawer.subviews.count, 2) + } + + func testDisablingOrDetachingDropsThePendingClose() throws { + let disabled = Fixture(open: true) + defer { disabled.close() } + XCTAssertTrue(disabled.drawer.accessibilityPerformEscape()) + try disabled.requireFade() + disabled.drawer.enabled = false + XCTAssertFalse(disabled.isFading) + disabled.wait(0.3) + XCTAssertEqual(disabled.events, []) + + let detached = Fixture(open: true) + defer { detached.close() } + XCTAssertTrue(detached.drawer.accessibilityPerformEscape()) + try detached.requireFade() + detached.drawer.removeFromSuperview() + XCTAssertFalse(detached.isFading) + // Like an interrupted settle, it returns to the last state JS was told. + XCTAssertEqual(detached.progress, 1) + detached.wait(0.3) + XCTAssertEqual(detached.events, []) + detached.window.addSubview(detached.drawer) + XCTAssertEqual(detached.progress, 1) + XCTAssertEqual(detached.events, []) + } +} + +@MainActor +private final class Fixture { + let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) + let drawer = RCTBottomTabsDrawerContainerView(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) + private(set) var events: [Bool] = [] + private(set) var fadingAtEvent: [Bool] = [] + private let recognizer = FakePan(target: nil, action: nil) + + /// An enabled drawer that already rests at `open`, as the prop echo leaves it. + init(open: Bool) { + drawer.isReduceMotionEnabled = { true } + drawer.makeFadeSnapshot = { _ in UIView() } + drawer.insertChild(UIView(), atIndex: 0) + drawer.insertChild(UIView(), atIndex: 1) + drawer.swipeEnabled = true + drawer.enabled = true + // Outside a window, the drawer lands on a target without animating. + drawer.open = open + window.addSubview(drawer) + window.isHidden = false + drawer.layoutIfNeeded() + drawer.onDrawerOpenChange = { [unowned self] open in + self.events.append(open) + self.fadingAtEvent.append(self.isFading) + } + } + + var menuWidth: CGFloat { drawer.bounds.width * 0.8 } + var progress: CGFloat { value("progress") ?? -1 } + var stableOpen: Bool? { value("stableOpen") } + var isFading: Bool { value("fadeSnapshot") as UIView? != nil } + var isAnimating: Bool { value("displayLink") as CADisplayLink? != nil } + + func requireFade(file: StaticString = #filePath, line: UInt = #line) throws { + _ = try XCTUnwrap(value("fadeSnapshot") as UIView?, "Reduce Motion should cross-fade", + file: file, line: line) + } + + /// Delivers one recognizer callback, as UIKit does for the drawer's pan. + func pan(_ state: UIGestureRecognizer.State, dx: CGFloat = 0) { + recognizer.fakeState = state + recognizer.fakeTranslation = CGPoint(x: dx, y: 0) + drawer.perform(NSSelectorFromString("handlePan:"), with: recognizer) + } + + func wait(_ seconds: TimeInterval) { + RunLoop.main.run(until: Date().addingTimeInterval(seconds)) + } + + func waitUntil(timeout: TimeInterval = 2, _ condition: () -> Bool) -> Bool { + let deadline = Date().addingTimeInterval(timeout) + while !condition() && Date() < deadline { wait(0.01) } + return condition() + } + + func close() { + drawer.removeFromSuperview() + window.isHidden = true + } + + private func value(_ name: String) -> T? { + Mirror(reflecting: drawer).descendant(name) as? T + } +} + +private final class FakePan: UIPanGestureRecognizer { + var fakeState: UIGestureRecognizer.State = .possible + var fakeTranslation = CGPoint.zero + + override var state: UIGestureRecognizer.State { + get { fakeState } + set { fakeState = newValue } + } + override var numberOfTouches: Int { 1 } + override func translation(in view: UIView?) -> CGPoint { fakeTranslation } + override func velocity(in view: UIView?) -> CGPoint { .zero } +} diff --git a/native-views/react-native-bottom-tabs/react-native-bottom-tabs.podspec b/native-views/react-native-bottom-tabs/react-native-bottom-tabs.podspec index 4ef99bf5c..eaa843fe7 100644 --- a/native-views/react-native-bottom-tabs/react-native-bottom-tabs.podspec +++ b/native-views/react-native-bottom-tabs/react-native-bottom-tabs.podspec @@ -19,6 +19,7 @@ Pod::Spec.new do |s| "ios/**/*.{swift}", "ios/**/*.{h,m,mm,cpp}", ] + s.exclude_files = "ios/tests/**/*" s.static_framework = true @@ -34,5 +35,10 @@ Pod::Spec.new do |s| s.dependency "OneKeyImage" + s.test_spec "Tests" do |test_spec| + test_spec.source_files = "ios/tests/**/*.swift" + test_spec.pod_target_xcconfig = { "PRODUCT_MODULE_NAME" => "BottomTabsModuleTests" } + end + install_modules_dependencies(s) end diff --git a/scripts/ios-native-plan.mjs b/scripts/ios-native-plan.mjs index 28e454573..13abd0289 100644 --- a/scripts/ios-native-plan.mjs +++ b/scripts/ios-native-plan.mjs @@ -1,6 +1,7 @@ import { pathToFileURL } from "node:url"; -// Keep Pager with NativeList and Image: its test bundle links both pods. +// Keep Pager with NativeList and Image: its test bundle links both pods. Bottom +// tabs also links Image. const plans = { ui: { buildTargets: [], @@ -8,6 +9,7 @@ const plans = { "react-native-pager-view-Unit-Tests", "react-native-native-list-Unit-Tests", "OneKeyImage-Unit-Tests", + "react-native-bottom-tabs-Unit-Tests", ], }, services: { diff --git a/scripts/ios-native-plan.test.mjs b/scripts/ios-native-plan.test.mjs index 9dd8299f4..1dd71a743 100644 --- a/scripts/ios-native-plan.test.mjs +++ b/scripts/ios-native-plan.test.mjs @@ -20,6 +20,7 @@ const originalSchemes = [ "react-native-native-list-Unit-Tests", "PerpDepthBar-Unit-Tests", "ReactNativeBundleCrypto-Unit-Tests", "ReactNativeImageCropPicker-Unit-Tests", "ReactNativeCaptureProtection-Unit-Tests", "ReactNativePhotoLibrary-Unit-Tests", "ReactNativeJpush-Unit-Tests", + "react-native-bottom-tabs-Unit-Tests", ]; test("two independent macOS jobs preserve every original iOS suite and both pod builds", () => { @@ -43,6 +44,7 @@ test("two independent macOS jobs preserve every original iOS suite and both pod assert.deepEqual(plans.flatMap((plan) => plan.buildTargets), ["ReactNativeLiteCard", "NativeOverlay"]); assert.deepEqual(getIosNativePlan("ui").testSchemes, [ "react-native-pager-view-Unit-Tests", "react-native-native-list-Unit-Tests", "OneKeyImage-Unit-Tests", + "react-native-bottom-tabs-Unit-Tests", ]); }); From e9b48d0b72da717927d1eef531fc827df43de07c Mon Sep 17 00:00:00 2001 From: Franco Date: Sun, 15 Nov 2026 12:49:01 +0800 Subject: [PATCH 5/5] fix(bottom-tabs): keep touches off the views under a Reduce Motion fade --- .../react-native-bottom-tabs/docs/SPEC.md | 10 ++++-- .../RCTBottomTabsDrawerContainerView.swift | 10 ++++++ .../BottomTabsDrawerReduceMotionTests.swift | 33 +++++++++++++++++-- 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/native-views/react-native-bottom-tabs/docs/SPEC.md b/native-views/react-native-bottom-tabs/docs/SPEC.md index 2d46161ed..50ef7fc6a 100644 --- a/native-views/react-native-bottom-tabs/docs/SPEC.md +++ b/native-views/react-native-bottom-tabs/docs/SPEC.md @@ -214,7 +214,9 @@ faded to leaves the fade running and only replaces whether its completion is a user transition. A touch, an animated settle, a newer cross-fade, disabling or detach removes the snapshot without completing it, as a touch does a running animation, so a drag that begins during a faded close never receives that -close's prop echo; a resize completes it at once. +close's prop echo; a resize completes it at once. While the snapshot shows, the +host takes every touch itself, so none reaches a page, menu or dim control that +is already in the final state under it; the drawer pan still receives them. Android has no separate reduced-motion setting and lands such transitions immediately. Resize snaps a pending settlement to its target, emitting its user event once @@ -251,8 +253,10 @@ unchanged, and that the menu slot is 80 percent wide. The iOS suite forcing Reduce Motion and supplying the fade snapshot through internal test hooks. It asserts that a user close reports once, after the snapshot is gone; that a drag taking over the fade drops the faded close and reports only its own -release; that a resize lands the fade at once; and that same-target and newer -requests, disabling and detach take over or drop the pending report. +release; that a resize lands the fade at once; that same-target and newer +requests, disabling and detach take over or drop the pending report; and that +touches during an opening or closing fade land on the host, not on the menu, +page or dim under the snapshot. Recorded evidence so far: on the iPhone 17 simulator (iOS 26) in the consumer app, tap open/close timing, fling overshoot (about 2 points), smooth reversal, the corner ramp, the reduced-motion cross-fade, the light/dark palettes and a diff --git a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift index e1ee70b17..0d7b2d80a 100644 --- a/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift +++ b/native-views/react-native-bottom-tabs/ios/RCTBottomTabsDrawerContainerView.swift @@ -215,6 +215,16 @@ final class RCTBottomTabsDrawerContainerView: UIView, UIGestureRecognizerDelegat return true } + // While a cross-fade runs, the views under the snapshot already show the + // final state, so a touch would reach a control that is not where it + // appears. The host takes those touches itself (the snapshot cannot: its + // alpha is already 0 for hit-testing once the fade starts). The pan is on + // the host, so a drag still takes over the fade. + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + let hit = super.hitTest(point, with: event) + return hit != nil && fadeSnapshot != nil ? self : hit + } + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard enabled else { return false } let start = touch.location(in: self) diff --git a/native-views/react-native-bottom-tabs/ios/tests/BottomTabsDrawerReduceMotionTests.swift b/native-views/react-native-bottom-tabs/ios/tests/BottomTabsDrawerReduceMotionTests.swift index e2a6f5361..8a5182148 100644 --- a/native-views/react-native-bottom-tabs/ios/tests/BottomTabsDrawerReduceMotionTests.swift +++ b/native-views/react-native-bottom-tabs/ios/tests/BottomTabsDrawerReduceMotionTests.swift @@ -97,6 +97,30 @@ final class BottomTabsDrawerReduceMotionTests: XCTestCase { XCTAssertEqual(fixture.drawer.subviews.count, 2) } + func testTouchesLandOnTheHostUntilTheFadeEnds() throws { + // Closing: the menu still shows, over a page already back in place. + let closing = Fixture(open: true) + defer { closing.close() } + let inMenu = CGPoint(x: closing.menuWidth / 2, y: 100) + XCTAssertTrue(closing.drawer.accessibilityPerformEscape()) + try closing.requireFade() + XCTAssertTrue(closing.hit(inMenu) === closing.drawer, "not the page under the shown menu") + XCTAssertTrue(closing.waitUntil { !closing.isFading }) + XCTAssertTrue(closing.hit(inMenu) === closing.page) + + // Opening: the page still shows, over a menu and dim already open. + let opening = Fixture(open: false) + defer { opening.close() } + let onDim = CGPoint(x: opening.menuWidth + 20, y: 100) + opening.drawer.open = true + try opening.requireFade() + XCTAssertTrue(opening.hit(inMenu) === opening.drawer, "not the menu under the shown page") + XCTAssertTrue(opening.hit(onDim) === opening.drawer, "not the dim, which would close") + XCTAssertTrue(opening.waitUntil { !opening.isFading }) + XCTAssertTrue(opening.hit(inMenu) === opening.menu) + XCTAssertTrue(opening.hit(onDim) is UIButton) + } + func testDisablingOrDetachingDropsThePendingClose() throws { let disabled = Fixture(open: true) defer { disabled.close() } @@ -127,6 +151,8 @@ final class BottomTabsDrawerReduceMotionTests: XCTestCase { private final class Fixture { let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) let drawer = RCTBottomTabsDrawerContainerView(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) + let menu = UIView() + let page = UIView() private(set) var events: [Bool] = [] private(set) var fadingAtEvent: [Bool] = [] private let recognizer = FakePan(target: nil, action: nil) @@ -135,8 +161,8 @@ private final class Fixture { init(open: Bool) { drawer.isReduceMotionEnabled = { true } drawer.makeFadeSnapshot = { _ in UIView() } - drawer.insertChild(UIView(), atIndex: 0) - drawer.insertChild(UIView(), atIndex: 1) + drawer.insertChild(menu, atIndex: 0) + drawer.insertChild(page, atIndex: 1) drawer.swipeEnabled = true drawer.enabled = true // Outside a window, the drawer lands on a target without animating. @@ -161,6 +187,9 @@ private final class Fixture { file: file, line: line) } + /// The view UIKit would deliver a touch at `point` to. + func hit(_ point: CGPoint) -> UIView? { drawer.hitTest(point, with: nil) } + /// Delivers one recognizer callback, as UIKit does for the drawer's pan. func pan(_ state: UIGestureRecognizer.State, dx: CGFloat = 0) { recognizer.fakeState = state