Last active
December 16, 2022 01:15
-
-
Save PhilipDukhov/0b34fac47ae04242868b8bc3afeb5dfe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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