Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,7 @@ class BottomSheetHostView(context: Context) : ReactViewGroup(context), NestedScr
scrim.clearScrimProgress()
state.suppressScrimForClosingTarget = false
state.scrimPinnedFull = false
state.scrimOpacityFloor = 0f
for (i in 0 until clipContainer.childCount) {
card.resetContentTransform(clipContainer.getChildAt(i))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ internal class Detents(
// Entries without a value are dropped up front, so the specs and the scrim
// opacities stay aligned by index.
val entries = raw.filter { it["value"] is Number }
scrim.scrimOpacities = entries.map { (it["scrimOpacity"] as? Number)?.toFloat() ?: 1f }
val newScrimOpacities = entries.map { (it["scrimOpacity"] as? Number)?.toFloat() ?: 1f }
state.rawDetentSpecs = entries.map { dict ->
val value = (dict["value"] as Number).toDouble()
val kind =
Expand Down Expand Up @@ -107,7 +107,8 @@ internal class Detents(
contentRegion.isContentRegionChangePending = true
}
contentRegion.recomputeNativeGeometry()
refreshDetentsFromLayout()
scrim.scrimOpacities = newScrimOpacities
refreshDetentsFromLayout(previousScrimOpacities)
// The re-resolved detents can change the card's shape at its current position.
contentRegion.recomputeNativeGeometry()
if (scrim.scrimOpacities != previousScrimOpacities) scrim.updateScrim()
Expand Down Expand Up @@ -221,12 +222,12 @@ internal class Detents(
state.rawDetentSpecs[index].insets.bottom
}

fun refreshDetentsFromLayout() {
resolveDetentsFromLayout()
fun refreshDetentsFromLayout(previousScrimOpacities: List<Float> = scrim.scrimOpacities) {
resolveDetentsFromLayout(previousScrimOpacities)
replayPendingIndexIfResolved()
}

private fun resolveDetentsFromLayout() {
private fun resolveDetentsFromLayout(previousScrimOpacities: List<Float>) {
if (!state.isPanning) {
state.activeDragRange = null
state.activeDragDetentSpecs = null
Expand Down Expand Up @@ -257,13 +258,22 @@ internal class Detents(
val previousMaxHeight =
if (state.lastAppliedMaxDetentHeight.isFinite()) state.lastAppliedMaxDetentHeight
else state.height.toFloat()
val previousVisibleHeight = previousMaxHeight - state.sheetContainer.translationY
// Whether the scrim is currently fully opaque, i.e. the sheet is settled at
// or above the first non-zero detent. If so, a detent resize must not dip
// the scrim while the sheet re-anchors to the new geometry.
val wasScrimFull =
state.modal &&
state.hasLaidOut &&
!state.isPanning &&
state.modal &&
state.firstOpenDetentPosition > 0f &&
state.currentSheetHeight() + 0.5f >= state.firstOpenDetentPosition
previousVisibleHeight + 0.5f >= state.firstOpenDetentPosition
val previousScrimOpacity =
if (state.hasLaidOut && !state.isPanning && state.modal && !state.scrimPinnedFull) {
scrim.scrimOpacityAt(previousVisibleHeight, previousScrimOpacities)
} else {
0f
}
state.detentSpecs = resolvedDetents
if (state.width > 0 && state.height > 0 && state.detentSpecs.isNotEmpty()) {
host.layoutSheetContainer(state.width, state.height)
Expand Down Expand Up @@ -291,6 +301,9 @@ internal class Detents(
state.sheetContainer.translationY =
(newMaxHeight - visibleHeight).coerceIn(0f, newMaxHeight)
state.scrimPinnedFull = state.scrimPinnedFull || wasScrimFull
if (!state.scrimPinnedFull) {
state.scrimOpacityFloor = maxOf(state.scrimOpacityFloor, previousScrimOpacity)
}
snapping.emitPosition()
snapping.snapToIndex(
state.targetIndex,
Expand All @@ -305,10 +318,14 @@ internal class Detents(
val shouldAnimateHeight = shouldAnimateContentHeight(state.targetIndex)
if (kotlin.math.abs(targetHeight - currentVisibleHeight) <= 0.5f) {
// No meaningful change.
state.scrimPinnedFull = false
state.scrimOpacityFloor = 0f
closeRequestPresentationTracker.onTransitionSettled()
state.sheetContainer.translationY = targetTy
snapping.emitPosition()
} else if (!shouldAnimateHeight) {
state.scrimPinnedFull = false
state.scrimOpacityFloor = 0f
closeRequestPresentationTracker.onTransitionSettled()
state.sheetContainer.translationY = targetTy
snapping.emitPosition()
Expand All @@ -320,6 +337,9 @@ internal class Detents(
state.sheetContainer.translationY =
(newMaxHeight - currentVisibleHeight).coerceIn(0f, newMaxHeight)
state.scrimPinnedFull = state.scrimPinnedFull || wasScrimFull
if (!state.scrimPinnedFull) {
state.scrimOpacityFloor = maxOf(state.scrimOpacityFloor, previousScrimOpacity)
}
snapping.emitPosition()
snapping.snapToIndex(
state.targetIndex,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ internal class Gestures(
// The user takes control: drop any index retained from props.
state.pendingIndex = null
state.scrimPinnedFull = false
state.scrimOpacityFloor = 0f
state.panStartingIndex = state.targetIndex
val dragDetentSpecs = state.detentSpecs.toList()
state.activeDragDetentSpecs = dragDetentSpecs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ internal class Scrim(private val state: SheetState) {
return
}

scrimProgress = scrimOpacityAt(position)
val targetOpacity =
state.detentSpecs.getOrNull(state.targetIndex)?.let { scrimOpacityAt(it.position) } ?: 0f
scrimProgress = maxOf(scrimOpacityAt(position), minOf(state.scrimOpacityFloor, targetOpacity))
state.hostView.invalidate()
}

Expand All @@ -71,11 +73,11 @@ internal class Scrim(private val state: SheetState) {
* Interpolates the scrim opacity for a sheet height by bracketing it between adjacent detent
* heights and lerping each detent index's configured value.
*/
private fun scrimOpacityAt(position: Float): Float =
fun scrimOpacityAt(position: Float, opacities: List<Float> = scrimOpacities): Float =
state.interpolateAtPosition(
position,
state.detentSpecs.indices.map {
(scrimOpacities.getOrNull(it) ?: 1f).coerceIn(0f, 1f)
(opacities.getOrNull(it) ?: 1f).coerceIn(0f, 1f)
},
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ internal class ScrollCoordination(private val state: SheetState, private val sna
// The user takes control: drop any index retained from props.
state.pendingIndex = null
state.scrimPinnedFull = false
state.scrimOpacityFloor = 0f
state.panStartingIndex = state.targetIndex
val dragDetentSpecs = state.detentSpecs.toList()
state.activeDragDetentSpecs = dragDetentSpecs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ internal class SheetState(val hostView: ViewGroup, val sheetContainer: BottomShe
var initialTouchX = 0f
var suppressScrimForClosingTarget = false
var scrimPinnedFull = false
var scrimOpacityFloor = 0f

// The height the container geometry and translations are currently anchored
// to. It can change after a layout (rotation), and translations computed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ internal class Snapping(
}
if (!preserveScrimPin) {
state.scrimPinnedFull = false
state.scrimOpacityFloor = 0f
}

val targetTy = translationY(index)
Expand Down Expand Up @@ -188,6 +189,7 @@ internal class Snapping(
state.activeAnimationEmitsSettle = false
state.suppressScrimForClosingTarget = false
state.scrimPinnedFull = false
state.scrimOpacityFloor = 0f
if (state.closedIndex == index) {
state.sheetContainer.translationY = translationY(index)
scrim.hideScrim()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package com.swmansion.reactnativebottomsheet

import android.app.Activity
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests
Expand Down Expand Up @@ -120,6 +124,150 @@ class BottomSheetViewScrimDismissTest {
}
}

@Test
fun `growing the open detent mid-settle does not dip the scrim opacity`() {
val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup()
val activity = controller.get()
val listener = RecordingBottomSheetListener()
val host = BottomSheetHostView(activity)
try {
host.animateIn = false
host.modal = true
host.setScrimColor(Color.BLACK)
host.setDetents(
listOf(
mapOf("value" to 0.0, "scrimOpacity" to 0.0),
mapOf("value" to 300.0, "scrimOpacity" to 1.0),
),
)
host.setIndex(1)
val content = FrameLayout(activity)
host.addSheetChild(content, 0)
activity.setContentView(host, ViewGroup.LayoutParams(1080, 1920))
content.measure(
View.MeasureSpec.makeMeasureSpec(1080, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(1920, View.MeasureSpec.EXACTLY),
)
layoutView(host)
host.listener = listener

// Drag gently partway down and hold briefly before releasing so velocity is ~0 and the
// sheet snaps back to the open detent (index 1) rather than flicking closed.
val density = host.resources.displayMetrics.density
val downTime = nextTouchDownTime
nextTouchDownTime += 700L
dragHost(host, downTime, 90f * density to 240L, 0f to 300L)
assertEquals(listOf(1), listener.indexChanges)

val beforeAlpha = readScrimAlpha(host)
assertTrue(
"Expected scrim to remain visible after short drag, got $beforeAlpha",
beforeAlpha > 100,
)

// Grow the open detent while the snap-back spring is still active.
val grownDetents =
listOf(
mapOf("value" to 0.0, "scrimOpacity" to 0.0),
mapOf("value" to 900.0, "scrimOpacity" to 1.0),
)
host.setDetents(grownDetents)
val afterAlpha = readScrimAlpha(host)
assertTrue(
"Expected scrim alpha ($afterAlpha) not to dip below $beforeAlpha after detent growth",
afterAlpha >= beforeAlpha,
)

// Switching to the closed detent clears the floor; trigger a synchronous scrim recompute
// without relying on Robolectric's Choreographer advancing the closing spring.
host.setIndex(0)
host.setDetents(grownDetents)
val closingAlpha = readScrimAlpha(host)
assertTrue(
"Expected closing to clear the floor ($closingAlpha < $beforeAlpha)",
closingAlpha < beforeAlpha,
)
} finally {
host.destroy()
shadowOf(Looper.getMainLooper()).idle()
controller.close()
}
}

@Test
fun `shrinking the host height while settled at an open detent keeps the scrim pinned`() {
val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup()
val activity = controller.get()
val host = BottomSheetHostView(activity)
try {
host.animateIn = false
host.modal = true
host.setScrimColor(Color.BLACK)
host.setDetents(
listOf(
mapOf("value" to 0.0, "kind" to "points", "scrimOpacity" to 0.0),
mapOf("value" to 0.5, "kind" to "percentage", "scrimOpacity" to 0.0),
mapOf("value" to 1.0, "kind" to "percentage", "scrimOpacity" to 1.0),
),
)
host.setIndex(1)
activity.setContentView(host, ViewGroup.LayoutParams(1080, 1920))
layoutView(host, height = 1920)

// Shrink the host so newHeight - oldTranslationY falls below the old open detent;
// using previousMaxHeight keeps the sheet recognized as open and pins the scrim.
layoutView(host, height = 1000)

assertEquals(255, readScrimAlpha(host))
} finally {
host.destroy()
shadowOf(Looper.getMainLooper()).idle()
controller.close()
}
}

private fun readScrimAlpha(host: BottomSheetHostView): Int {
val canvas = RecordingScrimCanvas()
host.draw(canvas)
return canvas.lastAlpha
}

private fun dragHost(
host: BottomSheetHostView,
downTime: Long,
vararg segments: Pair<Float, Long>,
) {
val x = 540f
var y = 1920f - 100f * host.resources.displayMetrics.density
var time = downTime
dispatchTouch(host, downTime, time, MotionEvent.ACTION_DOWN, x, y)
for ((distance, duration) in segments) {
val steps = (duration / 16L).toInt()
repeat(steps) {
y += distance / steps
time += 16L
dispatchTouch(host, downTime, time, MotionEvent.ACTION_MOVE, x, y)
}
}
dispatchTouch(host, downTime, time + 16L, MotionEvent.ACTION_UP, x, y)
}

private fun dispatchTouch(
view: View,
downTime: Long,
eventTime: Long,
action: Int,
x: Float,
y: Float,
) {
val event = MotionEvent.obtain(downTime, eventTime, action, x, y, 0)
try {
view.dispatchTouchEvent(event)
} finally {
event.recycle()
}
}

/**
* Grows the open detent, which re-anchors the sheet and pins the scrim until the spring ends. The
* sheet is still below the detent's position, where the scrim is invisible unless it is pinned.
Expand Down Expand Up @@ -192,9 +340,8 @@ class BottomSheetViewScrimDismissTest {
up.recycle()
}

private fun layoutView(view: View) {
private fun layoutView(view: View, height: Int = 1920) {
val width = 1080
val height = 1920
view.measure(
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY),
Expand All @@ -204,6 +351,14 @@ class BottomSheetViewScrimDismissTest {
}
}

private class RecordingScrimCanvas : Canvas() {
var lastAlpha = 0

override fun drawRect(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) {
lastAlpha = paint.alpha
}
}

private class RecordingBottomSheetListener : BottomSheetViewListener {
val indexChanges = mutableListOf<Int>()

Expand Down
12 changes: 9 additions & 3 deletions ios/HostingView/BottomSheetHostingView+Detents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -221,15 +221,19 @@ extension BottomSheetHostingView {
// was computed against — not the freshly resolved one.
let previousMaxHeight =
lastAppliedMaxDetentHeight.isFinite ? lastAppliedMaxDetentHeight : sheetContainerHeight
let previousVisibleHeight = previousMaxHeight - currentTranslationY
// Whether the scrim is currently fully opaque, i.e. the sheet is settled at
// or above the first non-zero detent. If so, a detent resize must not dip
// the scrim while the sheet re-anchors to the new geometry.
let wasScrimFull = hasLaidOut
&& !isPanning
&& modal
&& firstOpenDetentPosition > 0
&& currentSheetHeight + 0.5 >= firstOpenDetentPosition
&& previousVisibleHeight + 0.5 >= firstOpenDetentPosition
scrimPinnedFull = scrimPinnedFull || wasScrimFull
if hasLaidOut, !isPanning, modal, !scrimPinnedFull {
scrimOpacityFloor = max(scrimOpacityFloor, scrimOpacity(forPosition: previousVisibleHeight))
}
detentSpecs = resolvedDetents

guard bounds.width > 0, bounds.height > 0, !detentSpecs.isEmpty else {
Expand Down Expand Up @@ -263,13 +267,15 @@ extension BottomSheetHostingView {
let shouldAnimateHeight = shouldAnimateContentHeight(at: targetIndex)
if abs(targetHeight - currentVisibleHeight) <= 0.5 {
// No meaningful change.
scrimPinnedFull = false
scrimOpacityFloor = 0
setSheetTranslation(targetTy)
emitPosition()
scrimPinnedFull = false
} else if !shouldAnimateHeight {
scrimPinnedFull = false
scrimOpacityFloor = 0
setSheetTranslation(targetTy)
emitPosition()
scrimPinnedFull = false
} else {
// The content detent changed (grew or shrank): re-anchor at the
// current visible height, then animate to the new target. The surface
Expand Down
Loading