InteractiveBackGesture.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/InteractiveBackGesture.kt
1package eu.friedcutlet.yokan.ui.navigation23import androidx.compose.animation.core.Spring4import androidx.compose.animation.core.animate5import androidx.compose.animation.core.spring6import androidx.compose.foundation.gestures.awaitEachGesture7import androidx.compose.foundation.gestures.awaitFirstDown8import androidx.compose.runtime.getValue9import androidx.compose.runtime.mutableFloatStateOf10import androidx.compose.runtime.mutableStateOf11import androidx.compose.runtime.setValue12import androidx.compose.ui.Modifier13import androidx.compose.ui.input.pointer.PointerEventPass14import androidx.compose.ui.input.pointer.pointerInput15import androidx.compose.ui.input.pointer.util.VelocityTracker16import kotlinx.coroutines.CoroutineScope17import kotlinx.coroutines.Job18import kotlinx.coroutines.launch19import kotlin.math.abs2021/** Gesture state belongs to one entry. Its offset survives until that entry finishes leaving. */22internal class InteractiveBackGesture(private val scope: CoroutineScope) {23 var active by mutableStateOf(false)24 private set25 var progress by mutableFloatStateOf(0f)26 private set27 private var settling: Job? = null28 private var disposed = false2930 fun begin(): Boolean {31 if (disposed || active || settling?.isActive == true) return false32 active = true33 return true34 }3536 fun drag(pixels: Float, width: Float) {37 progress = (progress + pixels / width).coerceIn(0f, 1f)38 }3940 fun finish(velocity: Float, cancelled: Boolean, onComplete: () -> Unit) {41 if (disposed || !active || settling?.isActive == true) return42 val complete = !cancelled && shouldCompleteBack(progress, velocity)43 settling = scope.launch {44 animate(45 initialValue = progress,46 targetValue = if (complete) 1f else 0f,47 initialVelocity = if (cancelled) 0f else velocity,48 animationSpec = spring(dampingRatio = Spring.DampingRatioNoBouncy, stiffness = 700f, visibilityThreshold = 0.001f),49 ) { value, _ -> progress = value.coerceIn(0f, 1f) }50 if (complete) {51 // Do not reset to zero here: the outgoing entry is still composed for this frame.52 onComplete()53 } else {54 active = false55 }56 }57 }5859 fun dispose() { disposed = true; settling?.cancel() }60}6162/** Velocity is in screen widths/second, so the same gesture works on phones and tablets. */63internal fun shouldCompleteBack(progress: Float, velocity: Float): Boolean =64 if (abs(velocity) >= 1f) velocity > 0f else progress >= 0.5f6566internal fun Modifier.interactiveBackGesture(67 gesture: InteractiveBackGesture,68 edgeWidth: Float,69 canStart: () -> Boolean,70 onComplete: () -> Unit,71): Modifier = pointerInput(gesture, edgeWidth) {72 awaitEachGesture {73 val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)74 // Check the original DOWN, not the position after touch slop. Leave other swipes alone.75 if (down.position.x > edgeWidth || !canStart() || !gesture.begin()) return@awaitEachGesture76 val width = size.width.toFloat().coerceAtLeast(1f)77 val tracker = VelocityTracker().apply { addPosition(down.uptimeMillis, down.position) }78 var dragging = false79 var cancelled = true80 var totalX = 0f81 var totalY = 0f82 try {83 while (true) {84 val event = awaitPointerEvent(PointerEventPass.Initial)85 val change = event.changes.firstOrNull { it.id == down.id } ?: break86 tracker.addPosition(change.uptimeMillis, change.position)87 if (change.isConsumed || event.changes.count { it.pressed } > 1) break88 if (!change.pressed) {89 cancelled = !dragging90 break91 }92 val delta = change.position - change.previousPosition93 totalX += delta.x94 totalY += delta.y95 if (!dragging) {96 if (abs(totalY) > viewConfiguration.touchSlop || totalX < -viewConfiguration.touchSlop) break97 if (totalX <= viewConfiguration.touchSlop) continue98 dragging = true99 gesture.drag(totalX - viewConfiguration.touchSlop, width)100 } else {101 gesture.drag(delta.x, width)102 }103 change.consume()104 }105 } finally {106 gesture.finish(tracker.calculateVelocity().x / width, cancelled, onComplete)107 }108 }109}110