Modern Apps git

← Modern-Apps.git

wordmaker: clamp crossword zoom and pan, double-tap reset, refit (#ux-audit)

Commit
d159a85f917ae8ba09df9d16ef06c12194c5311a
Author
Vayun Mathur <[email protected]>
When
2026-11-13 01:26 UTC (23 days ago)
Parents
025b061
Symptom: the crossword's pinch-zoom had no limits - the board could
be shrunk to a speck or blown up without bound, and dragged
completely off-screen with no way back short of restarting the level.
After a rotation it kept the old orientation's scale, so it no longer
fit (or was needlessly small).

Root cause: CrosswordBoard multiplied an unclamped scale state by
every zoomChange and added every pan without limits. The fit scale
was recomputed when the size changed, but the scale state was only
keyed on the puzzle, so the new fit was ignored after the first
composition. The board was also aligned TopStart inside its
unbounded wrapper, so a board bigger than the box was not centred on
the pivot the zoom maths assumed.

Fix:
- New pure BoardZoom holds the zoom relative to the fit plus the pan.
  Each gesture step clamps the zoom to [fit, max(3x fit, 2x natural
  size)] and the pan so a board larger than the box can only move
  until its edge meets the box edge (a board that fits stays
  centred). The centroid pivot maths is unchanged.
- The fit is recomputed from the box's current constraints on every
  layout and the stored zoom/pan are re-clamped against it, so a
  rotation refits the board while keeping the user's relative zoom.
- Double-tap on the board (anywhere not on a found word, which keeps
  opening its definition) resets to fit-to-screen.
- The board is centred inside its unbounded wrapper.

User-visible effect: zoom stays between "whole board visible" and a
comfortable close-up, the board can't be lost off-screen, double-tap
gets back to the overview, and rotating refits the board.

Verification: BoardZoomTest (fit, zoom clamps, pan clamps, pivot,
re-clamping after a size change) and CrosswordZoomTest (real pinch
gestures: zoom-out stops at the fit, zoom-in caps at 2x natural size,
double-tap resets, resizing the box from 148 to 222 dp refits from
0.5 to 0.75).

Diff

games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/BoardZoom.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/BoardZoom.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/BoardZoom.ktnew file mode 100644index 0000000000..09af7e5ff7--- /dev/null+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/BoardZoom.kt@@ -0,0 +1,76 @@+package com.vayunmathur.games.wordmaker.ui.components++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import kotlin.math.max+import kotlin.math.min++/**+ * Pinch-zoom state of the crossword board: a zoom relative to the fit-to-screen scale plus a+ * pan of the board's centre from the box's centre, both in pixels.+ *+ * Keeping the zoom relative to the fit means the fit can be recomputed whenever the box+ * changes size (rotation, split screen) without leaving a scale meant for the old size.+ */+internal data class BoardZoom(val zoom: Float = 1f, val pan: Offset = Offset.Zero) {++    /** Absolute layer scale for a board whose fit-to-box scale is [fit]. */+    fun scale(fit: Float): Float = fit * zoom++    /**+     * One pinch/drag step: [zoomChange] around [centroid] (relative to the box centre) plus+     * [panChange], clamped so the board can neither shrink below the fit, grow past+     * [maxZoom], nor be pushed off-screen.+     */+    fun transformed(+        fit: Float,+        board: Size,+        box: Size,+        centroid: Offset,+        zoomChange: Float,+        panChange: Offset,+    ): BoardZoom {+        val newZoom = (zoom * zoomChange).coerceIn(1f, maxZoom(fit))+        val applied = newZoom / zoom+        // Keep the board point under the centroid fixed while zooming, then apply the drag.+        val newPan = centroid - (centroid - pan) * applied + panChange+        return BoardZoom(newZoom, clampPan(newPan, board, box, fit * newZoom))+    }++    /** This zoom with its pan re-clamped for the current sizes (after a size change). */+    fun clampedTo(fit: Float, board: Size, box: Size): BoardZoom {+        val z = zoom.coerceIn(1f, maxZoom(fit))+        return BoardZoom(z, clampPan(pan, board, box, fit * z))+    }++    companion object {+        /** Zooming in goes to at least this many times the fit... */+        private const val MIN_MAX_ZOOM = 3f++        /** ...and always far enough for cells to reach this scale (natural size is 1). */+        private const val MAX_ABSOLUTE_SCALE = 2f++        /** Scale at which a [board] fits inside [box]; never above natural size. */+        fun fitScale(board: Size, box: Size): Float {+            val sx = if (board.width > 0f) box.width / board.width else 1f+            val sy = if (board.height > 0f) box.height / board.height else 1f+            return min(min(sx, sy), 1f).coerceAtLeast(MIN_FIT)+        }++        /** Largest zoom (relative to [fit]) a pinch may reach. */+        fun maxZoom(fit: Float): Float = max(MIN_MAX_ZOOM, MAX_ABSOLUTE_SCALE / fit)++        /**+         * Pan limits: a board larger than the box may move until its edge meets the box edge;+         * a board that fits stays centred on that axis.+         */+        fun clampPan(pan: Offset, board: Size, box: Size, scale: Float): Offset {+            val maxX = max(0f, (board.width * scale - box.width) / 2)+            val maxY = max(0f, (board.height * scale - box.height) / 2)+            return Offset(pan.x.coerceIn(-maxX, maxX), pan.y.coerceIn(-maxY, maxY))+        }++        /** Guards against a zero-size box (before the first layout) collapsing the scale. */+        private const val MIN_FIT = 0.05f+    }+}
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/CrosswordBoard.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/CrosswordBoard.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/CrosswordBoard.ktindex 5f5da3d69f..e34c2141e8 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/CrosswordBoard.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/CrosswordBoard.kt@@ -1,6 +1,7 @@ package com.vayunmathur.games.wordmaker.ui.components  import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.rememberTransformableState import androidx.compose.foundation.gestures.transformable import androidx.compose.foundation.layout.Box@@ -16,7 +17,6 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue@@ -24,9 +24,11 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight@@ -69,18 +71,19 @@ fun CrosswordBoard(         val numRows = crosswordData.gridStructure.size         val numCols = if (numRows > 0) crosswordData.gridStructure[0].length else 0 -        val boardWidth = 37.dp * numCols-        val boardHeight = 37.dp * numRows--        val initialScale = remember(crosswordData, maxWidth, maxHeight) {-            val scaleX = if (boardWidth.value > 0) maxWidth / boardWidth else 1f-            val scaleY = if (boardHeight.value > 0) maxHeight / boardHeight else 1f-            minOf(scaleX, scaleY, 1f)-        }--        var scale by remember(crosswordData) { mutableFloatStateOf(initialScale) }-        var offset by remember(crosswordData) { mutableStateOf(Offset.Zero) }-        var boxCenter by remember { mutableStateOf(Offset.Zero) }+        val density = LocalDensity.current+        val board = with(density) { Size((CELL_PITCH * numCols).toPx(), (CELL_PITCH * numRows).toPx()) }+        val box = Size(+            if (constraints.hasBoundedWidth) constraints.maxWidth.toFloat() else board.width,+            if (constraints.hasBoundedHeight) constraints.maxHeight.toFloat() else board.height,+        )+        // Recomputed from the current size on every layout, so after a rotation the board is+        // fitted to the new box instead of keeping a scale meant for the old one. The user's+        // zoom is stored relative to this fit and re-clamped to the new size.+        val fit = BoardZoom.fitScale(board, box)+        var zoom by remember(crosswordData) { mutableStateOf(BoardZoom()) }+        val view = zoom.clampedTo(fit, board, box)+        val scale = view.scale(fit)          // Ensure parent knows the current scale, especially the initial one         LaunchedEffect(scale) {@@ -88,31 +91,41 @@ fun CrosswordBoard(         }          val state = rememberTransformableState { centroid, zoomChange, offsetChange, _ ->-            scale *= zoomChange-            // Keep the board point under the gesture centroid fixed while zooming.-            // The graphicsLayer lives on the centered child (default centre-            // transformOrigin), so pivot relative to the container centre, then-            // apply the two-finger drag.-            val d = centroid - boxCenter-            offset = d - (d - offset) * zoomChange + offsetChange-            scaleUpdated(scale)+            // Zoom is clamped between the fit and BoardZoom.maxZoom, and the pan so the board+            // cannot be pushed off-screen. The graphicsLayer pivots on the board centre, which+            // sits on the box centre, so the centroid is taken relative to the box centre.+            zoom = zoom.clampedTo(fit, board, box).transformed(+                fit = fit,+                board = board,+                box = box,+                centroid = centroid - Offset(box.width / 2, box.height / 2),+                zoomChange = zoomChange,+                panChange = offsetChange,+            )         }          Box(             modifier = Modifier                 .fillMaxSize()-                .onGloballyPositioned { boxCenter = Offset(it.size.width / 2f, it.size.height / 2f) }+                // Double-tap anywhere off a found word puts the board back to fit-to-screen.+                // Outside transformable on purpose: the tap detector consumes the down, and+                // transformable abandons a gesture whose events were consumed before it saw them.+                .pointerInput(crosswordData) {+                    detectTapGestures(onDoubleTap = { zoom = BoardZoom() })+                }                 .transformable(state = state)         ) {             Column(                 modifier = Modifier.align(Alignment.Center)-                    .wrapContentSize(align = Alignment.TopStart, unbounded = true)+                    // Centred even when larger than the box, so the layer's pivot (the board+                    // centre) is the box centre the zoom maths assumes.+                    .wrapContentSize(align = Alignment.Center, unbounded = true)                     .graphicsLayer(                         scaleX = scale,                         scaleY = scale,-                        translationX = offset.x,-                        translationY = offset.y-                    ) // 3. Apply transformations+                        translationX = view.pan.x,+                        translationY = view.pan.y+                    )             ) {                 crosswordData.gridStructure.forEachIndexed { y, rowString ->                     Row {@@ -148,5 +161,8 @@ fun CrosswordBoard( /** A crossword cell (excluding its 1 dp margin). */ private val CELL_SIZE = 35.dp +/** A cell plus its margin on both sides: the grid's pitch. */+private val CELL_PITCH = 37.dp+ /** A cell's letter. */ private val CELL_GLYPH = 18.dp
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/CrosswordZoomTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/CrosswordZoomTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/CrosswordZoomTest.ktnew file mode 100644index 0000000000..f0830bd3e6--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/CrosswordZoomTest.kt@@ -0,0 +1,108 @@+package com.vayunmathur.games.wordmaker.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.doubleClick+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithTag+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.pinch+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.wordmaker.data.CrosswordData+import com.vayunmathur.games.wordmaker.ui.components.CrosswordBoard+import com.vayunmathur.library.ui.DynamicTheme+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals++/** Pinch-zoom of the crossword board: clamped, resettable, and refitted on size change. */+@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w411dp-h891dp")+class CrosswordZoomTest {+    @get:Rule val rule = createComposeRule()++    // 8 columns x 6 rows: 296 x 222 dp at natural size.+    private val data = CrosswordData.fromString("...FIVE.\n.F.I.E..\nRIFE.R.R\n.R.R.IVY\nVERY.F.E\n.....Y..")!!+    private var width by mutableStateOf(148.dp)+    private var lastScale = -1f++    private fun setBoard() {+        rule.setContent {+            DynamicTheme {+                Box(Modifier.size(width, 400.dp).testTag("board")) {+                    CrosswordBoard(+                        foundWords = emptySet(), revealedHints = emptySet(), crosswordData = data, hiddenWords = emptySet(),+                        onCellPositioned = { _, _ -> }, onCellClicked = { _, _ -> }, scaleUpdated = { lastScale = it },+                    )+                }+            }+        }+        rule.waitForIdle()+    }++    private fun pinchBy(factor: Float) {+        // Fingers stay inside the 148 dp board (10 px apart from the centre, up to 60).+        rule.onNodeWithTag("board").performTouchInput {+            val c = center+            val start = 10f+            val end = start * factor+            pinch(c - Offset(start, 0f), c - Offset(end, 0f), c + Offset(start, 0f), c + Offset(end, 0f))+        }+        settle()+    }++    /**+     * The zoom is applied in the draw layer and reported through snapshotFlow, neither of which+     * needs a recomposition; run a frame so the layer and the collector catch up.+     */+    private fun settle() {+        rule.mainClock.advanceTimeByFrame()+        rule.waitForIdle()+    }++    /**+     * On-screen width of an (empty) grid cell's text: it scales with the board's layer. The+     * widest one, since cells at the edge of a zoomed board are clipped by the viewport.+     */+    private fun cellWidth(): Float =+        rule.onAllNodesWithText(" ", useUnmergedTree = true).fetchSemanticsNodes().maxOf { it.boundsInRoot.width }++    @Test fun zoomIsClampedAndDoubleTapResetsIt() {+        setBoard()+        val fit = lastScale+        assertEquals(0.5f, fit, 0.01f) // 148 dp box / 296 dp board+        val widthAtFit = cellWidth()++        pinchBy(0.2f)+        assertEquals(fit, lastScale, 0.01f, "cannot zoom out past the fit")+        assertEquals(1f, cellWidth() / widthAtFit, 0.05f, "drawn board did not shrink past the fit")++        pinchBy(6f); pinchBy(6f); pinchBy(6f)+        // Max is 4x the fit here (enough to reach 2x natural size).+        assertEquals(4f, cellWidth() / widthAtFit, 0.2f, "drawn zoom is capped at 4x the fit (reported $lastScale)")+        assertEquals(2f, lastScale, 0.01f, "reported zoom is capped")++        rule.onNodeWithTag("board").performTouchInput { doubleClick(center + Offset(1f, 180f)) }+        settle()+        assertEquals(fit, lastScale, 0.01f, "double-tap resets to fit")+        assertEquals(1f, cellWidth() / widthAtFit, 0.05f, "drawn board is back at the fit")+    }++    @Test fun fitIsRecomputedWhenTheBoxChangesSize() {+        setBoard()+        assertEquals(0.5f, lastScale, 0.01f)+        width = 222.dp // e.g. rotation: the box changes size+        rule.waitForIdle()+        assertEquals(0.75f, lastScale, 0.01f)+    }+}
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/BoardZoomTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/BoardZoomTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/BoardZoomTest.ktnew file mode 100644index 0000000000..e3617af2f4--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/BoardZoomTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.games.wordmaker.ui.components++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class BoardZoomTest {+    private val board = Size(370f, 222f)   // 10 x 6 cells at 37 px+    private val portrait = Size(300f, 500f)+    private val landscape = Size(700f, 200f)++    @Test fun fitNeverUpscalesAndFollowsTheBox() {+        assertEquals(1f, BoardZoom.fitScale(board, Size(1000f, 1000f)))+        assertEquals(300f / 370f, BoardZoom.fitScale(board, portrait))+        assertEquals(200f / 222f, BoardZoom.fitScale(board, landscape))+    }++    @Test fun zoomIsClampedBetweenFitAndMax() {+        val fit = BoardZoom.fitScale(board, portrait)+        val zoomedOut = BoardZoom().transformed(fit, board, portrait, Offset.Zero, zoomChange = 0.1f, panChange = Offset.Zero)+        assertEquals(fit, zoomedOut.scale(fit))+        val zoomedIn = BoardZoom().transformed(fit, board, portrait, Offset.Zero, zoomChange = 50f, panChange = Offset.Zero)+        assertEquals(BoardZoom.maxZoom(fit), zoomedIn.zoom)+        assertTrue(zoomedIn.scale(fit) >= 2f - 1e-4f, "max zoom reaches at least 2x natural size")+    }++    @Test fun panCannotPushTheBoardOffScreen() {+        val fit = BoardZoom.fitScale(board, portrait)+        // At the fit the board is no wider than the box: it stays centred however far you drag.+        val atFit = BoardZoom().transformed(fit, board, portrait, Offset.Zero, 1f, Offset(5000f, -5000f))+        assertEquals(0f, atFit.pan.x, 0.01f)+        assertEquals(0f, atFit.pan.y, 0.01f)+        // Zoomed 2x: it may move only until its edge meets the box edge.+        val zoomed = BoardZoom(zoom = 2f).transformed(fit, board, portrait, Offset.Zero, 1f, Offset(5000f, 5000f))+        val scaled = board.width * fit * 2f+        assertEquals((scaled - portrait.width) / 2, zoomed.pan.x, 0.01f)+        assertEquals(0f, zoomed.pan.y, 0.01f) // 222 * 0.81 * 2 = 360 < 500: still fits vertically+    }++    @Test fun pinchKeepsThePointUnderTheFingersFixed() {+        val fit = 1f+        val big = Size(1000f, 1000f)+        val centroid = Offset(100f, 50f)+        val z = BoardZoom().transformed(fit, Size(2000f, 2000f), big, centroid, zoomChange = 1.5f, panChange = Offset.Zero)+        // Board point under the centroid before: centroid (pan 0, scale 1). After: pan + centroid' * 1.5.+        assertEquals(centroid.x, z.pan.x + centroid.x * 1.5f, 0.01f)+        assertEquals(centroid.y, z.pan.y + centroid.y * 1.5f, 0.01f)+    }++    @Test fun rotationReclampsAStaleZoomAndPan() {+        val portraitFit = BoardZoom.fitScale(board, portrait)+        val zoomed = BoardZoom().transformed(portraitFit, board, portrait, Offset.Zero, 2f, Offset(10_000f, 0f))+        // In landscape the fit changes and the old pan would push the board too far.+        val landscapeFit = BoardZoom.fitScale(board, landscape)+        val view = zoomed.clampedTo(landscapeFit, board, landscape)+        val maxX = maxOf(0f, (board.width * view.scale(landscapeFit) - landscape.width) / 2)+        assertTrue(kotlin.math.abs(view.pan.x) <= maxX + 0.01f)+        assertEquals(zoomed.zoom, view.zoom)+    }+}