Modern Apps git

← Modern-Apps.git

wordmaker: stop recomposing the game screen every tick and frame (#ux-audit)

Commit
2a07f934e2582f908575f4fb4b7c711ce2c5ca75
Author
Vayun Mathur <[email protected]>
When
2026-11-13 01:29 UTC (23 days ago)
Parents
d159a85
Symptom: visible jank on the game screen - during the hint cooldown,
competitive play, rejected-word shakes, word flights and especially
while pinch-zooming the crossword.

Root cause: hot values were Compose state read high up in the tree:
- WordGameScreen wrote remainingCooldown every 100 ms and the
  competitive remainingTime every 200 ms, recomposing the whole screen
  (board, wheel, overlays) 10 and 5 times a second.
- Both shake Animatables were read in composition (bonusShakeAnim.value
  in WordGameScreen, wordShakeAnim.value in WordGameWheel), so every
  shake frame recomposed the screen / the wheel.
- Every crossword cell reported its root position into a Map state
  (copying the whole map) on every frame of a pinch, and every letter
  on every frame of a shuffle; the board's own scale/pan and the
  screen's flight-letter scale were read in composition too.
- Flights read their progress in composition every frame.

Fix (no behaviour change intended):
- The competitive timer effect only waits for the deadline (wall-clock
  checks at most 1 s apart, so a device that slept past it still
  times out on wake) and writes no per-tick state. The countdown text
  ticks inside a private CompetitiveCountdown; the hint cooldown ticks
  inside a private HintButton, where only the enabled flag is read in
  composition (derivedStateOf) and the ring reads the clock in draw.
- Shake offsets are passed as () -> Float and read in graphicsLayer
  blocks (LetterChooser word box, bonus button).
- Cell and letter positions are plain HashMaps remembered per level;
  only a flight's start reads them.
- CrosswordBoard applies zoom in a graphicsLayer block and reports
  scale via snapshotFlow; the screen passes its scale, the word-box
  anchor and the bonus anchor to the overlays as providers.
- Flights read progress in absoluteOffset/graphicsLayer lambdas.

User-visible effect: smoother pinch-zoom, shakes and flights; the
screen no longer rebuilds 10x a second during a hint cooldown.

Verification: new LocalTickersTest - the hint button re-enables on
its own when the cooldown ends, and the competitive countdown runs
down to 00:00 and the timeout still fires. Existing overlay, corner
button, chooser, zoom and screen tests updated to the provider
parameters and still pass.

Diff

games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameOverlays.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameOverlays.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameOverlays.ktindex 4c4a234ed4..18cb085b90 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameOverlays.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameOverlays.kt@@ -61,13 +61,14 @@ fun WordGameOverlays(     animatedWord: String?,     animationProgress: Animatable<Float, AnimationVector1D>,     /** Root position of the formed-word box's text: where a bonus word takes off. */-    wordBoxOffset: Offset,+    wordBoxOffset: () -> Offset,     /** Root position of the bonus button's centre: where a bonus word lands. */-    bonusButtonCenter: Offset,+    bonusButtonCenter: () -> Offset,     /** Root position of the overlay's own origin; flights are drawn relative to it. */     rootOffset: Offset,     animatedLetters: List<AnimatedLetter>,-    scale: Float,+    /** Current crossword zoom, for the size of the flying letters. */+    scale: () -> Float, ) {     if (showHintDialog) {         AlertDialog(@@ -108,9 +109,6 @@ fun WordGameOverlays(     Box(Modifier.fillMaxSize(), contentAlignment = AbsoluteAlignment.TopLeft) {         animatedWord?.let { word ->             var wordSize by remember { mutableStateOf(IntSize.Zero) }-            val progress = animationProgress.value-            val alpha = 1f - progress-            val animScale = 1f - (progress * 0.5f)              Text(                 text = word,@@ -120,30 +118,38 @@ fun WordGameOverlays(                     .onSizeChanged { wordSize = it }                     .absoluteOffset {                         val offset = bonusFlightOffset(-                            wordBoxOffset, bonusButtonCenter, rootOffset, wordSize, animationProgress.value+                            wordBoxOffset(), bonusButtonCenter(), rootOffset, wordSize, animationProgress.value                         )                         IntOffset(offset.x.toInt(), offset.y.toInt())                     }-                    .graphicsLayer(-                        scaleX = animScale,-                        scaleY = animScale,-                        alpha = alpha-                    )+                    // Progress is read in placement and in the layer, never in composition, so a+                    // flight re-places and redraws the word without recomposing anything.+                    .graphicsLayer {+                        val progress = animationProgress.value+                        val animScale = 1f - (progress * 0.5f)+                        scaleX = animScale+                        scaleY = animScale+                        alpha = 1f - progress+                    }             )         }-        // Matches the crossword cell it lands in (dp-sized there too, so large fonts do not clip).-        val size = 35.dp * scale-        val fontSize = with(LocalDensity.current) { (18.dp * scale).toSp() }-        animatedLetters.forEach { letter ->-            val progress = letter.progress.value-            val offset = lerp(letter.startOffset, letter.endOffset, progress)--            SurfaceText(Modifier.absoluteOffset { IntOffset(offset.x.toInt(), offset.y.toInt()) },-                RoundedCornerShape(4.dp * scale),-                MaterialTheme.colorScheme.primary, letter.char.toString(),-                Modifier, FontWeight.Bold, fontSize, size,-                textColor = MaterialTheme.colorScheme.onPrimary,-                lineHeight = TILE_GLYPH_LINE_HEIGHT)+        if (animatedLetters.isNotEmpty()) {+            // Matches the crossword cell it lands in (dp-sized there too, so large fonts do+            // not clip). The zoom is only read while letters are actually flying.+            val zoom = scale()+            val size = 35.dp * zoom+            val fontSize = with(LocalDensity.current) { (18.dp * zoom).toSp() }+            animatedLetters.forEach { letter ->+                SurfaceText(Modifier.absoluteOffset {+                        val offset = lerp(letter.startOffset, letter.endOffset, letter.progress.value)+                        IntOffset(offset.x.toInt(), offset.y.toInt())+                    },+                    RoundedCornerShape(4.dp * zoom),+                    MaterialTheme.colorScheme.primary, letter.char.toString(),+                    Modifier, FontWeight.Bold, fontSize, size,+                    textColor = MaterialTheme.colorScheme.onPrimary,+                    lineHeight = TILE_GLYPH_LINE_HEIGHT)+            }         }     } }
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameScreen.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameScreen.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameScreen.ktindex 9a579f3f6c..b7c0b3628a 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameScreen.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameScreen.kt@@ -25,7 +25,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf-import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue@@ -66,6 +65,9 @@ import kotlinx.coroutines.delay /** Room above the wheel for the formed-word box and its padding. */ private val WHEEL_HEADROOM = 70.dp +/** Longest single wait of the competitive timer before it re-reads the wall clock. */+private const val MAX_TIMER_WAIT_MS = 1_000L+ @Composable fun WordGameScreen(     state: WordGameUiState,@@ -94,8 +96,6 @@ fun WordGameScreen(     }     var showBonusWordsDialog by remember(levelKey) { mutableStateOf(false) }     var showHintDialog by remember(levelKey) { mutableStateOf(false) }-    var remainingCooldown by remember { mutableLongStateOf(0L) }-    var remainingTime by remember(levelKey) { mutableLongStateOf(0L) }     var timedOut by remember(levelKey) { mutableStateOf(false) }     val density = LocalDensity.current     var rootOffset by remember { mutableStateOf(Offset.Zero) }@@ -105,16 +105,11 @@ fun WordGameScreen(     // second word waits for the first flight to finish instead of cancelling it.     var wordBoxOffset by remember(levelKey) { mutableStateOf(Offset.Zero) }     var bonusButtonCenter by remember(levelKey) { mutableStateOf(Offset.Zero) }-    var crosswordCellPositions by remember(levelKey) {-        mutableStateOf<Map<Pair<Int, Int>, Offset>>(-            emptyMap()-        )-    }-    var letterChooserPositions by remember(levelKey) {-        mutableStateOf<Map<Int, Offset>>(-            emptyMap()-        )-    }+    // Plain maps, not Compose state: every cell reports its position on every frame of a+    // pinch, and every letter on every frame of a shuffle, but only the start of a flight reads+    // them. As state, each report copied the whole map and recomposed the screen.+    val crosswordCellPositions = remember(levelKey) { HashMap<Pair<Int, Int>, Offset>() }+    val letterChooserPositions = remember(levelKey) { HashMap<Int, Offset>() }     val wordPlaceAnimations = rememberWordPlaceAnimations(         levelKey = levelKey,         crosswordData = crosswordData,@@ -140,28 +135,18 @@ fun WordGameScreen(      val isWon = crosswordData.winsWith(foundWords) +    // Only waits for the deadline; it writes no state per tick (the countdown text ticks on its+    // own inside the wheel), so the screen is not recomposed five times a second. Wall-clock+    // checks at most a second apart, so a device that slept past the deadline times out on wake.     LaunchedEffect(competitiveDeadline, isCompetitive, isWon, levelKey) {-        if (!isCompetitive || isWon || competitiveDeadline <= 0L) {-            if (competitiveDeadline <= 0L && !isWon) remainingTime = 0L-            return@LaunchedEffect-        }-        while (true) {-            remainingTime = (competitiveDeadline - System.currentTimeMillis()).coerceAtLeast(0)-            if (remainingTime <= 0L) break-            delay(200)-        }-        if (!isWon) {-            timedOut = true-            actions.onCompetitiveTimeout()-        }-    }--    LaunchedEffect(hintCooldownEnd) {+        if (!isCompetitive || isWon || competitiveDeadline <= 0L) return@LaunchedEffect         while (true) {-            remainingCooldown = (hintCooldownEnd - System.currentTimeMillis()).coerceAtLeast(0)-            if (remainingCooldown <= 0) break-            delay(100)+            val left = competitiveDeadline - System.currentTimeMillis()+            if (left <= 0L) break+            delay(left.coerceAtMost(MAX_TIMER_WAIT_MS))         }+        timedOut = true+        actions.onCompetitiveTimeout()     }      AppScaffold(@@ -208,12 +193,7 @@ fun WordGameScreen(                     revealedHints = revealedHints,                     crosswordData = crosswordData,                     hiddenWords = wordPlaceAnimations.flyingSolutionWords,-                    onCellPositioned = { position, offset ->-                        if (crosswordCellPositions[position] != offset) {-                            crosswordCellPositions =-                                crosswordCellPositions + (position to offset)-                        }-                    },+                    onCellPositioned = { position, offset -> crosswordCellPositions[position] = offset },                     onCellClicked = { row, col ->                         val word = crosswordData.getWordAt(row, col, foundWords)                         if (word != null && word in foundWords) {@@ -232,7 +212,7 @@ fun WordGameScreen(                     isCompetitive = isCompetitive,                     isDaily = isDaily,                     competitiveScore = competitiveScore,-                    remainingTimeMs = remainingTime,+                    competitiveDeadline = competitiveDeadline,                     dailyStreak = state.dailyStreak,                     wheelHeight = wheelHeight,                     isWon = isWon,@@ -257,10 +237,7 @@ fun WordGameScreen(                     wordShakeAnim = wordShakeAnim,                     bonusShakeAnim = bonusShakeAnim,                     onWordBoxPositioned = { wordBoxOffset = it },-                    letterChooserPositions = letterChooserPositions,-                    onLetterPositioned = { id, offset ->-                        letterChooserPositions = letterChooserPositions + (id to offset)-                    },+                    onLetterPositioned = { id, offset -> letterChooserPositions[id] = offset },                 )             } @@ -268,10 +245,10 @@ fun WordGameScreen(                 isWon = isWon,                 isCompetitive = isCompetitive,                 bonusWords = bonusWords,-                bonusShake = bonusShakeAnim.value,+                bonusShake = { bonusShakeAnim.value },                 onOpenBonusWords = { showBonusWordsDialog = true },                 onBonusButtonPositioned = { bonusButtonCenter = it },-                remainingCooldownMs = remainingCooldown,+                hintCooldownEnd = hintCooldownEnd,                 onOpenHint = { showHintDialog = true },             ) @@ -289,11 +266,11 @@ fun WordGameScreen(                 onDismissDefinition = { wordWithDefinition = null },                 animatedWord = wordPlaceAnimations.activeBonusWord,                 animationProgress = wordPlaceAnimations.bonusProgress,-                wordBoxOffset = wordBoxOffset,-                bonusButtonCenter = bonusButtonCenter,+                wordBoxOffset = { wordBoxOffset },+                bonusButtonCenter = { bonusButtonCenter },                 rootOffset = rootOffset,                 animatedLetters = wordPlaceAnimations.animatedLetters,-                scale = scale,+                scale = { scale },             )         }         }
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameWheel.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameWheel.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameWheel.ktindex e4f2206306..5039e0590f 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameWheel.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/WordGameWheel.kt@@ -11,6 +11,12 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset@@ -37,6 +43,7 @@ import com.vayunmathur.library.ui.IconHelp import com.vayunmathur.library.ui.IconBook import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Text+import kotlinx.coroutines.delay  /**  * Status bars plus the letter wheel below the board, extracted from@@ -48,7 +55,8 @@ fun WordGameWheel(     isCompetitive: Boolean,     isDaily: Boolean,     competitiveScore: Int,-    remainingTimeMs: Long,+    /** Epoch millis the competitive timer runs out; 0 when no timer runs. */+    competitiveDeadline: Long,     dailyStreak: Long,     wheelHeight: Dp,     isWon: Boolean,@@ -67,7 +75,6 @@ fun WordGameWheel(     wordShakeAnim: Animatable<Float, AnimationVector1D>,     bonusShakeAnim: Animatable<Float, AnimationVector1D>,     onWordBoxPositioned: (Offset) -> Unit,-    letterChooserPositions: Map<Int, Offset>,     onLetterPositioned: (Int, Offset) -> Unit, ) {     Column(@@ -75,9 +82,10 @@ fun WordGameWheel(         horizontalAlignment = Alignment.CenterHorizontally     ) {         if (isCompetitive) {-            CompetitiveStatusBar(+            CompetitiveCountdown(                 score = competitiveScore,-                remainingTimeMs = remainingTimeMs+                deadline = competitiveDeadline,+                running = !isWon && !timedOut,             )         } else if (isDaily) {             DailyStatusBar(streak = dailyStreak)@@ -118,12 +126,10 @@ fun WordGameWheel(                         onAnimateBonus = animations.enqueueBonus,                     ),                     onWordBoxPositioned = onWordBoxPositioned,-                    onLetterPositioned = { id, offset ->-                        if (letterChooserPositions[id] != offset) {-                            onLetterPositioned(id, offset)-                        }-                    },-                    wordShakeTranslation = wordShakeAnim.value+                    onLetterPositioned = onLetterPositioned,+                    // Read in the word box's graphicsLayer, not here: reading the shake value+                    // in composition recomposed the whole wheel on every shake frame.+                    wordShakeTranslation = { wordShakeAnim.value }                 )             }         }@@ -140,11 +146,13 @@ fun BoxScope.WordGameCornerButtons(     isWon: Boolean,     isCompetitive: Boolean,     bonusWords: Set<String>,-    bonusShake: Float,+    /** Current shake offset, read in the draw layer so a shake does not recompose. */+    bonusShake: () -> Float,     onOpenBonusWords: () -> Unit,     /** Receives the bonus button's centre in root coordinates. */     onBonusButtonPositioned: (Offset) -> Unit,-    remainingCooldownMs: Long,+    /** Epoch millis until which the hint is cooling down; 0 means available. */+    hintCooldownEnd: Long,     onOpenHint: () -> Unit, ) {     androidx.compose.foundation.layout.Box(@@ -159,7 +167,7 @@ fun BoxScope.WordGameCornerButtons(                 onBonusButtonPositioned(it.localToRoot(Offset(it.size.width / 2f, it.size.height / 2f)))             }             .graphicsLayer {-                translationX = bonusShake+                translationX = bonusShake()             },     ) {         // Badge: how many bonus words this puzzle has so far (#915).@@ -180,31 +188,78 @@ fun BoxScope.WordGameCornerButtons(     }      if (!isWon && !isCompetitive) {-        val hintEnabled = remainingCooldownMs <= 0L-        androidx.compose.foundation.layout.Box(+        HintButton(+            cooldownEnd = hintCooldownEnd,+            onOpenHint = onOpenHint,             modifier = Modifier                 .align(Alignment.BottomEnd)-                .padding(16.dp)+                .padding(16.dp),+        )+    }+}++/**+ * The hint button with its cooldown ring. The cooldown clock ticks here, not in the screen:+ * as screen state it recomposed the whole game ten times a second. Only the enabled flag is+ * read in composition; the ring reads the clock while drawing.+ */+@Composable+private fun HintButton(cooldownEnd: Long, onOpenHint: () -> Unit, modifier: Modifier) {+    var now by remember { mutableLongStateOf(System.currentTimeMillis()) }+    LaunchedEffect(cooldownEnd) {+        while (true) {+            now = System.currentTimeMillis()+            if (now >= cooldownEnd) break+            delay(COOLDOWN_TICK_MS)+        }+    }+    val hintEnabled by remember(cooldownEnd) { derivedStateOf { now >= cooldownEnd } }+    Box(modifier) {+        FilledIconButton(+            onClick = onOpenHint,+            enabled = hintEnabled         ) {-            FilledIconButton(-                onClick = onOpenHint,-                enabled = hintEnabled-            ) {-                // The button's disabled colours already dim the icon during the cooldown; a-                // second 0.5 alpha on top made it nearly invisible.-                IconHelp(contentDescription = stringResource(R.string.cd_hint))-            }-            if (!hintEnabled) {-                CircularProgressIndicator(-                    progress = { 1f - (remainingCooldownMs / 30_000f) },-                    modifier = Modifier.size(48.dp).align(Alignment.Center),-                    strokeWidth = 3.dp-                )-            }+            // The button's disabled colours already dim the icon during the cooldown; a+            // second 0.5 alpha on top made it nearly invisible.+            IconHelp(contentDescription = stringResource(R.string.cd_hint))+        }+        if (!hintEnabled) {+            CircularProgressIndicator(+                progress = { 1f - ((cooldownEnd - now).coerceAtLeast(0L) / HINT_COOLDOWN_MS) },+                modifier = Modifier.size(48.dp).align(Alignment.Center),+                strokeWidth = 3.dp+            )+        }+    }+}++/**+ * Competitive score and countdown. The countdown ticks locally, so only this bar recomposes+ * as the seconds run down, not the screen. It stops (frozen) once the level is over.+ */+@Composable+private fun CompetitiveCountdown(score: Int, deadline: Long, running: Boolean) {+    var now by remember { mutableLongStateOf(System.currentTimeMillis()) }+    LaunchedEffect(deadline, running) {+        // One fresh reading even when stopping, so the frozen value is the moment it ended.+        now = System.currentTimeMillis()+        while (running && deadline > 0L && now < deadline) {+            delay(COUNTDOWN_TICK_MS)+            now = System.currentTimeMillis()         }     }+    CompetitiveStatusBar(+        score = score,+        remainingTimeMs = if (deadline > 0L) (deadline - now).coerceAtLeast(0L) else 0L,+    ) } +private const val COOLDOWN_TICK_MS = 100L+private const val COUNTDOWN_TICK_MS = 200L++/** Length of the hint cooldown the ring counts down. */+private const val HINT_COOLDOWN_MS = 30_000f+ /** Most bonus words the badge spells out; beyond it shows "99+". */ private const val BONUS_BADGE_MAX = 99 
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 e34c2141e8..23028958c8 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@@ -19,7 +19,9 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip@@ -82,12 +84,14 @@ fun CrosswordBoard(         // 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) {-            scaleUpdated(scale)+        // Tell the parent the current scale, especially the initial one. Observed with+        // snapshotFlow and applied in the graphicsLayer block below, so the zoom is never read+        // in composition: a pinch redraws the board instead of recomposing every cell.+        val currentScaleUpdated by rememberUpdatedState(scaleUpdated)+        LaunchedEffect(fit, board, box) {+            snapshotFlow { zoom.clampedTo(fit, board, box).scale(fit) }+                .collect { currentScaleUpdated(it) }         }          val state = rememberTransformableState { centroid, zoomChange, offsetChange, _ ->@@ -120,12 +124,14 @@ fun CrosswordBoard(                     // 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 = view.pan.x,+                    .graphicsLayer {+                        val view = zoom.clampedTo(fit, board, box)+                        val scale = view.scale(fit)+                        scaleX = scale+                        scaleY = scale+                        translationX = view.pan.x                         translationY = view.pan.y-                    )+                    }             ) {                 crosswordData.gridStructure.forEachIndexed { y, rowString ->                     Row {
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 ac53316ece..e8c5a99699 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@@ -68,7 +68,8 @@ fun LetterChooser(     onWordSubmitted: suspend CoroutineScope.(String, List<Int>) -> Unit,     onWordBoxPositioned: (Offset) -> Unit,     onLetterPositioned: (id: Int, offset: Offset) -> Unit,-    wordShakeTranslation: Float = 0f+    /** Current shake offset of a rejected word, read in the draw layer (no recomposition). */+    wordShakeTranslation: () -> Float = { 0f } ) {     val coroutineScope = rememberCoroutineScope() @@ -116,11 +117,11 @@ fun LetterChooser(         SurfaceText(             Modifier                 .padding(bottom = 20.dp)-                .graphicsLayer(-                    alpha = if (shownWord.isNotEmpty()) 1f else 0f,+                .graphicsLayer {+                    alpha = if (shownWord.isNotEmpty()) 1f else 0f                     // The shake belongs to the judged word, never to a new swipe.-                    translationX = if (isSpelling) 0f else wordShakeTranslation-                ),+                    translationX = if (isSpelling) 0f else wordShakeTranslation()+                },             RoundedCornerShape(8.dp), MaterialTheme.colorScheme.primaryContainer,             shownWord.ifEmpty { " " },             Modifier
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/BonusWordsCounterTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/BonusWordsCounterTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/BonusWordsCounterTest.ktindex c7bc5d9079..5f9d201de3 100644--- a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/BonusWordsCounterTest.kt+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/BonusWordsCounterTest.kt@@ -60,10 +60,10 @@ class BonusWordsCounterTest {                         isWon = false,                         isCompetitive = true,                         bonusWords = setOf("OWL", "COW"),-                        bonusShake = 0f,+                        bonusShake = { 0f },                         onOpenBonusWords = { opened = true },                         onBonusButtonPositioned = {},-                        remainingCooldownMs = 0L,+                        hintCooldownEnd = 0L,                         onOpenHint = {},                     )                 }@@ -83,10 +83,10 @@ class BonusWordsCounterTest {                         isWon = false,                         isCompetitive = true,                         bonusWords = emptySet(),-                        bonusShake = 0f,+                        bonusShake = { 0f },                         onOpenBonusWords = {},                         onBonusButtonPositioned = {},-                        remainingCooldownMs = 0L,+                        hintCooldownEnd = 0L,                         onOpenHint = {},                     )                 }
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/LocalTickersTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/LocalTickersTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/LocalTickersTest.ktnew file mode 100644index 0000000000..f4f6048c7d--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/LocalTickersTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.games.wordmaker.ui++import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import com.vayunmathur.games.wordmaker.data.CrosswordData+import com.vayunmathur.games.wordmaker.data.GameMode+import com.vayunmathur.games.wordmaker.platform.WordGameActions+import com.vayunmathur.games.wordmaker.platform.WordGameUiState+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.assertTrue++/**+ * The hint cooldown and the competitive countdown tick inside their own small composables now+ * (not as screen state); they must still run down and fire on their own.+ */+@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w411dp-h891dp")+class LocalTickersTest {+    @get:Rule val rule = createComposeRule()+    private val board = CrosswordData.fromString("CAT\n C \n T ")!!++    /** Lets real (wall-clock) time pass [untilMillis], then runs the frame clock so tickers wake. */+    private fun passWallClock(untilMillis: Long) {+        val wait = untilMillis - System.currentTimeMillis()+        if (wait > 0) Thread.sleep(wait)+        rule.mainClock.advanceTimeBy(1_500)+        rule.waitForIdle()+    }++    @Test fun hintButtonReEnablesWhenItsCooldownEnds() {+        val end = System.currentTimeMillis() + 2_000+        val state = WordGameUiState(crosswordData = board, hintCooldownEnd = end)+        rule.setContent {+            DynamicTheme { WordGameScreen(state = state, actions = WordGameActions.Noop, onOpenGameCenter = {}, onOpenSettings = {}) }+        }+        if (System.currentTimeMillis() < end - 200) rule.onNodeWithContentDescription("Hint").assertIsNotEnabled()+        passWallClock(end + 100)+        rule.onNodeWithContentDescription("Hint").assertIsEnabled()+    }++    @Test fun competitiveCountdownRunsDownAndTimesOut() {+        var timedOut = false+        val actions = object : WordGameActions { override fun onCompetitiveTimeout() { timedOut = true } }+        val deadline = System.currentTimeMillis() + 2_500+        val state = WordGameUiState(+            crosswordData = board, gameMode = GameMode.COMPETITIVE,+            competitiveLevelNumber = 1, competitiveScore = 10, competitiveDeadline = deadline,+        )+        rule.setContent {+            DynamicTheme { WordGameScreen(state = state, actions = actions, onOpenGameCenter = {}, onOpenSettings = {}) }+        }+        passWallClock(deadline + 100)+        rule.onNodeWithText("00:00").assertExists()+        assertTrue(timedOut, "the screen's timer still fires at the deadline")+    }+}
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordFlightPlacementTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordFlightPlacementTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordFlightPlacementTest.ktindex 5527a2c0ee..b80ab86a13 100644--- a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordFlightPlacementTest.kt+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordFlightPlacementTest.kt@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.platform.LocalDensity@@ -43,8 +44,8 @@ class WordFlightPlacementTest {                             foundWords = emptySet(), revealedHints = emptySet(), actions = WordGameActions.Noop,                             showBonusWordsDialog = false, onDismissBonusWords = {}, bonusWords = emptySet(),                             wordWithDefinition = null, onDismissDefinition = {}, animatedWord = null,-                            animationProgress = Animatable(0f), wordBoxOffset = Offset.Zero, bonusButtonCenter = Offset.Zero, rootOffset = Offset.Zero,-                            animatedLetters = listOf(letter), scale = 1f,+                            animationProgress = remember { Animatable(0f) }, wordBoxOffset = { Offset.Zero }, bonusButtonCenter = { Offset.Zero }, rootOffset = Offset.Zero,+                            animatedLetters = listOf(letter), scale = { 1f },                         )                     }                 }@@ -93,9 +94,9 @@ class WordFlightPlacementTest {                         foundWords = emptySet(), revealedHints = emptySet(), actions = WordGameActions.Noop,                         showBonusWordsDialog = false, onDismissBonusWords = {}, bonusWords = emptySet(),                         wordWithDefinition = null, onDismissDefinition = {}, animatedWord = "ZOO",-                        animationProgress = Animatable(1f), wordBoxOffset = Offset(100f, 400f),-                        bonusButtonCenter = bonusCenterInRoot, rootOffset = rootOffset,-                        animatedLetters = emptyList(), scale = 1f,+                        animationProgress = remember { Animatable(1f) }, wordBoxOffset = { Offset(100f, 400f) },+                        bonusButtonCenter = { bonusCenterInRoot }, rootOffset = rootOffset,+                        animatedLetters = emptyList(), scale = { 1f },                     )                 }             }
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.ktindex 2aaaa11ab3..2086a9b4c3 100644--- a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.kt+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.kt@@ -223,7 +223,7 @@ class WordMakerComposeTest {                     letters = listOf(ChooserLetter(0, 'C'), ChooserLetter(1, 'A'), ChooserLetter(2, 'T')),                     tapToSpell = true, wheelSpacing = WheelSpacing.DEFAULT,                     onShuffle = {}, onWordSubmitted = { w, _ -> submitted = w },-                    onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> }, wordShakeTranslation = 0f,+                    onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },                 )             }         }@@ -242,7 +242,7 @@ class WordMakerComposeTest {                     letters = listOf(ChooserLetter(0, 'C'), ChooserLetter(1, 'A'), ChooserLetter(2, 'T')),                     tapToSpell = true, wheelSpacing = WheelSpacing.WIDE,                     onShuffle = { shuffled = true }, onWordSubmitted = { _, _ -> },-                    onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> }, wordShakeTranslation = 0f,+                    onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },                 )             }         }@@ -260,7 +260,7 @@ class WordMakerComposeTest {                     letters = listOf(ChooserLetter(0, 'D'), ChooserLetter(1, 'O'), ChooserLetter(2, 'G'), ChooserLetter(3, 'S')),                     tapToSpell = false, wheelSpacing = WheelSpacing.DEFAULT,                     onShuffle = {}, onWordSubmitted = { _, _ -> },-                    onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> }, wordShakeTranslation = 0f,+                    onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },                 )             }         }@@ -316,8 +316,8 @@ class WordMakerComposeTest {                         showHintDialog = true, onDismissHint = {}, crosswordData = board(), foundWords = emptySet(), revealedHints = emptySet(),                         actions = actions, showBonusWordsDialog = false, onDismissBonusWords = {}, bonusWords = emptySet(),                         wordWithDefinition = null, onDismissDefinition = {}, animatedWord = "CAT", animationProgress = progress,-                        wordBoxOffset = Offset.Zero, bonusButtonCenter = Offset(100f, 100f), rootOffset = Offset.Zero,-                        animatedLetters = listOf(AnimatedLetter('C', Offset.Zero, Offset(50f, 50f), letterProgress)), scale = 1f,+                        wordBoxOffset = { Offset.Zero }, bonusButtonCenter = { Offset(100f, 100f) }, rootOffset = Offset.Zero,+                        animatedLetters = listOf(AnimatedLetter('C', Offset.Zero, Offset(50f, 50f), letterProgress)), scale = { 1f },                     )                 }             }@@ -334,7 +334,7 @@ class WordMakerComposeTest {                     showHintDialog = false, onDismissHint = {}, crosswordData = board(), foundWords = emptySet(), revealedHints = emptySet(),                     actions = WordGameActions.Noop, showBonusWordsDialog = true, onDismissBonusWords = {}, bonusWords = setOf("DOG"),                     wordWithDefinition = null, onDismissDefinition = {}, animatedWord = null, animationProgress = animationProgress,-                    wordBoxOffset = Offset.Zero, bonusButtonCenter = Offset.Zero, rootOffset = Offset.Zero, animatedLetters = emptyList(), scale = 1f,+                    wordBoxOffset = { Offset.Zero }, bonusButtonCenter = { Offset.Zero }, rootOffset = Offset.Zero, animatedLetters = emptyList(), scale = { 1f },                 )             }         }@@ -532,7 +532,7 @@ class WordMakerNavAndDragTest {                     letters = listOf(ChooserLetter(0, 'C'), ChooserLetter(1, 'A'), ChooserLetter(2, 'T'), ChooserLetter(3, 'S')),                     tapToSpell = false, wheelSpacing = WheelSpacing.DEFAULT,                     onShuffle = {}, onWordSubmitted = { w, _ -> submitted = w },-                    onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> }, wordShakeTranslation = 0f,+                    onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },                 )             }         }