Skip to content

Instantly share code, notes, and snippets.

@PhilipDukhov
Last active December 16, 2022 01:15
Show Gist options
  • Save PhilipDukhov/0b34fac47ae04242868b8bc3afeb5dfe to your computer and use it in GitHub Desktop.
Save PhilipDukhov/0b34fac47ae04242868b8bc3afeb5dfe to your computer and use it in GitHub Desktop.
fun Modifier.swipeableLeftRight(onLeft: () -> Unit, onRight: () -> 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.Left -> {
onLeft()
}
SwipeDirection.Right -> {
onRight()
}
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.Left,
anchorWidth / 2 to SwipeDirection.Initial,
anchorWidth to SwipeDirection.Right,
),
thresholds = { _, _ -> FractionalThreshold(0.3f) },
orientation = Orientation.Horizontal
)
}
private enum class SwipeDirection(val raw: Int) {
Left(0),
Initial(1),
Right(2),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment