ReaderZoom.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderZoom.kt
1package eu.friedcutlet.yokan.ui.screens.reader23import androidx.compose.runtime.getValue4import androidx.compose.runtime.setValue5import androidx.compose.animation.core.Animatable6import androidx.compose.animation.core.CubicBezierEasing7import androidx.compose.animation.core.VectorConverter8import androidx.compose.animation.core.animate9import androidx.compose.animation.core.tween10import androidx.compose.animation.core.exponentialDecay11import androidx.compose.foundation.gestures.awaitEachGesture12import androidx.compose.foundation.gestures.awaitFirstDown13import androidx.compose.foundation.gestures.calculateCentroid14import androidx.compose.foundation.gestures.calculatePan15import androidx.compose.foundation.gestures.calculateZoom16import androidx.compose.runtime.mutableFloatStateOf17import androidx.compose.runtime.mutableStateOf18import androidx.compose.ui.Modifier19import androidx.compose.ui.geometry.Offset20import androidx.compose.ui.input.pointer.PointerEventPass21import androidx.compose.ui.input.pointer.PointerEventType22import androidx.compose.ui.input.pointer.isSecondaryPressed23import androidx.compose.ui.input.pointer.pointerInput24import androidx.compose.ui.input.pointer.util.VelocityTracker25import androidx.compose.ui.unit.IntSize26import androidx.compose.ui.unit.Velocity27import kotlinx.coroutines.coroutineScope28import kotlinx.coroutines.Job29import kotlinx.coroutines.launch3031internal class ReaderZoomState {32 var scale by mutableFloatStateOf(1f)33 private set34 var offset by mutableStateOf(Offset.Zero)35 private set36 var lastPointerPosition by mutableStateOf(Offset.Zero)37 internal set3839 private var viewportSize by mutableStateOf(IntSize.Zero)4041 fun updateViewport(size: IntSize) {42 viewportSize = size43 offset = constrainZoomOffset(offset, scale, viewportSize)44 }4546 fun applyInitialTransform(transform: ReaderInitialTransform) {47 scale = transform.scale.coerceIn(MIN_ZOOM, MAX_ZOOM)48 offset = constrainZoomOffset(transform.offset, scale, viewportSize)49 }5051 fun transform(centroid: Offset, pan: Offset, zoomChange: Float) {52 val oldScale = scale53 val newScale = (oldScale * zoomChange).coerceIn(MIN_ZOOM, MAX_ZOOM)54 val center = viewportSize.centerOffset()55 val ratio = newScale / oldScale56 val transformed = offset * ratio + pan + (centroid - center) * (1f - ratio)57 scale = newScale58 offset = if (newScale == MIN_ZOOM) {59 Offset.Zero60 } else {61 constrainZoomOffset(transformed, newScale, viewportSize)62 }63 }6465 suspend fun toggleZoom(tapPosition: Offset, durationMillis: Int) {66 val targetScale = if (scale > MIN_ZOOM + 0.01f) MIN_ZOOM else DOUBLE_TAP_ZOOM67 val targetOffset = if (targetScale == MIN_ZOOM) {68 Offset.Zero69 } else {70 doubleTapZoomOffset(tapPosition, targetScale, viewportSize)71 }72 val startScale = scale73 val startOffset = offset74 animate(75 initialValue = 0f,76 targetValue = 1f,77 animationSpec = tween(durationMillis, easing = ReaderZoomEasing),78 ) { progress, _ ->79 scale = startScale + (targetScale - startScale) * progress80 offset = Offset(81 x = startOffset.x + (targetOffset.x - startOffset.x) * progress,82 y = startOffset.y + (targetOffset.y - startOffset.y) * progress,83 )84 }85 }8687 suspend fun fling(velocity: Velocity) {88 if (scale <= MIN_ZOOM) return89 val animation = Animatable(offset, Offset.VectorConverter)90 animation.animateDecay(91 initialVelocity = Offset(velocity.x, velocity.y),92 animationSpec = exponentialDecay(),93 ) {94 val constrained = constrainZoomOffset(value, scale, viewportSize)95 offset = constrained96 }97 }98}99100internal fun Modifier.readerZoomGestures(state: ReaderZoomState): Modifier = pointerInput(state) {101 coroutineScope {102 var flingJob: Job? = null103 awaitEachGesture {104 flingJob?.cancel()105 val velocityTracker = VelocityTracker()106 var handled = false107 val firstDown = awaitFirstDown(requireUnconsumed = false)108 state.lastPointerPosition = firstDown.position109 do {110 val event = awaitPointerEvent(PointerEventPass.Main)111 event.changes.firstOrNull { it.pressed && !it.previousPressed }?.let {112 state.lastPointerPosition = it.position113 }114 val pressedCount = event.changes.count { it.pressed }115 val zoomChange = event.calculateZoom()116 if (pressedCount > 0 && (pressedCount > 1 || state.scale > MIN_ZOOM)) {117 val centroid = event.calculateCentroid(useCurrent = true)118 velocityTracker.addPosition(event.changes.first().uptimeMillis, centroid)119 state.transform(120 centroid = centroid,121 pan = event.calculatePan(),122 zoomChange = zoomChange,123 )124 handled = true125 event.changes.forEach { it.consume() }126 }127 } while (event.changes.any { it.pressed })128 if (handled && state.scale > MIN_ZOOM) {129 val velocity = velocityTracker.calculateVelocity()130 flingJob = launch { state.fling(velocity) }131 }132 }133 }134}135136137internal fun Modifier.readerSecondaryClickZoom(138 state: ReaderZoomState,139 durationMillis: Int,140): Modifier = pointerInput(state, durationMillis) {141 coroutineScope {142 val animationScope = this143 var animationJob: Job? = null144 awaitPointerEventScope {145 while (true) {146 val event = awaitPointerEvent(PointerEventPass.Main)147 if (event.type == PointerEventType.Press && event.buttons.isSecondaryPressed) {148 val position = event.changes.firstOrNull()?.position ?: continue149 state.lastPointerPosition = position150 event.changes.forEach { it.consume() }151 animationJob?.cancel()152 animationJob = animationScope.launch {153 state.toggleZoom(position, durationMillis)154 }155 }156 }157 }158 }159}160internal fun doubleTapZoomOffset(161 tapPosition: Offset,162 targetScale: Float,163 viewportSize: IntSize,164): Offset {165 val center = viewportSize.centerOffset()166 return constrainZoomOffset(167 offset = (center - tapPosition) * (targetScale - 1f),168 scale = targetScale,169 viewportSize = viewportSize,170 )171}172173internal fun constrainZoomOffset(offset: Offset, scale: Float, viewportSize: IntSize): Offset {174 if (scale <= MIN_ZOOM || viewportSize.width <= 0 || viewportSize.height <= 0) return Offset.Zero175 val maxX = viewportSize.width * (scale - 1f) / 2f176 val maxY = viewportSize.height * (scale - 1f) / 2f177 return Offset(offset.x.coerceIn(-maxX, maxX), offset.y.coerceIn(-maxY, maxY))178}179180private fun IntSize.centerOffset(): Offset = Offset(width / 2f, height / 2f)181182internal const val MIN_ZOOM = 1f183private const val DOUBLE_TAP_ZOOM = 2f184internal const val MAX_ZOOM = 8f185private val ReaderZoomEasing = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1f)186