wordmaker: fit the letter wheel to the room it actually gets (#ux-audit)
- Commit
14a80dfb878a5b9ef1223ec41aca9f510ce190c7- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 01:16 UTC (23 days ago)
- Parents
9dfb18d
Symptom: with the Wider or Widest wheel spacing (or Wide on a 360 dp phone) the shuffle button disappeared and swipes started missing letters - touches registered on a ring offset from the drawn tiles. Root cause: the wheel row was a fixed 72 dp column + the nominal wheel box (2 x ring radius + 80 dp, up to 340 dp) + the 48 dp shuffle button. When that exceeded the screen width the Row squeezed the box and gave shuffle zero width. Letter centres for the trail and for hit-testing were computed from the nominal box size and ring radius, while the tiles were drawn centred in the squeezed (and sometimes non-square) box, so the two drifted apart. Fix: - New WheelGeometry (pure, unit-tested) computes the ring from the box's measured size: centre = measured centre, radius clamped so every tile stays inside, and tiles shrink in proportion only when the box is smaller than the Default spacing's box. Hit-testing picks the nearest letter whose tile contains the touch. - The wheel is a BoxWithConstraints between two equal 56 dp side columns (tap-to-spell buttons left, shuffle right). It is the weighted child, so the side columns are always measured first and shuffle can never be squeezed out; the box is square and capped at the spacing's nominal size. - Tiles, the trail and the drag handler all use the same geometry. The drag handler reads it through rememberUpdatedState, so a size or spacing change no longer needs to restart the gesture. User-visible effect: every spacing works on every phone width. When the screen is too narrow for the chosen spacing the ring is as wide as fits (on 411 dp phones Wider/Widest now render at ~115 dp radius instead of overflowing); Default and Wide on typical phones are unchanged. Shuffle is always visible. Verification: WheelGeometryTest covers ordering, clamping to the measured (also non-square) box, hit-testing and tile scaling. LetterChooserInputTest runs Widest on a 360 dp screen: shuffle is displayed and a swipe aimed at the drawn C, A, T tiles spells "CAT".
Diff
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooser.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooser.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooser.ktindex 58dbfc6903..ba0f52a3ee 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooser.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooser.kt@@ -4,14 +4,16 @@ import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape@@ -76,7 +78,6 @@ fun LetterChooser( var selectedLettersIndices by remember(letters) { mutableStateOf(listOf<Int>()) } val formedWord = selectedLettersIndices.map { letters[it].char }.joinToString("")- var dragStartOffset by remember(letters) { mutableStateOf(Offset.Zero) } var currentDragPosition by remember(letters) { mutableStateOf<Offset?>(null) } // The word box keeps showing a submitted word while it is judged (a rejected word shakes@@ -105,43 +106,6 @@ fun LetterChooser( } } - val density = LocalDensity.current- val letterCircleRadius = with(density) { 35.dp.toPx() }- val boxSize = wheelSpacing.boxSize- val boxSizePx = with(density) { boxSize.toPx() }- val boxCenter = Offset(boxSizePx / 2, boxSizePx / 2)-- val angleStep = 2 * Math.PI / letters.size.toDouble()- val radius = wheelSpacing.ringRadius- val radiusPx = with(density) { radius.toPx() }- val letterCenters = remember(letters, boxCenter, radiusPx) {- List(letters.size) { index ->- val angle = angleStep * index - (Math.PI / 2)- boxCenter + Offset(cos(angle).toFloat() * radiusPx, sin(angle).toFloat() * radiusPx)- }- }-- fun getLetterAtArc(position: Offset): Int {- val relative = position - boxCenter-- val angle = atan2(relative.y, relative.x)- var normalizedAngle = angle + Math.PI / 2- while (normalizedAngle < 0) normalizedAngle += 2 * Math.PI- while (normalizedAngle >= 2 * Math.PI) normalizedAngle -= 2 * Math.PI-- return (normalizedAngle / angleStep).roundToInt() % letters.size- }-- fun getLetterAtCircle(position: Offset): Int? {- for (i in letterCenters.indices) {- val center = letterCenters[i]- if (distance(position, center) <= letterCircleRadius) {- return i- }- }- return null- }- // While a swipe is in progress the box shows it; otherwise it shows the word being judged. val isSpelling = selectedLettersIndices.isNotEmpty() val shownWord = if (isSpelling) formedWord else judgedWord.orEmpty()@@ -165,9 +129,12 @@ fun LetterChooser( null ) - Row(verticalAlignment = Alignment.Top) {+ // The wheel takes the room left between two equal side columns, so the shuffle button+ // (right column) always stays on screen and the wheel stays centred. Wider spacings+ // used to push the row past the screen edge on narrow phones, dropping shuffle.+ Row(Modifier.weight(1f, fill = false), verticalAlignment = Alignment.Top) { Column(- modifier = Modifier.width(72.dp),+ modifier = Modifier.width(SIDE_COLUMN_WIDTH), horizontalAlignment = Alignment.CenterHorizontally ) { if (tapToSpell && selectedLettersIndices.isNotEmpty()) {@@ -182,99 +149,138 @@ fun LetterChooser( } } }- Box(+ BoxWithConstraints( modifier = Modifier- .size(boxSize)- .onGloballyPositioned {- dragStartOffset = it.localToRoot(Offset.Zero)- }- // Keyed on the spacing as well as the letters: the gesture coroutine keeps- // the closures from the composition that started it, and getLetterAtArc /- // getLetterAtCircle capture boxCenter, radiusPx and letterCenters. Without- // the extra key, changing the spacing mid-puzzle redraws the wheel at the- // new radius but keeps hit-testing against the old one.- .pointerInput(letters, wheelSpacing) {- detectDragGestures(- onDragStart = { startOffset ->- currentDragPosition = startOffset- selectedLettersIndices = listOf(getLetterAtArc(startOffset))- },- onDrag = { change, _ ->- currentDragPosition = change.position- getLetterAtCircle(change.position)?.let { idx ->- if (idx !in selectedLettersIndices) {- selectedLettersIndices = selectedLettersIndices + idx- } else if (selectedLettersIndices.size > 1 && idx == selectedLettersIndices[selectedLettersIndices.size - 2]) {- selectedLettersIndices = selectedLettersIndices.dropLast(1)- }- }- },- onDragEnd = {- currentDragPosition = null- submitSelection()- },- onDragCancel = {- currentDragPosition = null- selectedLettersIndices = emptyList()- }- )- },+ .weight(1f, fill = false)+ .sizeIn(maxWidth = wheelSpacing.boxSize, maxHeight = wheelSpacing.boxSize)+ .aspectRatio(1f), contentAlignment = Alignment.Center ) {- val primaryColor = MaterialTheme.colorScheme.primary- Canvas(modifier = Modifier.fillMaxSize()) {- selectedLettersIndices.zipWithNext { a, b ->- drawLine(primaryColor, letterCenters[a], letterCenters[b], 10f, cap = StrokeCap.Round)- }- val lastLetter = selectedLettersIndices.lastOrNull()- if (lastLetter != null && currentDragPosition != null) {- drawLine(primaryColor, letterCenters[lastLetter], currentDragPosition!!, 10f, cap = StrokeCap.Round)- }+ // Everything below is laid out from the box's measured size, so the tiles, the+ // trail and the touch targets agree even when the box got less than it asked for.+ val density = LocalDensity.current+ val widthPx = constraints.maxWidth.toFloat()+ val heightPx = constraints.maxHeight.toFloat()+ val tilePx = WheelGeometry.tileSize(+ side = minOf(widthPx, heightPx),+ defaultSide = with(density) { WheelSpacing.DEFAULT.boxSize.toPx() },+ nominalTile = with(density) { LETTER_TILE.toPx() },+ )+ val geometry = WheelGeometry.fit(+ widthPx, heightPx, with(density) { wheelSpacing.ringRadius.toPx() }, tilePx / 2, letters.size+ )+ val tileSize = with(density) { tilePx.toDp() }+ val radiusDp = with(density) { geometry.ringRadius.toDp() }+ // The gesture coroutine outlives recompositions; it reads the geometry through+ // updated state, so a size or spacing change mid-puzzle is hit-tested at the new+ // positions without restarting a swipe in progress.+ val currentGeometry by rememberUpdatedState(geometry)++ fun getLetterAtArc(position: Offset): Int {+ val relative = position - currentGeometry.center+ val angleStep = 2 * Math.PI / letters.size.toDouble()+ var normalizedAngle = atan2(relative.y, relative.x) + Math.PI / 2+ while (normalizedAngle < 0) normalizedAngle += 2 * Math.PI+ while (normalizedAngle >= 2 * Math.PI) normalizedAngle -= 2 * Math.PI+ return (normalizedAngle / angleStep).roundToInt() % letters.size }- Surface(- Modifier.fillMaxSize(0.9f),- CircleShape,- MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.5f)- ) {} - letters.forEachIndexed { index, chooserLetter ->- key(chooserLetter.id) {- val angle = angleStep * index - (Math.PI / 2)- val targetX = (cos(angle) * radius.value).dp- val targetY = (sin(angle) * radius.value).dp+ // The tiles' parent handles the swipe, so it sees every move after the tiles+ // (which only take taps, in tap-to-spell mode).+ Box(+ Modifier+ .fillMaxSize()+ .pointerInput(letters) {+ detectDragGestures(+ onDragStart = { startOffset ->+ currentDragPosition = startOffset+ selectedLettersIndices = listOf(getLetterAtArc(startOffset))+ },+ onDrag = { change, _ ->+ currentDragPosition = change.position+ currentGeometry.letterAt(change.position)?.let { idx ->+ if (idx !in selectedLettersIndices) {+ selectedLettersIndices = selectedLettersIndices + idx+ } else if (selectedLettersIndices.size > 1 && idx == selectedLettersIndices[selectedLettersIndices.size - 2]) {+ selectedLettersIndices = selectedLettersIndices.dropLast(1)+ }+ }+ },+ onDragEnd = {+ currentDragPosition = null+ submitSelection()+ },+ onDragCancel = {+ currentDragPosition = null+ selectedLettersIndices = emptyList()+ }+ )+ },+ contentAlignment = Alignment.Center+ ) {+ val primaryColor = MaterialTheme.colorScheme.primary+ Canvas(modifier = Modifier.fillMaxSize()) {+ val centers = geometry.centers+ selectedLettersIndices.zipWithNext { a, b ->+ drawLine(primaryColor, centers[a], centers[b], 10f, cap = StrokeCap.Round)+ }+ val lastLetter = selectedLettersIndices.lastOrNull()+ val dragPosition = currentDragPosition+ if (lastLetter != null && dragPosition != null) {+ drawLine(primaryColor, centers[lastLetter], dragPosition, 10f, cap = StrokeCap.Round)+ }+ }+ Surface(+ Modifier.fillMaxSize(0.9f),+ CircleShape,+ MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.5f)+ ) {} - val x = animatedDp(targetX)- val y = animatedDp(targetY)+ letters.forEachIndexed { index, chooserLetter ->+ key(chooserLetter.id) {+ val angle = WheelGeometry.angleOf(index, letters.size)+ val x = animatedDp((cos(angle) * radiusDp.value).dp)+ val y = animatedDp((sin(angle) * radiusDp.value).dp) - SurfaceText(Modifier- .align(Alignment.Center)- .offset { IntOffset(x.roundToPx(), y.roundToPx()) }- .onGloballyPositioned { coordinates ->- onLetterPositioned(chooserLetter.id, coordinates.localToRoot(Offset.Zero))- }- .then(if (tapToSpell) Modifier.clickable {- if (selectedLettersIndices.lastOrNull() == index) {- selectedLettersIndices = selectedLettersIndices.dropLast(1)- } else if (index !in selectedLettersIndices) {- selectedLettersIndices = selectedLettersIndices + index+ SurfaceText(Modifier+ .align(Alignment.Center)+ .offset { IntOffset(x.roundToPx(), y.roundToPx()) }+ .onGloballyPositioned { coordinates ->+ onLetterPositioned(chooserLetter.id, coordinates.localToRoot(Offset.Zero)) }- } else Modifier),- CircleShape,- if (index in selectedLettersIndices) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.secondary,- chooserLetter.char.toString(),- Modifier.padding(1.dp),- FontWeight.Bold,- 42.sp,- 70.dp- )+ .then(if (tapToSpell) Modifier.clickable {+ if (selectedLettersIndices.lastOrNull() == index) {+ selectedLettersIndices = selectedLettersIndices.dropLast(1)+ } else if (index !in selectedLettersIndices) {+ selectedLettersIndices = selectedLettersIndices + index+ }+ } else Modifier),+ CircleShape,+ if (index in selectedLettersIndices) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.secondary,+ chooserLetter.char.toString(),+ Modifier.padding(1.dp),+ FontWeight.Bold,+ 42.sp,+ tileSize+ )+ } } } }- FilledIconButton(onClick = onShuffle) {- Icon(painterResource(R.drawable.ic_shuffle), contentDescription = stringResource(R.string.cd_shuffle))+ Column(+ modifier = Modifier.width(SIDE_COLUMN_WIDTH),+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ FilledIconButton(onClick = onShuffle) {+ Icon(painterResource(R.drawable.ic_shuffle), contentDescription = stringResource(R.string.cd_shuffle))+ } } } } } -private fun distance(a: Offset, b: Offset): Float = (a - b).getDistance()+/** Width of each column beside the wheel: tap-to-spell buttons on one side, shuffle on the other. */+private val SIDE_COLUMN_WIDTH = 56.dp++/** A letter tile at full size. */+private val LETTER_TILE = 70.dp
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/WheelGeometry.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/WheelGeometry.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/WheelGeometry.ktnew file mode 100644index 0000000000..a0a47c68b4--- /dev/null+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/components/WheelGeometry.kt@@ -0,0 +1,60 @@+package com.vayunmathur.games.wordmaker.ui.components++import androidx.compose.ui.geometry.Offset+import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.min+import kotlin.math.sin++/**+ * Where the letters of the wheel sit, in the wheel box's own pixel space.+ *+ * Built from the box's *measured* size rather than the nominal [WheelSpacing] size, so drawing,+ * the trail and hit-testing always agree with what is on screen: when a narrow phone or a wide+ * spacing gives the box less room than it asked for, the ring shrinks to fit instead of the+ * touch targets drifting away from the tiles.+ */+internal class WheelGeometry(+ /** Centre of the box. */+ val center: Offset,+ /** Distance from [center] to each letter's centre. */+ val ringRadius: Float,+ /** Half a letter tile: a touch this close to a letter's centre is on that letter. */+ val tileRadius: Float,+ val count: Int,+) {+ /** Letter centres, index 0 at the top and going clockwise. */+ val centers: List<Offset> = List(count) { index ->+ val angle = angleOf(index, count)+ center + Offset(cos(angle).toFloat() * ringRadius, sin(angle).toFloat() * ringRadius)+ }++ /** The letter whose tile contains [position] (the nearest one where tiles overlap), or null. */+ fun letterAt(position: Offset): Int? =+ centers.indices+ .filter { (centers[it] - position).getDistance() <= tileRadius }+ .minByOrNull { (centers[it] - position).getDistance() }++ companion object {+ /** Angle of letter [index] of [count], in radians, measured clockwise from the x axis. */+ fun angleOf(index: Int, count: Int): Double = 2 * PI * index / count - PI / 2++ /**+ * Fits a ring of [nominalRadius] into a [width] x [height] box: the radius is clamped so+ * every tile of [tileRadius] stays inside the box.+ */+ fun fit(width: Float, height: Float, nominalRadius: Float, tileRadius: Float, count: Int): WheelGeometry {+ val half = min(width, height) / 2+ val radius = nominalRadius.coerceAtMost(half - tileRadius).coerceAtLeast(0f)+ return WheelGeometry(Offset(width / 2, height / 2), radius, tileRadius, count)+ }++ /**+ * Tile size for a wheel box of [side], given the box the default spacing asks for: full size when the+ * box got at least the default room, shrunk in proportion below that so the letters keep+ * a gap between them on very narrow screens.+ */+ fun tileSize(side: Float, defaultSide: Float, nominalTile: Float): Float =+ if (defaultSide <= 0f) nominalTile else nominalTile * min(1f, side / defaultSide)+ }+}
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooserInputTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooserInputTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooserInputTest.ktindex e1f8d9eb3b..396740d477 100644--- a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooserInputTest.kt+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/LetterChooserInputTest.kt@@ -3,6 +3,7 @@ package com.vayunmathur.games.wordmaker.ui.components import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.geometry.Offset import androidx.compose.ui.platform.LocalLayoutDirection+import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText@@ -97,4 +98,17 @@ class LetterChooserInputTest { rule.waitForIdle() assertEquals(listOf("CA", "T"), submitted) }++ @Config(qualifiers = "w360dp-h740dp")+ @Test fun widestSpacingOnANarrowPhoneKeepsShuffleAndAccurateTouches() {+ val submitted = mutableListOf<String>()+ setChooser(spacing = WheelSpacing.WIDEST) { submitted += it }+ // The shuffle button used to be pushed off the right edge here.+ rule.onNodeWithContentDescription("Shuffle").assertIsDisplayed()+ val c = centerOf('C'); val a = centerOf('A'); val t = centerOf('T')+ // Touches aimed at where the letters are drawn land on those letters.+ rule.onRoot().performTouchInput { down(c); moveTo(c + Offset(0f, 12f)); moveTo(a); moveTo(t); up() }+ rule.waitForIdle()+ assertEquals(listOf("CAT"), submitted)+ } }
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/WheelGeometryTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/WheelGeometryTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/WheelGeometryTest.ktnew file mode 100644index 0000000000..50f1b6642e--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/components/WheelGeometryTest.kt@@ -0,0 +1,68 @@+package com.vayunmathur.games.wordmaker.ui.components++import androidx.compose.ui.geometry.Offset+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class WheelGeometryTest {+ private fun assertNear(expected: Offset, actual: Offset) {+ assertTrue((expected - actual).getDistance() < 0.01f, "expected $expected, got $actual")+ }++ @Test fun lettersStartAtTheTopAndGoClockwise() {+ val g = WheelGeometry.fit(width = 300f, height = 300f, nominalRadius = 100f, tileRadius = 35f, count = 4)+ assertNear(Offset(150f, 50f), g.centers[0])+ assertNear(Offset(250f, 150f), g.centers[1])+ assertNear(Offset(150f, 250f), g.centers[2])+ assertNear(Offset(50f, 150f), g.centers[3])+ }++ @Test fun ringFollowsTheMeasuredBoxNotTheNominalOne() {+ // Asked for a 130 radius (the Widest spacing) but the box only got 248 px:+ // the ring shrinks so every tile stays inside, and the centre is the measured centre.+ val g = WheelGeometry.fit(width = 248f, height = 248f, nominalRadius = 130f, tileRadius = 35f, count = 6)+ assertEquals(124f - 35f, g.ringRadius)+ assertEquals(Offset(124f, 124f), g.center)+ g.centers.forEach { c ->+ assertTrue(c.x - 35f >= -0.01f && c.x + 35f <= 248.01f, "tile at $c leaves the box")+ assertTrue(c.y - 35f >= -0.01f && c.y + 35f <= 248.01f, "tile at $c leaves the box")+ }+ }++ @Test fun nonSquareBoxUsesItsShortSideAndItsOwnCentre() {+ val g = WheelGeometry.fit(width = 250f, height = 230f, nominalRadius = 85f, tileRadius = 35f, count = 3)+ assertEquals(Offset(125f, 115f), g.center)+ assertEquals(115f - 35f, g.ringRadius)+ }++ @Test fun roomyBoxKeepsTheNominalRadius() {+ val g = WheelGeometry.fit(width = 400f, height = 400f, nominalRadius = 85f, tileRadius = 35f, count = 5)+ assertEquals(85f, g.ringRadius)+ }++ @Test fun hitTestUsesTheTileCircle() {+ val g = WheelGeometry.fit(width = 300f, height = 300f, nominalRadius = 100f, tileRadius = 35f, count = 4)+ assertEquals(0, g.letterAt(Offset(150f, 50f)))+ assertEquals(1, g.letterAt(Offset(250f + 30f, 150f)))+ // The centre of the wheel and the box corners are on no letter.+ assertNull(g.letterAt(Offset(150f, 150f)))+ assertNull(g.letterAt(Offset(2f, 2f)))+ assertNull(g.letterAt(Offset(298f, 298f)))+ }++ @Test fun overlappingTilesPickTheNearestLetter() {+ // Eight letters on a tight ring: neighbouring tiles overlap.+ val g = WheelGeometry.fit(width = 250f, height = 250f, nominalRadius = 85f, tileRadius = 35f, count = 8)+ val between = (g.centers[0] * 0.48f) + (g.centers[1] * 0.52f)+ assertTrue((g.centers[0] - between).getDistance() <= 35f, "both tiles contain the point")+ assertEquals(1, g.letterAt(between))+ }++ @Test fun tilesShrinkOnlyBelowTheDefaultBox() {+ assertEquals(70f, WheelGeometry.tileSize(side = 300f, defaultSide = 250f, nominalTile = 70f))+ assertEquals(70f, WheelGeometry.tileSize(side = 250f, defaultSide = 250f, nominalTile = 70f))+ assertEquals(56f, WheelGeometry.tileSize(side = 200f, defaultSide = 250f, nominalTile = 70f), 0.001f)+ }+}