Skip to content

Instantly share code, notes, and snippets.

@PhilipDukhov
Created October 15, 2021 11:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhilipDukhov/293eee8e9a21cdd51d5a19fa9c524ba3 to your computer and use it in GitHub Desktop.
Save PhilipDukhov/293eee8e9a21cdd51d5a19fa9c524ba3 to your computer and use it in GitHub Desktop.
fun Modifier.swipeableTopBottom(onTop: () -> Unit, onBottom: () -> Unit): Modifier = composed {
var width by rememberSaveable { mutableStateOf(0f) }
val swipeableState = rememberSwipeableState(
SwipeDirection.Initial,
animationSpec = snap()
)
val anchorWidth = remember(width) {
if (width == 0f) {
1f
} else {
width
}
}
val scope = rememberCoroutineScope()
if (swipeableState.isAnimationRunning) {
DisposableEffect(Unit) {
onDispose {
when (swipeableState.currentValue) {
SwipeDirection.Top -> {
onTop()
}
SwipeDirection.Bottom -> {
onBottom()
}
else -> {
return@onDispose
}
}
scope.launch {
swipeableState.snapTo(SwipeDirection.Initial)
}
}
}
}
return@composed Modifier
.onSizeChanged { width = it.width.toFloat() }
.swipeable(
state = swipeableState,
anchors = mapOf(
0f to SwipeDirection.Top,
anchorWidth / 2 to SwipeDirection.Initial,
anchorWidth to SwipeDirection.Bottom,
),
thresholds = { _, _ -> FractionalThreshold(0.3f) },
orientation = Orientation.Vertical
)
}
private enum class SwipeDirection(val raw: Int) {
Top(0),
Initial(1),
Bottom(2),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment