ui: share Photos' pinch/double-tap zoom as zoomGestures (#918)
- Commit
fd5477e8dd5a6c99c334465eb51659d1f2ec3e23- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-14 14:07 UTC (22 days ago)
- Parents
8913ff4
The appstore needs a full-screen screenshot viewer (#918) with the same pinch, pan and double-tap zoom the Photos viewer already has. That code lived privately in photos/ (PhotoZoomGestures.kt plus a ZoomState data class in PhotoDetailView.kt), so the second user would have meant a copy. It moves into :library:ui instead, which is where shared Compose chrome lives; :library:ui cannot see :library:image, so what moves is the gesture modifier and its state, not an image component. What changed: - library/ui ZoomState.kt: the zoom/pan value (scale + offset applied as a graphicsLayer around the content centre) and its geometry as pure functions: transformed() for a pinch/pan step, toggledAt() for double tap, maxZoomOffset()/clampZoomOffset() for the pan bounds. - library/ui ZoomGestures.kt: zoomGestures(zoom, containerSize, onZoomChange, onTap, acceptsTap), the old photoZoomGestures with the Photos-specific names generalised (onToggleMetadata -> onTap, isChromeTap -> acceptsTap). Every callback is read through rememberUpdatedState because pointerInput(Unit) never re-keys. - photos: PhotoZoomGestures.kt deleted; PhotoDetailView, VaultViewerScreen, PhotoPage, PhotoDetailSection and two tests now use the library types. Public surface is otherwise unchanged. Behaviour kept from Photos: scale 1..5, double tap toggles fit <-> 2.5x, pan clamped to the container, and pager-friendly consumption (at fit a one-finger drag is left to the HorizontalPager; zoomed, drags pan until they hit the left/right edge and then go to the pager; pinches are always consumed). Behaviour fixed, for both apps: taps now work on a zoomed image. The old loop consumed every pointer event while zoomed, including the up of a stationary tap, which cancelled detectTapGestures; so once zoomed in, Photos could not toggle its chrome with a tap or double-tap back to fit (only a pinch out worked). The loop now moves and consumes nothing until the touch passes the touch slop or a second finger pinches, which is also what keeps the pager from stealing a zoomed drag (the pager's own slop is horizontal-only, so ours is always crossed first). Behaviour improved, for both apps: pinches now zoom around the point between the fingers and a double tap zooms into the tapped point. Before, both always zoomed around the centre, so magnifying a corner of a photo meant zooming then dragging the detail back into view. The transform semantics are unchanged (same scale/offset graphicsLayer), so Photos' face boxes and OCR text layer, which reuse the same layer, stay aligned. Tests: ZoomStateTest covers identity, centroid anchoring (the content point under the fingers stays put), scale and pan clamps (an at-fit offset is exactly Offset.Zero, not -0f), and the double-tap target and edge clamp. ZoomGesturesTest drives real pointer input under Robolectric: double tap in and back out, pinch out, a one-finger swipe at fit leaving zoom alone, a tap on a zoomed image reaching onTap, a zoomed drag panning, and acceptsTap=false suppressing both tap kinds. Verified in the toolchain container: :library:ui unit tests and lint pass, :photos compiles and its PhotosSlice3 viewer tests pass. Not caused by this change and left alone: :library:ui:detekt flags the existing IconsSliceTest as LargeClass, and :photos:lint fails on four UnrememberedMutableState errors in PhotosSlice1VaultUiTest and PhotosSlice3WallpaperTest, both already on origin/main.
Diff
library/ui/AGENTS.md
diff --git a/library/ui/AGENTS.md b/library/ui/AGENTS.mdindex 8509e5e386..5eced9c5ed 100644--- a/library/ui/AGENTS.md+++ b/library/ui/AGENTS.md@@ -78,6 +78,9 @@ - com/vayunmathur/library/ui/PopVisibility.kt - com/vayunmathur/library/ui/FreeHeightBottomSheet.kt - com/vayunmathur/library/ui/FreeHeightSheetState.kt+### Media viewer+- com/vayunmathur/library/ui/ZoomState.kt — pure zoom/pan value + anchored pinch, clamp, double-tap math+- com/vayunmathur/library/ui/ZoomGestures.kt — `zoomGestures()` pinch/pan/double-tap modifier, pager-friendly (photos viewer, appstore screenshots) ### Forms + settings - com/vayunmathur/library/ui/FormComponents.kt - com/vayunmathur/library/ui/FormSection.kt
library/ui/src/main/java/com/vayunmathur/library/ui/ZoomGestures.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/ZoomGestures.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/ZoomGestures.ktnew file mode 100644index 0000000000..7c48db2eed--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/ZoomGestures.kt@@ -0,0 +1,104 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculateCentroid+import androidx.compose.foundation.gestures.calculatePan+import androidx.compose.foundation.gestures.calculateZoom+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.runtime.Composable+import androidx.compose.runtime.State+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.isSpecified+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.unit.IntSize++/**+ * Pinch-to-zoom, pan, double-tap zoom and single tap for a full-screen media viewer.+ *+ * Put the returned modifier on the box that receives touches, and apply [zoom] to the+ * content with a `graphicsLayer` (scale around the centre, translate by the offset). The+ * state is hoisted: gestures read [zoom] as a [State], so a pinch updates the layer without+ * recomposing the content, and every change goes through [onZoomChange].+ *+ * Built to live inside a `HorizontalPager`: at fit scale a one-finger drag is left+ * unconsumed so the pager swipes; once zoomed, drags past the touch slop pan the content,+ * and a drag that runs into the left or right edge is released to the pager again so the+ * next page can be reached without zooming out first. Pinches are always consumed; taps+ * never are, so single and double taps work at any scale.+ *+ * Pinches zoom around the point between the fingers, up to [ZoomState.DEFAULT_MAX_SCALE];+ * a double tap zooms into the tapped point at [ZoomState.DEFAULT_DOUBLE_TAP_SCALE], or back+ * to fit. The geometry is [ZoomState]'s.+ *+ * @param containerSize live reader for the measured content box, used as the zoom pivot+ * and to clamp the pan.+ * @param onTap single tap (e.g. toggle viewer chrome); delayed by the double-tap timeout.+ * @param acceptsTap gates both tap kinds by position, so taps that land on an overlay drawn+ * over the content (a metadata card, say) do not also zoom or toggle the viewer.+ */+@Composable+fun zoomGestures(+ zoom: State<ZoomState>,+ containerSize: () -> IntSize,+ onZoomChange: (ZoomState) -> Unit,+ onTap: (Offset) -> Unit = {},+ acceptsTap: (Offset) -> Boolean = { true },+): Modifier {+ // pointerInput(Unit) never re-keys, so every input it reads goes through state.+ val latestSize by rememberUpdatedState(containerSize)+ val latestOnZoomChange by rememberUpdatedState(onZoomChange)+ val latestOnTap by rememberUpdatedState(onTap)+ val latestAcceptsTap by rememberUpdatedState(acceptsTap)+ return Modifier+ .pointerInput(Unit) {+ detectTapGestures(+ onTap = { offset -> if (latestAcceptsTap(offset)) latestOnTap(offset) },+ onDoubleTap = { offset ->+ if (latestAcceptsTap(offset)) {+ latestOnZoomChange(+ zoom.value.toggledAt(offset, latestSize())+ )+ }+ },+ )+ }+ .pointerInput(Unit) {+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ // Nothing moves or is consumed until the touch has travelled past the slop or a+ // second finger pinches. Consuming the up of a stationary tap would cancel+ // detectTapGestures above, so a zoomed image could never be tapped or+ // double-tapped back to fit.+ var pastSlop = false+ var slopPan = Offset.Zero+ do {+ val event = awaitPointerEvent()+ val zoomChange = event.calculateZoom()+ val pan = event.calculatePan()+ val isPinching = zoomChange != 1f+ if (!pastSlop) {+ slopPan += pan+ pastSlop = isPinching || slopPan.getDistance() > viewConfiguration.touchSlop+ }+ val current = zoom.value+ if (pastSlop && (current.isZoomed || isPinching)) {+ val size = latestSize()+ val centroid = event.calculateCentroid(useCurrent = false)+ .takeIf { it.isSpecified } ?: Offset(size.width / 2f, size.height / 2f)+ val next = current.transformed(zoomChange, pan, centroid, size)+ latestOnZoomChange(next)+ val max = maxZoomOffset(next.scale, size)+ val atEdge = (pan.x > 0f && next.offset.x >= max.x) ||+ (pan.x < 0f && next.offset.x <= -max.x)+ if (next.scale > 1f && (isPinching || !atEdge)) {+ event.changes.forEach { it.consume() }+ }+ }+ } while (event.changes.any { it.pressed })+ }+ }+}
library/ui/src/main/java/com/vayunmathur/library/ui/ZoomState.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/ZoomState.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/ZoomState.ktnew file mode 100644index 0000000000..3f6bfa6fc9--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/ZoomState.kt@@ -0,0 +1,87 @@+package com.vayunmathur.library.ui++import androidx.compose.runtime.Immutable+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.unit.IntSize++/**+ * Scale and pan of zoomable content, applied as a `graphicsLayer` around the content's+ * centre: `scaleX = scaleY = scale`, `translationX/Y = offset`.+ *+ * Pure value + math so the gesture handling in [zoomGestures] stays a thin shell and the+ * geometry can be unit-tested without a pointer. Scale never drops below 1 — content is+ * laid out to fit, and zooming out past fit only adds letterboxing — and the pan is clamped+ * so the scaled content always covers its container instead of sliding off-screen.+ */+@Immutable+data class ZoomState(val scale: Float = 1f, val offset: Offset = Offset.Zero) {++ /** True once the content is meaningfully magnified (a pinch rounding to 1 is not). */+ val isZoomed: Boolean get() = scale > ZOOMED_THRESHOLD++ /**+ * Applies one pinch/pan step. [zoomChange] multiplies the scale around [centroid] (in+ * container coordinates), so the point between the user's fingers stays under them, then+ * [pan] moves the content. The result is clamped to `1..maxScale` and to the container.+ * Returns the identity state when the scale settles back at 1.+ */+ fun transformed(+ zoomChange: Float,+ pan: Offset,+ centroid: Offset,+ containerSize: IntSize,+ maxScale: Float = DEFAULT_MAX_SCALE,+ ): ZoomState {+ val newScale = (scale * zoomChange).coerceIn(1f, maxScale)+ if (newScale <= 1f) return ZoomState()+ val anchor = centroid - containerSize.center()+ // The content point under the centroid is (anchor - offset) / scale from the centre;+ // solve for the offset that keeps it under the centroid at the new scale.+ val anchored = anchor - (anchor - offset) * (newScale / scale)+ return ZoomState(newScale, clampZoomOffset(anchored + pan, newScale, containerSize))+ }++ /**+ * The double-tap toggle: back to fit when zoomed, otherwise to [zoomedScale] centred on+ * [tap] so the tapped detail is what gets magnified.+ */+ fun toggledAt(+ tap: Offset,+ containerSize: IntSize,+ zoomedScale: Float = DEFAULT_DOUBLE_TAP_SCALE,+ ): ZoomState =+ if (scale > 1f) {+ ZoomState()+ } else {+ ZoomState().transformed(zoomedScale, Offset.Zero, tap, containerSize, zoomedScale)+ }++ companion object {+ /** Pinch ceiling: enough to read small UI text in a phone screenshot or photo. */+ const val DEFAULT_MAX_SCALE = 5f++ /** Double-tap target scale. */+ const val DEFAULT_DOUBLE_TAP_SCALE = 2.5f++ private const val ZOOMED_THRESHOLD = 1.01f+ }+}++/**+ * Largest translation, per axis, that still keeps content scaled by [scale] covering a+ * [containerSize] box (zero at fit).+ */+fun maxZoomOffset(scale: Float, containerSize: IntSize): Offset {+ val extra = (scale - 1f).coerceAtLeast(0f) / 2f+ return Offset(containerSize.width * extra, containerSize.height * extra)+}++/** [offset] clamped to `±maxZoomOffset(scale, containerSize)` on each axis. */+fun clampZoomOffset(offset: Offset, scale: Float, containerSize: IntSize): Offset {+ val max = maxZoomOffset(scale, containerSize)+ // `+ 0f` turns the -0f that clamping a negative value into [-0, 0] yields back into 0f;+ // Offset compares bit patterns, so an at-fit offset must be exactly Offset.Zero.+ return Offset(offset.x.coerceIn(-max.x, max.x) + 0f, offset.y.coerceIn(-max.y, max.y) + 0f)+}++private fun IntSize.center(): Offset = Offset(width / 2f, height / 2f)
library/ui/src/test/java/com/vayunmathur/library/ui/ZoomGesturesTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/ZoomGesturesTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/ZoomGesturesTest.ktnew file mode 100644index 0000000000..d5ccbd615b--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/ZoomGesturesTest.kt@@ -0,0 +1,122 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.test.click+import androidx.compose.ui.test.doubleClick+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithTag+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.pinch+import androidx.compose.ui.test.swipeDown+import androidx.compose.ui.test.swipeLeft+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** [zoomGestures] wired to real pointer input: taps at any scale, pinch, pan, pager pass-through. */+@RunWith(RobolectricTestRunner::class)+class ZoomGesturesTest {++ @get:Rule+ val rule = createComposeRule()++ private val zoom = mutableStateOf(ZoomState())+ private var taps = 0++ private fun setContent(acceptsTap: (Offset) -> Boolean = { true }) {+ rule.setContent {+ var size = IntSize.Zero+ Box(+ Modifier+ .size(300.dp)+ .onSizeChanged { size = it }+ .testTag("zoom")+ .then(+ zoomGestures(+ zoom = zoom,+ containerSize = { size },+ onZoomChange = { zoom.value = it },+ onTap = { taps++ },+ acceptsTap = acceptsTap,+ )+ )+ )+ }+ }++ @Test+ fun `double tap zooms in and a second one restores fit`() {+ setContent()+ rule.onNodeWithTag("zoom").performTouchInput { doubleClick(center) }+ rule.waitForIdle()+ assertEquals(ZoomState.DEFAULT_DOUBLE_TAP_SCALE, zoom.value.scale)++ rule.onNodeWithTag("zoom").performTouchInput { doubleClick(center) }+ rule.waitForIdle()+ assertEquals(ZoomState(), zoom.value)+ }++ @Test+ fun `pinch out zooms`() {+ setContent()+ rule.onNodeWithTag("zoom").performTouchInput {+ pinch(+ start0 = center - Offset(20f, 0f),+ end0 = center - Offset(120f, 0f),+ start1 = center + Offset(20f, 0f),+ end1 = center + Offset(120f, 0f),+ )+ }+ rule.waitForIdle()+ assertTrue(zoom.value.isZoomed, "scale was ${zoom.value.scale}")+ }++ @Test+ fun `one finger drag at fit scale leaves zoom alone`() {+ setContent()+ rule.onNodeWithTag("zoom").performTouchInput { swipeLeft() }+ rule.waitForIdle()+ assertEquals(ZoomState(), zoom.value)+ }++ @Test+ fun `rejected taps neither zoom nor fire onTap`() {+ setContent(acceptsTap = { false })+ rule.onNodeWithTag("zoom").performTouchInput { doubleClick(center) }+ rule.waitForIdle()+ assertEquals(ZoomState(), zoom.value)+ assertEquals(0, taps)+ }++ @Test+ fun `a tap on a zoomed image still reaches onTap`() {+ setContent()+ zoom.value = ZoomState(scale = 2f)+ rule.onNodeWithTag("zoom").performTouchInput { click(center) }+ rule.mainClock.advanceTimeBy(1_000L)+ rule.waitForIdle()+ assertEquals(1, taps)+ assertEquals(ZoomState(scale = 2f), zoom.value)+ }++ @Test+ fun `dragging a zoomed image pans it`() {+ setContent()+ zoom.value = ZoomState(scale = 2f)+ rule.onNodeWithTag("zoom").performTouchInput { swipeDown() }+ rule.waitForIdle()+ assertEquals(2f, zoom.value.scale)+ assertTrue(zoom.value.offset.y > 0f, "offset was ${zoom.value.offset}")+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/ZoomStateTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/ZoomStateTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/ZoomStateTest.ktnew file mode 100644index 0000000000..57c7ac7da7--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/ZoomStateTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.library.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.unit.IntSize+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Geometry behind [zoomGestures]: anchoring, clamping, the double-tap toggle. */+class ZoomStateTest {++ private val box = IntSize(400, 800)+ private val center = Offset(200f, 400f)++ @Test+ fun `default is identity and not zoomed`() {+ val z = ZoomState()+ assertEquals(1f, z.scale)+ assertEquals(Offset.Zero, z.offset)+ assertFalse(z.isZoomed)+ }++ @Test+ fun `pinch around the centre scales without moving`() {+ val z = ZoomState().transformed(2f, Offset.Zero, center, box)+ assertEquals(2f, z.scale)+ assertEquals(Offset.Zero, z.offset)+ assertTrue(z.isZoomed)+ }++ @Test+ fun `pinch keeps the content point under the centroid`() {+ val centroid = Offset(300f, 500f)+ val start = ZoomState(scale = 1.5f, offset = Offset(-20f, 10f))+ val z = start.transformed(2f, Offset.Zero, centroid, box)+ // Content point under the centroid, measured from the centre, before and after.+ val anchor = centroid - center+ val before = (anchor - start.offset) / start.scale+ val after = (anchor - z.offset) / z.scale+ assertEquals(3f, z.scale)+ assertEquals(before.x, after.x, 0.001f)+ assertEquals(before.y, after.y, 0.001f)+ }++ @Test+ fun `scale is clamped to fit and to the ceiling`() {+ assertEquals(ZoomState(), ZoomState(scale = 2f, offset = Offset(50f, 50f)).transformed(0.1f, Offset.Zero, center, box))+ assertEquals(+ ZoomState.DEFAULT_MAX_SCALE,+ ZoomState(scale = 4f).transformed(10f, Offset.Zero, center, box).scale,+ )+ }++ @Test+ fun `pan is clamped so content covers the container`() {+ val z = ZoomState(scale = 2f).transformed(1f, Offset(10_000f, -10_000f), center, box)+ assertEquals(Offset(200f, 400f), maxZoomOffset(2f, box))+ assertEquals(Offset(200f, -400f), z.offset)+ }++ @Test+ fun `pan at fit scale has no room`() {+ assertEquals(Offset.Zero, maxZoomOffset(1f, box))+ assertEquals(Offset.Zero, clampZoomOffset(Offset(30f, -30f), 1f, box))+ }++ @Test+ fun `double tap zooms into the tapped point and back`() {+ val tap = Offset(300f, 600f)+ val zoomed = ZoomState().toggledAt(tap, box)+ assertEquals(ZoomState.DEFAULT_DOUBLE_TAP_SCALE, zoomed.scale)+ // The tapped point stays where it was: offset = -(tap - centre) * (scale - 1).+ assertEquals(Offset(-150f, -300f), zoomed.offset)+ assertEquals(ZoomState(), zoomed.toggledAt(tap, box))+ }++ @Test+ fun `double tap near an edge stays clamped`() {+ val zoomed = ZoomState().toggledAt(Offset(0f, 0f), box, zoomedScale = 2f)+ assertEquals(Offset(200f, 400f), zoomed.offset)+ }+}
photos/AGENTS.md
diff --git a/photos/AGENTS.md b/photos/AGENTS.mdindex 3c3c21ea76..94043207ae 100644--- a/photos/AGENTS.md+++ b/photos/AGENTS.md@@ -104,7 +104,6 @@ _Install: ./install photos (dev by default)._ - com/vayunmathur/photos/ui/PhotoFilmstrip.kt - com/vayunmathur/photos/ui/PhotoViewerActions.kt - com/vayunmathur/photos/ui/PhotoViewerWideLayout.kt-- com/vayunmathur/photos/ui/PhotoZoomGestures.kt - com/vayunmathur/photos/ui/EditRoute.kt - com/vayunmathur/photos/ui/EditActivity.kt - com/vayunmathur/photos/ui/FaceBoxLayer.kt
photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.ktindex 9e75b128f5..1503c04936 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.kt@@ -24,6 +24,7 @@ import com.vayunmathur.library.ui.FadeVisibility import com.vayunmathur.library.ui.FilledTonalButton import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.ZoomState import com.vayunmathur.photos.R import com.vayunmathur.photos.data.OcrLayout import com.vayunmathur.photos.data.Photo
photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.ktindex b69c28a41e..d12dce7fca 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt@@ -20,12 +20,13 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.IntSize import androidx.core.net.toUri+import com.vayunmathur.library.ui.ZoomState import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.library.ui.zoomGestures import com.vayunmathur.photos.R import com.vayunmathur.photos.data.OcrLayout import com.vayunmathur.photos.data.Photo@@ -41,9 +42,6 @@ import kotlinx.coroutines.withContext import java.io.File import kotlin.math.absoluteValue -// Helper class to store zoom information-data class ZoomState(val scale: Float = 1f, val offset: Offset = Offset.Zero)- @Composable fun PhotoDetailView( photo: Photo,@@ -182,12 +180,12 @@ fun PhotoDetailView( modifier = Modifier.fillMaxSize() .then(- photoZoomGestures(- currentZoom = currentZoom,+ zoomGestures(+ zoom = currentZoom, containerSize = sizeReader,- onZoomUpdate = updatedOnZoomUpdate,- onToggleMetadata = updatedOnToggleMetadata,- isChromeTap = { tap -> metadataSize.height <= 0 || tap.y < (sizeReader().height - metadataSize.height).toFloat() },+ onZoomChange = updatedOnZoomUpdate,+ onTap = { updatedOnToggleMetadata() },+ acceptsTap = { tap -> metadataSize.height <= 0 || tap.y < (sizeReader().height - metadataSize.height).toFloat() }, ) ) ) {
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex 1a6a1ced35..0a67f6dc53 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -31,6 +31,7 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.ZoomState import com.vayunmathur.library.ui.isExpandedWidth import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.Route
photos/src/main/java/com/vayunmathur/photos/ui/PhotoZoomGestures.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoZoomGestures.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoZoomGestures.ktdeleted file mode 100644index 336f7b59bb..0000000000--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoZoomGestures.kt+++ /dev/null@@ -1,112 +0,0 @@-package com.vayunmathur.photos.ui--import androidx.compose.foundation.gestures.awaitEachGesture-import androidx.compose.foundation.gestures.awaitFirstDown-import androidx.compose.foundation.gestures.calculatePan-import androidx.compose.foundation.gestures.calculateZoom-import androidx.compose.foundation.gestures.detectTapGestures-import androidx.compose.runtime.Composable-import androidx.compose.runtime.State-import androidx.compose.runtime.getValue-import androidx.compose.runtime.rememberUpdatedState-import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.input.pointer.pointerInput-import androidx.compose.ui.unit.IntSize--/**- * Tap (toggle chrome) + double-tap (zoom toggle) + pinch/pan for the photo viewer.- * Reads [currentZoom] as a [State] so pinches update without recomposing; writes- * go through [onZoomUpdate]. [containerSize] is the measured image container used- * to clamp the pan offset.- *- * [isChromeTap] decides whether a tap at the given Box-relative offset toggles the- * chrome: taps landing on overlay controls (e.g. the metadata card) must not, or- * every button press would also flip the chrome for the next photo.- */-@Composable-internal fun photoZoomGestures(- currentZoom: State<ZoomState>,- /** Live reader for the measured container, used to clamp the pan offset. */- containerSize: () -> IntSize,- onZoomUpdate: (ZoomState) -> Unit,- onToggleMetadata: () -> Unit,- isChromeTap: (Offset) -> Boolean = { true },-): Modifier {- // pointerInput(Unit) never re-keys, so read the latest predicate through state.- val latestIsChromeTap by rememberUpdatedState(isChromeTap)- return Modifier- .pointerInput(Unit) {- detectTapGestures(- onTap = { offset -> if (latestIsChromeTap(offset)) onToggleMetadata() },- onDoubleTap = { offset ->- if (!latestIsChromeTap(offset)) return@detectTapGestures- val newScale =- if (currentZoom.value.scale > 1f) 1f else 2.5f- onZoomUpdate(- ZoomState(- scale = newScale,- offset = Offset.Zero- )- )- }- )- }- .pointerInput(Unit) {- awaitEachGesture {- awaitFirstDown(requireUnconsumed = false)- do {- val event = awaitPointerEvent()- val zoomChange = event.calculateZoom()- val panChange = event.calculatePan()-- val isPinching = zoomChange != 1f- val zoom = currentZoom.value- val isZoomed = zoom.scale > 1.01f-- if (isZoomed || isPinching) {- val newScale =- (zoom.scale * zoomChange).coerceIn(- 1f,- 5f- )-- if (newScale > 1f) {- val size = containerSize()- val maxX = (size.width * (newScale - 1) / 2)- val maxY = (size.height * (newScale - 1) / 2)-- val newOffset = zoom.offset + panChange-- val isAtLeftEdge =- newOffset.x >= maxX && panChange.x > 0- val isAtRightEdge =- newOffset.x <= -maxX && panChange.x < 0-- val boundedOffset =- Offset(- newOffset.x.coerceIn(-maxX, maxX),- newOffset.y.coerceIn(-maxY, maxY)- )-- onZoomUpdate(- ZoomState(- scale = newScale,- offset = boundedOffset- )- )-- if (isPinching || (!isAtLeftEdge && !isAtRightEdge)- ) {- event.changes.forEach { it.consume() }- }- } else {- onZoomUpdate(- ZoomState(scale = 1f, offset = Offset.Zero)- )- }- }- } while (event.changes.any { it.pressed })- }- }-}
photos/src/main/java/com/vayunmathur/photos/ui/VaultViewerScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/VaultViewerScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/VaultViewerScreen.ktindex 6b067595c3..f1cb773acb 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/VaultViewerScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/VaultViewerScreen.kt@@ -29,6 +29,8 @@ import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.ZoomState+import com.vayunmathur.library.ui.zoomGestures import java.io.File /**@@ -65,11 +67,11 @@ fun VaultViewerScreen( .background(Color.Black) .onGloballyPositioned { containerSize = it.size } .then(- photoZoomGestures(- currentZoom = zoomState,+ zoomGestures(+ zoom = zoomState, containerSize = { containerSize },- onZoomUpdate = { zoom = it },- onToggleMetadata = { isChromeVisible = !isChromeVisible },+ onZoomChange = { zoom = it },+ onTap = { isChromeVisible = !isChromeVisible }, ) ) ) {
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ExtrasTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ExtrasTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ExtrasTest.ktindex f317c46f2d..ed45637b3f 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ExtrasTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ExtrasTest.kt@@ -8,6 +8,7 @@ import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.unit.IntSize import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.ZoomState import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.R import com.vayunmathur.photos.Route@@ -19,7 +20,6 @@ import com.vayunmathur.photos.data.VideoFilterPreset import com.vayunmathur.photos.ui.OcrTextLayer import com.vayunmathur.photos.ui.SecureFolderPage import com.vayunmathur.photos.ui.VaultViewerScreen-import com.vayunmathur.photos.ui.ZoomState import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ViewerTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ViewerTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ViewerTest.ktindex 1a38c3864c..e3cc595869 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ViewerTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ViewerTest.kt@@ -22,6 +22,7 @@ import androidx.compose.foundation.layout.requiredWidth import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.ZoomState import com.vayunmathur.photos.R import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.VideoData@@ -30,7 +31,6 @@ import com.vayunmathur.photos.ui.PhotoDetailSection import com.vayunmathur.photos.ui.PhotoMetadataCard import com.vayunmathur.photos.ui.PhotoViewerActions import com.vayunmathur.photos.ui.PhotoViewerWideLayout-import com.vayunmathur.photos.ui.ZoomState import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue