Modern Apps git

← Modern-Apps.git

solitaire: fix stack drag duplicates and clipping; animate drops (#owner-report)

Commit
31b0665be13118fbbeb7dcde022bf53abc866e17
Author
Vayun Mathur <[email protected]>
When
2026-11-12 20:44 UTC (23 days ago)
Parents
811fc6a
Symptom (owner report): dragging a card with cards on top of it left
every card above the grabbed one drawn in the source pile (a "fake
stack" left behind), while the dragged visual showed the full stack,
so those cards appeared twice; the dragged stack was also cut off at
the bottom. Drops snapped instantly, and a rejected drop just
reappeared in place.

Root causes:
- DraggableCard hid itself with a local `isDragging` flag, so only
  the grabbed card went invisible; the cards above it are separate
  DraggableCards that never knew they were being carried, while
  DragOverlay drew the whole carried list.
- DragOverlay was a child of each board, inside the screen's
  verticalScroll column, whose viewport clips; a long stack dragged
  low was cut off. zIndex only orders siblings, so it could not
  escape that clip.

Fix:
- DragInfo now records where the carried run lives (pileId +
  startIndex -> PileRange). Every DraggableCard hides itself when the
  drag's range covers its slot (matched on pile, index and card), so
  the whole carried run disappears from the source and nothing else
  does. Hidden cards stay laid out (the gesture keeps running) and
  are hidden from accessibility too.
- The stack under the finger is drawn by the top-level
  CardMotionLayer (outside the scroll column, above the board), once
  per card, opaque; the per-board DragOverlay is gone, so Klondike,
  FreeCell and Spider share it.
- endDrag hands the stack straight to a flight in the same update:
  an accepted drop is applied and flies from under the finger to the
  exact slot it now occupies; a rejected (or cancelled) drop flies
  back to where it was picked up. The cards stay hidden in their pile
  until the flight lands, so they reappear exactly once.
  tryMoveByDrag now returns the accepting target id.
- DragAndDrop.kt is now DraggableCard.kt (one public composable);
  AGENTS.md key files updated.

User-visible effect: a dragged run leaves the source pile, appears
once under the finger, is never clipped, and lands or returns with a
short animation.

Verification: new DragDropFlightTest (carried range, rejected drop
returns the whole stack home, accepted drop lands on the next slot);
DragAndViewModelTest lifecycle updated for drop flights; new Compose
CardMotionLayerTest: a drag leaves no duplicate card in the source
pile while dragging, the tap-move flight target equals the slot the
column draws the card at, and a second tap during a flight does not
cancel the first move. :games:solitaire:testDevUnitTest in the
container build.

Diff

games/solitaire/AGENTS.md
diff --git a/games/solitaire/AGENTS.md b/games/solitaire/AGENTS.mdindex 7b5a5b5b58..2103be8d91 100644--- a/games/solitaire/AGENTS.md+++ b/games/solitaire/AGENTS.md@@ -36,6 +36,7 @@ _Install: ./install games/solitaire (dev by default)._ - com/vayunmathur/games/solitaire/platform/SolitaireSpiderOps.kt - com/vayunmathur/games/solitaire/platform/SolitairePyramidOps.kt - com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt+- com/vayunmathur/games/solitaire/platform/SolitaireFlight.kt — in-flight moves (visual only; game state updates first) - com/vayunmathur/games/solitaire/platform/SolitaireAchievementsManager.kt - com/vayunmathur/games/solitaire/platform/AppBackupAgent.kt ### ui/ — boards + shared card/drag components@@ -47,10 +48,14 @@ _Install: ./install games/solitaire (dev by default)._ - com/vayunmathur/games/solitaire/ui/SpiderBoard.kt - com/vayunmathur/games/solitaire/ui/PyramidBoard.kt - com/vayunmathur/games/solitaire/ui/TableauColumn.kt+- com/vayunmathur/games/solitaire/ui/FreeCellTableauColumn.kt - com/vayunmathur/games/solitaire/ui/FoundationSlot.kt - com/vayunmathur/games/solitaire/ui/FreeCellSlot.kt - com/vayunmathur/games/solitaire/ui/CardView.kt-- com/vayunmathur/games/solitaire/ui/DragAndDrop.kt+- com/vayunmathur/games/solitaire/ui/DraggableCard.kt — pick-up/tap source; hidden while it is carried or in flight+- com/vayunmathur/games/solitaire/ui/DropTarget.kt+- com/vayunmathur/games/solitaire/ui/CardMotionLayer.kt — top-level layer drawing the drag + every flight (outside the scroll clip)+- com/vayunmathur/games/solitaire/ui/PileLayout.kt — card slot offsets shared by piles (draw) and flights (land) - com/vayunmathur/games/solitaire/ui/GameActionBar.kt - com/vayunmathur/games/solitaire/ui/GameModeDisplayName.kt - com/vayunmathur/games/solitaire/ui/WinOverlay.kt
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.ktindex 1ec5d00967..a0d4a17a46 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt@@ -49,22 +49,23 @@ private fun tableauFaceUp(state: SolitaireUiState, col: Int): List<Card>? = when /** A foundation only ever accepts a drag that carries the single top card. */ internal fun SolitaireViewModel.isSingleCardDrag(sourceId: String): Boolean = draggedCards(sourceId).size == 1 +/**+ * Drops the stack from [sourceId] on the first candidate target that accepts it. Returns the+ * accepting target's id, or null when no target took the move (nothing changed).+ */ internal fun SolitaireViewModel.tryMoveByDragImpl(     sourceId: String,     dropOffset: Offset,     cardSize: IntSize = IntSize.Zero,-) {-    val mode = uiStateInternal.value.gameMode ?: return+): String? {+    val mode = uiStateInternal.value.gameMode ?: return null+    if (mode == GameMode.PYRAMID) return null // Pyramid is tap-based, not drag-based.     for (targetId in candidateDropTargets(dropOffset, cardSize)) {         val before = uiStateInternal.value-        when (mode) {-            GameMode.KLONDIKE -> handleKlondikeDropImpl(sourceId, targetId)-            GameMode.SPIDER -> handleSpiderDropImpl(sourceId, targetId)-            GameMode.FREECELL -> handleFreeCellDropImpl(sourceId, targetId)-            GameMode.PYRAMID -> return // Pyramid is tap-based, not drag-based.-        }-        if (uiStateInternal.value !== before) return+        applyDrop(sourceId, targetId)+        if (uiStateInternal.value !== before) return targetId     }+    return null }  /**@@ -117,7 +118,15 @@ internal fun SolitaireViewModel.startDragImpl(sourceId: String, startPos: Offset         dragInfoInternal.value = null         return false     }-    dragInfoInternal.value = DragInfo(range.cards, sourceId, startPos, startPos, cardSize)+    dragInfoInternal.value = DragInfo(+        cards = range.cards,+        sourceId = sourceId,+        offset = startPos,+        startPos = startPos,+        cardSize = cardSize,+        pileId = range.pileId,+        startIndex = range.start,+    )     return true } @@ -125,15 +134,34 @@ internal fun SolitaireViewModel.updateDragImpl(offset: Offset) {     dragInfoInternal.update { it?.copy(offset = offset) } } +/**+ * Drops the carried stack. An accepted drop is applied at once and the stack flies from under+ * the finger to the slot it now occupies; a rejected one flies back to where it was picked up.+ * Either way the stack is handed from the drag to a flight in the same update, so the cards+ * are hidden in their pile until that flight lands and reappear there exactly once.+ */ internal fun SolitaireViewModel.endDragImpl(dropOffset: Offset, cardSize: IntSize) {     val info = dragInfoInternal.value ?: return     // Use the cardSize recorded at drag start (finger owns that card), with the     // current drop size as fallback so call sites lacking a size still resolve.     val effectiveSize = if (cardSize.width > 0 && cardSize.height > 0) cardSize else info.cardSize-    tryMoveByDrag(info.sourceId, dropOffset, effectiveSize)+    val targetId = tryMoveByDrag(info.sourceId, dropOffset, effectiveSize)+    if (targetId != null) {+        launchFlight(info.cards, info.offset, targetId, info.cardSize)+    } else {+        returnCarriedCards(info)+    }     dragInfoInternal.value = null } +/** The gesture was cancelled: the stack goes back where it came from. */ internal fun SolitaireViewModel.cancelDragImpl() {+    dragInfoInternal.value?.let { returnCarriedCards(it) }     dragInfoInternal.value = null }++/** Flies an undropped stack home, if it is still where it was picked up. */+private fun SolitaireViewModel.returnCarriedCards(info: DragInfo) {+    if (sourceRange(info.sourceId) != info.range) return+    launchReturnFlight(info.range, info.offset, info.startPos, info.cardSize)+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.ktindex d08f74210b..dcd5cb2528 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.kt@@ -39,7 +39,7 @@ fun SolitaireViewModel.tryMoveByDrag(     sourceId: String,     dropOffset: androidx.compose.ui.geometry.Offset,     cardSize: androidx.compose.ui.unit.IntSize = androidx.compose.ui.unit.IntSize.Zero,-) = tryMoveByDragImpl(sourceId, dropOffset, cardSize)+): String? = tryMoveByDragImpl(sourceId, dropOffset, cardSize)  internal fun SolitaireViewModel.newKlondikeGameImpl(config: GameConfig) {     val deck = createShuffledDeck()
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.ktindex e312a4af7e..663e076d1a 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt@@ -23,13 +23,24 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update +/**+ * The stack under the finger. [offset] is the leading card's current top-left and [startPos]+ * where it was picked up, both in root coordinates. The carried cards stay in game state at+ * [pileId] from [startIndex] until the drop, and the board hides them there so the only copy+ * on screen is the one the motion layer draws under the finger.+ */ data class DragInfo(     val cards: List<Card>,     val sourceId: String,     val offset: Offset = Offset.Zero,     val startPos: Offset = Offset.Zero,-    val cardSize: IntSize = IntSize.Zero-)+    val cardSize: IntSize = IntSize.Zero,+    val pileId: String = "",+    val startIndex: Int = 0,+) {+    /** Where the carried cards live while they are carried. */+    val range: PileRange get() = PileRange(pileId, startIndex, cards)+}  class SolitaireViewModel(application: Application) : AndroidViewModel(application), SolitaireActions {     internal val uiStateInternal = MutableStateFlow(SolitaireUiState())
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardMotionLayer.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardMotionLayer.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardMotionLayer.ktindex 648e9e7111..ea14b760bf 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardMotionLayer.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardMotionLayer.kt@@ -33,7 +33,8 @@ private const val FAST_FLIGHT_MILLIS = 110 private const val MOTION_LAYER_Z = 1f  /**- * Every card in motion, drawn in one layer laid over the whole game screen.+ * Every card in motion — the stack under the finger and every flight — drawn in one layer laid+ * over the whole game screen.  *  * It lives outside the board's scrolling column rather than inside a pile, so nothing in motion  * is clipped by a pile's bounds or by the scroll viewport, and it works in root coordinates so a@@ -47,6 +48,7 @@ private const val MOTION_LAYER_Z = 1f @Composable fun CardMotionLayer(actions: SolitaireActions, modifier: Modifier = Modifier) {     val flights by actions.flights.collectAsState()+    val drag by actions.dragInfo.collectAsState()     var origin by remember { mutableStateOf(Offset.Zero) }     Box(         modifier = modifier@@ -57,6 +59,14 @@ fun CardMotionLayer(actions: SolitaireActions, modifier: Modifier = Modifier) {         flights.forEach { flight ->             key(flight.id) { FlyingCards(flight, actions) { origin } }         }+        // The stack under the finger, drawn last so it passes over everything else.+        drag?.let { carried ->+            CarriedCards(+                cards = carried.cards,+                cardSize = carried.cardSize,+                modifier = Modifier.offset { (carried.offset - origin).round() },+            )+        }     } } 
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DraggableCard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DraggableCard.ktsimilarity index 59%rename from games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.ktrename to games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DraggableCard.ktindex 9cf0c1c740..1d84d6e278 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DraggableCard.kt@@ -3,8 +3,6 @@ package com.vayunmathur.games.solitaire.ui import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.offset import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -18,18 +16,21 @@ import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInRoot-import androidx.compose.ui.unit.Dp-import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.semantics.hideFromAccessibility+import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.IntSize-import androidx.compose.ui.unit.dp-import androidx.compose.ui.zIndex import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.platform.SolitaireActions  /**- * A card the player can pick up. [sourceId] identifies the pile position it comes from;- * the cards the drag actually carries are derived from live game state by the view model,- * so nothing here can go stale between recompositions.+ * A card the player can pick up. [sourceId] identifies the pile position it comes from; the+ * cards a drag or tap actually carries are derived from live game state by the view model, so+ * nothing here can go stale between recompositions.+ *+ * [pileId] and [index] locate the card in its pile. While the card is part of the stack under+ * the finger, or of a flight still travelling to (or back to) this slot, it is laid out but not+ * drawn — the motion layer draws it instead — so every card is on screen exactly once. It stays+ * laid out so the gesture that carries it keeps running and its position stays registered.  */ @Composable fun DraggableCard(@@ -41,14 +42,13 @@ fun DraggableCard(     modifier: Modifier = Modifier,     content: @Composable () -> Unit ) {-    var isDragging by remember { mutableStateOf(false) }     var dragOffset by remember { mutableStateOf(Offset.Zero) }     var startPos by remember { mutableStateOf(Offset.Zero) }     var cardSize by remember { mutableStateOf(IntSize.Zero) }-    // Hidden while a flight carries this card into (or back to) this slot, so the-    // flight — not a copy underneath — is what the player sees travelling.+    val drag by actions.dragInfo.collectAsState()     val flights by actions.flights.collectAsState()-    val isFlying = flights.any { it.hides.covers(pileId, index, card) }+    val hidden = drag?.range?.covers(pileId, index, card) == true ||+        flights.any { it.hides.covers(pileId, index, card) }     // Feeds the animated auto-complete its launch points; unlaid cards (the stock)     // stay absent and fly instantly instead.     LaunchedEffect(card, startPos, cardSize) {@@ -70,7 +70,7 @@ fun DraggableCard(                 detectDragGestures(                     onDragStart = {                         dragOffset = Offset.Zero-                        isDragging = actions.startDrag(sourceId, startPos, cardSize)+                        actions.startDrag(sourceId, startPos, cardSize)                     },                     onDrag = { change, dragAmount ->                         change.consume()@@ -80,61 +80,18 @@ fun DraggableCard(                     onDragEnd = {                         val center = Offset(cardSize.width / 2f, cardSize.height / 2f)                         actions.endDrag(startPos + dragOffset + center, cardSize)-                        isDragging = false                         dragOffset = Offset.Zero                     },                     onDragCancel = {                         actions.cancelDrag()-                        isDragging = false                         dragOffset = Offset.Zero                     }                 )             }-            .graphicsLayer {-                if (isDragging || isFlying) alpha = 0f-            }+            .graphicsLayer { if (hidden) alpha = 0f }+            // The copy in motion is the one a screen reader should find, not this one.+            .then(if (hidden) Modifier.semantics { hideFromAccessibility() } else Modifier)     ) {         content()     } }--@Composable-fun DragOverlay(-    actions: SolitaireActions,-    cardWidth: Dp,-    cardHeight: Dp,-    modifier: Modifier = Modifier-) {-    val dragInfo by actions.dragInfo.collectAsState()-    var overlayPos by remember { mutableStateOf(Offset.Zero) }--    val faceUpOverlap = 22.dp--    Box(-        modifier = modifier-            .fillMaxSize()-            .zIndex(Float.MAX_VALUE)-            .onGloballyPositioned { coords ->-                overlayPos = coords.positionInRoot()-            }-    ) {-        val info = dragInfo ?: return@Box-        val relX = (info.offset.x - overlayPos.x).toInt()-        val relY = (info.offset.y - overlayPos.y).toInt()--        Box(-            modifier = Modifier-                .offset { IntOffset(relX, relY) }-                .graphicsLayer { alpha = 0.9f }-        ) {-            info.cards.forEachIndexed { index, card ->-                CardFace(-                    card = card,-                    modifier = Modifier.offset(y = faceUpOverlap * index),-                    cardWidth = cardWidth,-                    cardHeight = cardHeight-                )-            }-        }-    }-}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.ktindex 9c0918f5f4..e170c2ced2 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt@@ -53,7 +53,6 @@ fun FreeCellBoard(state: FreeCellState, actions: SolitaireActions, modifier: Mod             }         } -        DragOverlay(actions, cardWidth, cardHeight)         }     } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.ktindex c669e1b2b7..c189dba581 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt@@ -126,7 +126,6 @@ fun KlondikeBoard(state: KlondikeState, actions: SolitaireActions, modifier: Mod             }         } -        DragOverlay(actions, cardWidth, cardHeight)         }     } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.ktindex e3f0679b3f..835ea5e16a 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.kt@@ -70,7 +70,6 @@ fun SpiderBoard(state: SpiderState, actions: SolitaireActions, modifier: Modifie             }         } -        DragOverlay(actions, cardWidth, cardHeight)         }     } }
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.ktindex c6c8bf49e5..ded9eab892 100644--- a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.kt+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.kt@@ -63,10 +63,16 @@ class DragAndViewModelTest {         val k = vm.uiState.value.klondike!!         assertTrue(k.waste.isEmpty())         assertEquals(queen, k.tableauPiles[0].faceUp.last())-        // Cancel clears without moving.+        // The accepted drop flies the queen from under the finger to her new slot.+        val landing = vm.flights.value.single()+        assertEquals(FlightTarget.Slot("tableau_0", 0, 1), landing.target)+        assertEquals(Offset(50f, 60f), landing.from)+        vm.landFlight(landing.id)+        // Cancel clears without moving, flying the card back home.         assertTrue(vm.startDrag("tableau_0_1", Offset.Zero, IntSize(60, 84)))         vm.cancelDrag()         assertNull(vm.dragInfo.value)+        assertEquals(FlightTarget.Point(Offset.Zero), vm.flights.value.single().target)         assertEquals(1, vm.uiState.value.klondike!!.moveCount)         // EndDrag with nothing in flight is a no-op.         vm.endDrag(Offset.Zero, IntSize.Zero)
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragDropFlightTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragDropFlightTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragDropFlightTest.ktnew file mode 100644index 0000000000..4fd7b6b867--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragDropFlightTest.kt@@ -0,0 +1,88 @@+package com.vayunmathur.games.solitaire.platform++import android.app.Application+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.unit.IntSize+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Stack drags: the carried range, and the hand-off to a landing or returning flight. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class DragDropFlightTest {+    private val app = ApplicationProvider.getApplicationContext<Application>()+    private val king = Card(Suit.SPADES, Rank.KING)+    private val queen = Card(Suit.HEARTS, Rank.QUEEN)+    private val jack = Card(Suit.CLUBS, Rank.JACK)+    private val size = IntSize(60, 90)++    private fun vm(vararg piles: TableauPile): SolitaireViewModel {+        val vm = SolitaireViewModel(app)+        vm.uiStateInternal.value = SolitaireUiState(+            gameMode = GameMode.KLONDIKE,+            klondike = KlondikeState(tableauPiles = piles.toList() + List(7 - piles.size) { TableauPile() }),+        )+        return vm+    }++    @Test fun dragCarriesTheRangeAboveTheGrabbedCard() {+        val vm = vm(TableauPile(faceDown = listOf(Card(Suit.CLUBS, Rank.TWO)), faceUp = listOf(king, queen, jack)))+        assertTrue(vm.startDrag("tableau_0_1", Offset(5f, 30f), size))+        val range = vm.dragInfo.value!!.range+        assertEquals(PileRange("tableau_0", 1, listOf(queen, jack)), range)+        // Every carried card is hidden in the source; the one beneath is not.+        assertTrue(range.covers("tableau_0", 1, queen))+        assertTrue(range.covers("tableau_0", 2, jack))+        assertFalse(range.covers("tableau_0", 0, king))+    }++    @Test fun rejectedDropFliesTheWholeStackBackHome() {+        val vm = vm(TableauPile(faceUp = listOf(king, queen, jack)))+        val home = Offset(5f, 30f)+        assertTrue(vm.startDrag("tableau_0_1", home, size))+        vm.updateDrag(Offset(200f, 300f))+        val before = vm.uiState.value+        vm.endDrag(Offset(230f, 345f), size) // no drop targets at all+        assertNull(vm.dragInfo.value)+        assertEquals(before, vm.uiState.value)+        val flight = vm.flights.value.single()+        assertEquals(listOf(queen, jack), flight.cards)+        assertEquals(Offset(200f, 300f), flight.from)+        assertEquals(FlightTarget.Point(home), flight.target)+        assertEquals(PileRange("tableau_0", 1, listOf(queen, jack)), flight.hides)+        vm.landFlight(flight.id)+        assertTrue(vm.flights.value.isEmpty())+    }++    @Test fun acceptedStackDropLandsOnTheDestinationsNextSlot() {+        val redKing = Card(Suit.DIAMONDS, Rank.KING)+        val vm = vm(+            TableauPile(faceUp = listOf(redKing, Card(Suit.SPADES, Rank.QUEEN), Card(Suit.HEARTS, Rank.JACK))),+            TableauPile(faceUp = listOf(Card(Suit.HEARTS, Rank.KING))),+        )+        vm.dropTargets["tableau_1"] = Rect(100f, 0f, 160f, 90f)+        assertTrue(vm.startDrag("tableau_0_1", Offset(5f, 30f), size))+        vm.updateDrag(Offset(110f, 20f))+        vm.endDrag(Offset(140f, 65f), size)+        assertEquals(1, vm.uiState.value.klondike!!.tableauPiles[0].faceUp.size)+        val flight = vm.flights.value.single()+        assertEquals(Offset(110f, 20f), flight.from)+        assertEquals(FlightTarget.Slot("tableau_1", 0, 1), flight.target)+        assertEquals(flight.cards, vm.uiState.value.klondike!!.tableauPiles[1].faceUp.drop(1))+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/CardMotionLayerTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/CardMotionLayerTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/CardMotionLayerTest.ktnew file mode 100644index 0000000000..d219c76e4e--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/CardMotionLayerTest.kt@@ -0,0 +1,169 @@+package com.vayunmathur.games.solitaire.ui++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.semantics.SemanticsProperties+import androidx.compose.ui.test.SemanticsMatcher+import androidx.compose.ui.test.click+import androidx.compose.ui.test.hasAnyAncestor+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import com.vayunmathur.games.solitaire.platform.DragInfo+import com.vayunmathur.games.solitaire.platform.FlightTarget+import com.vayunmathur.games.solitaire.platform.SolitaireViewModel+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+import org.robolectric.annotation.Config++/** The board and the motion layer together: each card on screen once, flights on the board's slots. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CardMotionLayerTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val app = ApplicationProvider.getApplicationContext<Application>()+    private val king = Card(Suit.SPADES, Rank.KING)+    private val queen = Card(Suit.HEARTS, Rank.QUEEN)+    private val jack = Card(Suit.CLUBS, Rank.JACK)++    /** Text nodes a sighted player would see: not inside a card hidden for being in motion. */+    private fun visibleCount(text: String): Int = composeRule.onAllNodes(+        hasText(text) and !hasAnyAncestor(SemanticsMatcher.keyIsDefined(SemanticsProperties.HideFromAccessibility)),+        useUnmergedTree = true,+    ).fetchSemanticsNodes().size++    @Test+    fun dragHidesEveryCarriedCardInTheSourceAndDrawsEachOnce() {+        val actions = RecordingActions()+        val pile = TableauPile(faceUp = listOf(king, queen, jack))+        composeRule.setContent {+            Box {+                TableauColumn(pile = pile, columnIndex = 0, actions = actions)+                CardMotionLayer(actions)+            }+        }+        listOf("K", "Q", "J").forEach { assertEquals(1, visibleCount(it), it) }+        // Grab the queen: the queen and the jack above her are carried.+        actions.dragFlow.value = DragInfo(+            cards = listOf(queen, jack),+            sourceId = "tableau_0_1",+            offset = Offset(300f, 400f),+            startPos = Offset.Zero,+            cardSize = IntSize(60, 84),+            pileId = "tableau_0",+            startIndex = 1,+        )+        composeRule.waitForIdle()+        // No stack left behind in the source, no duplicate under the finger.+        listOf("K", "Q", "J").forEach { assertEquals(1, visibleCount(it), it) }+        actions.dragFlow.value = null+        composeRule.waitForIdle()+        listOf("K", "Q", "J").forEach { assertEquals(1, visibleCount(it), it) }+    }++    @Test+    fun tapMoveFlightLandsExactlyOnTheSlotTheBoardDrawsTheCardAt() {+        val vm = SolitaireViewModel(app)+        val seven = Card(Suit.HEARTS, Rank.SEVEN)+        vm.uiStateInternal.value = SolitaireUiState(+            gameMode = GameMode.KLONDIKE,+            klondike = KlondikeState(+                waste = listOf(seven),+                tableauPiles = listOf(+                    TableauPile(+                        faceDown = listOf(Card(Suit.CLUBS, Rank.TWO), Card(Suit.CLUBS, Rank.THREE)),+                        faceUp = listOf(Card(Suit.SPADES, Rank.EIGHT)),+                    ),+                ) + List(6) { TableauPile() },+            ),+        )+        composeRule.setContent {+            val ui by vm.uiState.collectAsState()+            Box {+                TableauColumn(ui.klondike!!.tableauPiles[0], 0, vm, Modifier, 50.dp, 75.dp)+                CardMotionLayer(vm)+            }+        }+        composeRule.mainClock.autoAdvance = false+        composeRule.runOnIdle { assertTrue(vm.requestAutoMove("waste", Offset(400f, 10f), IntSize(50, 75))) }+        val slot = vm.flights.value.single().target as FlightTarget.Slot+        assertEquals(FlightTarget.Slot("tableau_0", 2, 1), slot)+        composeRule.mainClock.autoAdvance = true+        composeRule.waitForIdle()+        assertTrue(vm.flights.value.isEmpty(), "flight never landed")+        val pileOrigin = vm.dropTargets.getValue("tableau_0").topLeft+        val target = with(composeRule.density) { pileSlotPosition(pileOrigin, slot) }+        // Where the column actually drew the seven after the move.+        val drawn = vm.cardPositions.getValue(seven)+        assertEquals(drawn.x, target.x, absoluteTolerance = 1f)+        assertEquals(drawn.y, target.y, absoluteTolerance = 1f)+    }++    @Test+    fun secondTapDuringAFlightDoesNotCancelTheFirstMove() {+        val vm = SolitaireViewModel(app)+        val heartsAce = Card(Suit.HEARTS, Rank.ACE)+        val spadesAce = Card(Suit.SPADES, Rank.ACE)+        vm.uiStateInternal.value = SolitaireUiState(+            gameMode = GameMode.KLONDIKE,+            klondike = KlondikeState(+                waste = listOf(heartsAce),+                tableauPiles = listOf(TableauPile(faceUp = listOf(spadesAce))) + List(6) { TableauPile() },+            ),+        )+        composeRule.setContent {+            val ui by vm.uiState.collectAsState()+            Box {+                KlondikeBoard(ui.klondike!!, vm)+                CardMotionLayer(vm)+            }+        }+        composeRule.waitForIdle()+        val wasteAt = vm.cardPositions.getValue(heartsAce)+        val tableauAt = vm.cardPositions.getValue(spadesAce)+        val inset = Offset(10f, 10f)+        composeRule.mainClock.autoAdvance = false+        composeRule.onRoot().performTouchInput { click(wasteAt + inset) }+        composeRule.mainClock.advanceTimeBy(FRAME_MS * 3)+        assertEquals(1, vm.flights.value.size, "first tap did not fly")+        composeRule.onRoot().performTouchInput { click(tableauAt + inset) }+        composeRule.mainClock.advanceTimeBy(FRAME_MS * 3)+        // Both in the air, both applied.+        assertEquals(2, vm.flights.value.size)+        val mid = vm.uiState.value.klondike!!+        assertEquals(listOf(heartsAce), mid.foundations[0])+        assertEquals(listOf(spadesAce), mid.foundations[2])+        assertEquals(2, visibleCount("A")) // the two flying copies; their foundation tops are hidden+        composeRule.mainClock.autoAdvance = true+        composeRule.waitForIdle()+        assertTrue(vm.flights.value.isEmpty())+        assertEquals(mid, vm.uiState.value.klondike)+        assertEquals(2, visibleCount("A")) // each ace on its foundation, once+    }++    private companion object {+        const val FRAME_MS = 16L+    }+}