From 368992cb5f6b1dfd02351ac5fa1930848a3e7c55 Mon Sep 17 00:00:00 2001 From: Matt Batchelder Date: Thu, 3 Dec 2026 07:16:21 -0600 Subject: [PATCH 1/3] Add play cards for each unique game lineup --- changes/play-cards.md | 4 + docs/STATUS.md | 8 + e2e/playcards.spec.ts | 64 ++++ src/components/HalfCourt.tsx | 335 +++++++++++++++++ src/components/PlayCardsModal.test.tsx | 209 +++++++++++ src/components/PlayCardsModal.tsx | 393 ++++++++++++++++++++ src/data/repo.ts | 26 +- src/data/types.ts | 31 ++ src/data/validate.test.ts | 11 + src/data/validate.ts | 16 + src/domain/playCards.test.ts | 262 +++++++++++++ src/domain/playCards.ts | 409 ++++++++++++++++++++ src/screens/GameDayScreen.test.tsx | 25 +- src/screens/GameDayScreen.tsx | 23 +- src/screens/PlanScreen.test.tsx | 15 + src/screens/PlanScreen.tsx | 26 +- src/styles.css | 494 +++++++++++++++++++++++++ 17 files changed, 2343 insertions(+), 8 deletions(-) create mode 100644 changes/play-cards.md create mode 100644 e2e/playcards.spec.ts create mode 100644 src/components/HalfCourt.tsx create mode 100644 src/components/PlayCardsModal.test.tsx create mode 100644 src/components/PlayCardsModal.tsx create mode 100644 src/domain/playCards.test.ts create mode 100644 src/domain/playCards.ts diff --git a/changes/play-cards.md b/changes/play-cards.md new file mode 100644 index 0000000..c98219a --- /dev/null +++ b/changes/play-cards.md @@ -0,0 +1,4 @@ +--- +type: new +--- +Play cards for every lineup: tap Play cards on the Plan or Game Day screen to swipe through Offense (1-2-2 / 2-2-1), Defense (2-3 Zone, 3-2 Zone, Box & 1), and Inbounding Stack (with Left/Right lane, toggleable cut arrows, and Play all / Step 1→4 animation), drag players freely, and tap Reset to snap back to standard spacing. diff --git a/docs/STATUS.md b/docs/STATUS.md index 2ade945..634af9d 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -148,6 +148,14 @@ Fixed on 2026-11-08: quick taps on the practice length and drill minutes stepper Tests: `src/domain/practice.test.ts` (with property tests for team splits and dragging), `src/data/practice.test.ts`, `src/screens/Practice.test.tsx`, and `e2e/practice.spec.ts` (WebKit at 375×667 with a wide font). Help topic **Planning practices**. +## 11b. Game play cards + +| ID | Status | Notes | +|----|--------|-------| +| PC1 | ✅ 📱 | **Play cards** button inline with **On court** on both the Plan (Segments view) and Game Day screens (`src/components/PlayCardsModal.tsx`, `src/components/HalfCourt.tsx`), adding zero vertical height on Game Day. Opens a fullscreen half-court deck (basket at top) for each unique 5-player lineup (`lineupKey` in `src/domain/playCards.ts`), stored in the optional unindexed `playCards` field on games (included in backups and Coach ↔ Assistant handoffs). | +| PC2 | ✅ 📱 | Three cards in order: **Offense** (`1-2-2` / `2-2-1` auto-picked from lineup positions, with formation toggle), **Defense** (`2-3 Zone` default, plus `3-2 Zone` and `Box & 1`), and **Inbounding Stack** (Center defaults to baseline inbounder; 4 stack players single-file starting at the 3rd lane hash mark, with Left/Right lane mirroring). Every player token shows name, jersey/position, and drags freely anywhere on the court. Every card has a **↺ Reset** button that snaps players back to default spacing for whiteboard use. | +| PC3 | ✅ 📱 | **Inbounding Stack** annotations and animation: toggleable directional cut arrows (`1` away from basket, `2` toward basket, `3` forward to inbounder, `4` pop back), recomputed dynamically when players are dragged or mirrored; **▶ Play all** and **Step 1→4** animation modes. Swipe left/right between cards; swiping left past the last card (or tapping **Done**) returns to the lineup screen. | + ## 12. Documentation and help | ID | Status | Notes | diff --git a/e2e/playcards.spec.ts b/e2e/playcards.spec.ts new file mode 100644 index 0000000..85bd35f --- /dev/null +++ b/e2e/playcards.spec.ts @@ -0,0 +1,64 @@ +import { expect, test } from '@playwright/test'; + +test.describe('Play cards on iPhone', () => { + test.use({ viewport: { width: 402, height: 874 } }); + + test('opens play cards from Plan and Game Day, switches formations, animates stack, and persists per unique lineup', async ({ + page, + }) => { + await page.goto('./'); + await page.getByRole('button', { name: 'Load demo team' }).click(); + await page.getByRole('radio', { name: 'Games' }).click(); + await page.getByRole('button', { name: '+ New game' }).click(); + await page.getByRole('button', { name: 'Generate plan' }).click(); + + // Open Play Cards from Plan screen (Q1 · 1 of 2) + await page.getByRole('button', { name: 'Play cards' }).click(); + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole('heading', { name: 'Offense' })).toBeVisible(); + await expect(dialog.locator('[data-player-token]')).toHaveCount(5); + + // Move to Defense, switch to Box & 1, then Reset stays on Box & 1 + await dialog.getByRole('button', { name: 'Next ›' }).click(); + await expect(dialog.getByRole('heading', { name: 'Defense' })).toBeVisible(); + await dialog.getByRole('radio', { name: 'Box & 1' }).click(); + await expect(dialog.getByRole('radio', { name: 'Box & 1' })).toBeChecked(); + + // Move to Inbounding Stack: verify arrows toggle, left/right side, and step animation + await dialog.getByRole('button', { name: 'Next ›' }).click(); + await expect(dialog.getByRole('heading', { name: 'Inbounding Stack' })).toBeVisible(); + await expect(dialog.getByTestId('stack-arrow-1')).toBeVisible(); + await dialog.getByRole('button', { name: 'Arrows: On' }).click(); + await expect(dialog.getByTestId('stack-arrow-1')).toHaveCount(0); + await dialog.getByRole('button', { name: 'Arrows: Off' }).click(); + await expect(dialog.getByTestId('stack-arrow-1')).toBeVisible(); + + await dialog.getByRole('radio', { name: 'Left lane' }).click(); + await expect(dialog.getByRole('radio', { name: 'Left lane' })).toBeChecked(); + + // Step through 1 -> 2 -> Play all -> Reset + await dialog.getByRole('button', { name: 'Step 1→4' }).click(); + await expect(dialog.getByText(/1\..*Away from basket/)).toBeVisible(); + await dialog.getByRole('button', { name: '▶ Play all' }).click(); + await expect(dialog.getByRole('button', { name: '↺ Stack' })).toBeVisible(); + await dialog.getByRole('button', { name: '↺ Reset' }).click(); + await expect(dialog.getByRole('button', { name: '▶ Play all' })).toBeVisible(); + + // Return to Plan screen via Done button at end of deck + await dialog.getByRole('button', { name: 'Done' }).last().click(); + await expect(dialog).toBeHidden(); + + // Start game and verify the exact same Q1 · 1 of 2 lineup still has Box & 1 and Left lane saved! + await page.getByRole('button', { name: 'Start game' }).click(); + await expect(page.getByRole('heading', { name: 'Q1 · 1 of 2' })).toBeVisible(); + await page.getByRole('button', { name: 'Play cards' }).click(); + await expect(dialog).toBeVisible(); + await dialog.getByRole('button', { name: 'Next ›' }).click(); + await expect(dialog.getByRole('radio', { name: 'Box & 1' })).toBeChecked(); + await dialog.getByRole('button', { name: 'Next ›' }).click(); + await expect(dialog.getByRole('radio', { name: 'Left lane' })).toBeChecked(); + await dialog.getByRole('button', { name: 'Done' }).last().click(); + await expect(dialog).toBeHidden(); + }); +}); diff --git a/src/components/HalfCourt.tsx b/src/components/HalfCourt.tsx new file mode 100644 index 0000000..7b6718e --- /dev/null +++ b/src/components/HalfCourt.tsx @@ -0,0 +1,335 @@ +import { useId, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react'; +import type { CourtPoint, Player, Position, StackSide } from '../data/types'; +import { + COURT, + clampPoint, + type StackMove, + type StackPlan, +} from '../domain/playCards'; +import type { Lineup, PlayerId } from '../engine'; + +interface HalfCourtProps { + lineup: Lineup; + byId: Map; + positions: Position[]; + coords: Record; + /** Whether players may be placed behind the baseline (true on the Stack card). */ + allowBaseline: boolean; + readOnly?: boolean; + /** Stack card extras: movement arrows, inbounder badge, and step animation state. */ + stackSide?: StackSide; + stackPlan?: StackPlan; + showAnnotations?: boolean; + animStage?: 0 | 1 | 2 | 3 | 4 | 'all'; + onDragStart?: () => void; + onMove: (playerId: PlayerId, point: CourtPoint) => void; +} + +function arrowPath(move: StackMove): string { + const { from, to, control } = move; + if (control) return `M ${from.x} ${from.y} Q ${control.x} ${control.y} ${to.x} ${to.y}`; + return `M ${from.x} ${from.y} L ${to.x} ${to.y}`; +} + +/** Label point for the small 1–4 step badge along a movement arrow. */ +function badgePoint(move: StackMove): CourtPoint { + const { from, to, control } = move; + if (control) { + // Midpoint of quadratic Bézier at t = 0.5 + return { + x: 0.25 * from.x + 0.5 * control.x + 0.25 * to.x, + y: 0.25 * from.y + 0.5 * control.y + 0.25 * to.y, + }; + } + return { + x: from.x + (to.x - from.x) * 0.58, + y: from.y + (to.y - from.y) * 0.58, + }; +} + +/** + * Interactive half-court diagram with the basket at the top. Players can be + * freely dragged anywhere inside the court bounds with touch or mouse. + */ +export function HalfCourt({ + lineup, + byId, + positions, + coords, + allowBaseline, + readOnly = false, + stackSide, + stackPlan, + showAnnotations = false, + animStage = 0, + onDragStart, + onMove, +}: HalfCourtProps) { + const stageRef = useRef(null); + const markerId = useId(); + const [dragging, setDragging] = useState<{ playerId: PlayerId; point: CourtPoint } | null>(null); + const draggingRef = useRef<{ playerId: PlayerId; point: CourtPoint } | null>(null); + + const shortPos = (positionId: string | null) => + positionId === null ? '' : (positions.find((p) => p.id === positionId)?.short ?? positionId); + + const pointFromPointer = (clientX: number, clientY: number): CourtPoint | null => { + const rect = stageRef.current?.getBoundingClientRect(); + if (!rect || rect.width === 0 || rect.height === 0) return null; + const x = ((clientX - rect.left) / rect.width) * 100; + const y = ((clientY - rect.top) / rect.height) * 100; + return clampPoint({ x, y }, allowBaseline); + }; + + const handlePointerDown = (playerId: PlayerId) => (e: PointerEvent) => { + e.stopPropagation(); + if (readOnly || (e.pointerType === 'mouse' && e.button !== 0)) return; + e.preventDefault(); + e.currentTarget.setPointerCapture?.(e.pointerId); + onDragStart?.(); + const start = coords[playerId] ?? { x: 50, y: 50 }; + const next = { playerId, point: start }; + draggingRef.current = next; + setDragging(next); + }; + + const handlePointerMove = (playerId: PlayerId) => (e: PointerEvent) => { + if (!draggingRef.current || draggingRef.current.playerId !== playerId) return; + e.stopPropagation(); + const point = pointFromPointer(e.clientX, e.clientY); + if (!point) return; + const next = { playerId, point }; + draggingRef.current = next; + setDragging(next); + }; + + const finishDrag = (playerId: PlayerId, commit: boolean) => { + const active = draggingRef.current; + if (!active || active.playerId !== playerId) return; + draggingRef.current = null; + setDragging(null); + if (commit) onMove(playerId, active.point); + }; + + const handleKeyDown = (playerId: PlayerId) => (e: KeyboardEvent) => { + if (readOnly) return; + const step = e.shiftKey ? 5 : 2; + let dx = 0; + let dy = 0; + if (e.key === 'ArrowLeft') dx = -step; + else if (e.key === 'ArrowRight') dx = step; + else if (e.key === 'ArrowUp') dy = -step; + else if (e.key === 'ArrowDown') dy = step; + else return; + e.preventDefault(); + e.stopPropagation(); + onDragStart?.(); + const cur = coords[playerId] ?? { x: 50, y: 50 }; + onMove(playerId, clampPoint({ x: cur.x + dx, y: cur.y + dy }, allowBaseline)); + }; + + const stepByPlayer = new Map(); + if (stackPlan) { + for (const move of stackPlan.moves) stepByPlayer.set(move.playerId, move); + } + + return ( +
+ + + {/* Draggable player tokens */} + {lineup.map((slot) => { + const player = byId.get(slot.playerId); + const name = player?.name ?? 'Unknown'; + const number = player?.number ?? ''; + const pos = shortPos(slot.positionId); + const isDragging = dragging?.playerId === slot.playerId; + const point = isDragging ? dragging.point : (coords[slot.playerId] ?? { x: 50, y: 50 }); + const isInbounder = stackPlan?.inbounderId === slot.playerId; + const move = stepByPlayer.get(slot.playerId); + const isActiveMover = + move !== undefined && + (animStage === 'all' || (typeof animStage === 'number' && animStage === move.step)); + + return ( + + ); + })} +
+ ); +} diff --git a/src/components/PlayCardsModal.test.tsx b/src/components/PlayCardsModal.test.tsx new file mode 100644 index 0000000..e2f8baa --- /dev/null +++ b/src/components/PlayCardsModal.test.tsx @@ -0,0 +1,209 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { useState } from 'react'; +import { describe, expect, it, vi } from 'vitest'; +import type { LineupPlayCards, Player } from '../data/types'; +import { DEFAULT_POSITIONS } from '../data/defaults'; +import { defaultOffensePositions, defaultStackPositions } from '../domain/playCards'; +import type { Lineup } from '../engine'; +import { PlayCardsModal } from './PlayCardsModal'; + +const players: Player[] = [ + { id: 'g1', teamId: 't1', name: 'Avery', number: '3', skills: { G: 3 }, active: true, createdAt: 1, updatedAt: 1 }, + { id: 'g2', teamId: 't1', name: 'Blake', number: '5', skills: { G: 2 }, active: true, createdAt: 1, updatedAt: 1 }, + { id: 'f1', teamId: 't1', name: 'Casey', number: '10', skills: { F: 2 }, active: true, createdAt: 1, updatedAt: 1 }, + { id: 'f2', teamId: 't1', name: 'Devon', number: '12', skills: { F: 3 }, active: true, createdAt: 1, updatedAt: 1 }, + { id: 'c1', teamId: 't1', name: 'Harper', number: '22', skills: { C: 3 }, active: true, createdAt: 1, updatedAt: 1 }, +]; + +const byId = new Map(players.map((p) => [p.id, p])); + +const lineup: Lineup = [ + { playerId: 'g1', positionId: 'G' }, + { playerId: 'g2', positionId: 'G' }, + { playerId: 'f1', positionId: 'F' }, + { playerId: 'f2', positionId: 'F' }, + { playerId: 'c1', positionId: 'C' }, +]; + +function Harness({ + initial, + readOnly = false, + onClose = vi.fn(), +}: { + initial?: LineupPlayCards; + readOnly?: boolean; + onClose?: () => void; +}) { + const [saved, setSaved] = useState(initial); + return ( + setSaved((cur) => updater(cur))} + onClose={onClose} + /> + ); +} + +describe('PlayCardsModal', () => { + it('renders all 5 players and navigates Offense → Defense → Inbounding Stack → closes', async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + render(); + + expect(screen.getByRole('heading', { name: 'Offense' })).toBeInTheDocument(); + for (const p of players) expect(screen.getByText(p.name)).toBeInTheDocument(); + + // Advance via Next button + await user.click(screen.getByRole('button', { name: 'Next ›' })); + expect(screen.getByRole('heading', { name: 'Defense' })).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Next ›' })); + expect(screen.getByRole('heading', { name: 'Inbounding Stack' })).toBeInTheDocument(); + + // Go back one card + await user.click(screen.getByRole('button', { name: '‹ Back' })); + expect(screen.getByRole('heading', { name: 'Defense' })).toBeInTheDocument(); + + // Jump via tab dot to Stack, then click footer Done (last card) + await user.click(screen.getByRole('tab', { name: 'Inbounding Stack' })); + const doneButtons = screen.getAllByRole('button', { name: 'Done' }); + await user.click(doneButtons.at(-1)!); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('swipes left/right through the 3 cards and returns to the lineup screen after swiping past the last card', () => { + const onClose = vi.fn(); + render(); + const dialog = screen.getByRole('dialog'); + + const swipe = (startX: number, endX: number) => { + fireEvent.touchStart(dialog, { touches: [{ clientX: startX, clientY: 200 }] }); + fireEvent.touchEnd(dialog, { changedTouches: [{ clientX: endX, clientY: 205 }] }); + }; + + expect(screen.getByRole('heading', { name: 'Offense' })).toBeInTheDocument(); + swipe(300, 150); + expect(screen.getByRole('heading', { name: 'Defense' })).toBeInTheDocument(); + swipe(150, 300); + expect(screen.getByRole('heading', { name: 'Offense' })).toBeInTheDocument(); + swipe(300, 150); + swipe(300, 150); + expect(screen.getByRole('heading', { name: 'Inbounding Stack' })).toBeInTheDocument(); + // Swiping left past the last card returns to the lineup screen. + swipe(300, 150); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('supports switching Offense (1-2-2 / 2-2-1) and Defense (2-3 / 3-2 / Box & 1) formations and Reset', async () => { + const user = userEvent.setup(); + render(); + + // Offense starts on 2-2-1 for 2G/2F/1C + expect(screen.getByRole('radio', { name: '2-2-1' })).toBeChecked(); + await user.click(screen.getByRole('radio', { name: '1-2-2' })); + expect(screen.getByRole('radio', { name: '1-2-2' })).toBeChecked(); + + // Drag/nudge a player with keyboard then snap back with Reset + const avery = screen.getByRole('button', { name: /Avery/ }); + const beforeLeft = avery.style.left; + fireEvent.keyDown(avery, { key: 'ArrowRight', shiftKey: true }); + expect(avery.style.left).not.toBe(beforeLeft); + + await user.click(screen.getByRole('button', { name: '↺ Reset' })); + const resetDefaults = defaultOffensePositions(lineup, '1-2-2'); + expect(avery.style.left).toBe(`${resetDefaults.g1!.x}%`); + expect(avery.style.top).toBe(`${resetDefaults.g1!.y}%`); + + // Switch to Defense and test all 3 formations + Reset + await user.click(screen.getByRole('button', { name: 'Next ›' })); + expect(screen.getByRole('radio', { name: '2-3 Zone' })).toBeChecked(); + await user.click(screen.getByRole('radio', { name: '3-2 Zone' })); + expect(screen.getByRole('radio', { name: '3-2 Zone' })).toBeChecked(); + await user.click(screen.getByRole('radio', { name: 'Box & 1' })); + expect(screen.getByRole('radio', { name: 'Box & 1' })).toBeChecked(); + // Guard should be at top of key (50, 62) + expect(screen.getByRole('button', { name: /Avery/ }).style.left).toBe('50%'); + expect(screen.getByRole('button', { name: /Avery/ }).style.top).toBe('62%'); + + fireEvent.keyDown(screen.getByRole('button', { name: /Avery/ }), { key: 'ArrowLeft', shiftKey: true }); + expect(screen.getByRole('button', { name: /Avery/ }).style.left).toBe('45%'); + await user.click(screen.getByRole('button', { name: '↺ Reset' })); + expect(screen.getByRole('button', { name: /Avery/ }).style.left).toBe('50%'); + }); + + it('drags a player freely using pointer events', () => { + render(); + const stage = document.querySelector('.court-stage') as HTMLElement; + vi.spyOn(stage, 'getBoundingClientRect').mockReturnValue({ + left: 0, + top: 0, + width: 400, + height: 400, + right: 400, + bottom: 400, + x: 0, + y: 0, + toJSON: () => ({}), + }); + + const harper = screen.getByRole('button', { name: /Harper/ }); + fireEvent.pointerDown(harper, { pointerId: 1, pointerType: 'touch', clientX: 200, clientY: 200 }); + fireEvent.pointerMove(harper, { pointerId: 1, pointerType: 'touch', clientX: 120, clientY: 280 }); + fireEvent.pointerUp(harper, { pointerId: 1, pointerType: 'touch', clientX: 120, clientY: 280 }); + + expect(harper.style.left).toBe('30%'); + expect(harper.style.top).toBe('70%'); + }); + + it('supports Stack Left/Right toggle, Arrows toggle, Play all, Step 1→4, and Reset', async () => { + const user = userEvent.setup(); + render(); + + await user.click(screen.getByRole('tab', { name: 'Inbounding Stack' })); + expect(screen.getByRole('heading', { name: 'Inbounding Stack' })).toBeInTheDocument(); + expect(screen.getByRole('radio', { name: 'Right lane' })).toBeChecked(); + expect(screen.getByTestId('stack-arrow-1')).toBeInTheDocument(); + expect(screen.getByTestId('stack-arrow-4')).toBeInTheDocument(); + + // Toggle arrows off and back on + await user.click(screen.getByRole('button', { name: 'Arrows: On' })); + expect(screen.queryByTestId('stack-arrow-1')).not.toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Arrows: Off' })); + expect(screen.getByTestId('stack-arrow-1')).toBeInTheDocument(); + + // Toggle Left lane mirrors coordinates + const harper = screen.getByRole('button', { name: /Harper/ }); + expect(harper.style.left).toBe('63%'); + await user.click(screen.getByRole('radio', { name: 'Left lane' })); + expect(harper.style.left).toBe('37%'); + + // Step 1→4 moves one player at a time + const avery = screen.getByRole('button', { name: /Avery/ }); + const startX = avery.style.left; + await user.click(screen.getByRole('button', { name: 'Step 1→4' })); + expect(avery.style.left).not.toBe(startX); + expect(screen.getByText(/1\. Avery: Away from basket/)).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: /Step 1\/4/ })); + expect(screen.getByText(/2\. Blake: Toward basket/)).toBeInTheDocument(); + + // Play all moves everyone, Stop resets back to stack + await user.click(screen.getByRole('button', { name: '▶ Play all' })); + expect(screen.getByRole('button', { name: '↺ Stack' })).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Stop' })); + expect(avery.style.left).toBe(startX); + + // Drag/nudge then Reset snaps back to default Left stack + fireEvent.keyDown(avery, { key: 'ArrowRight', shiftKey: true }); + expect(avery.style.left).not.toBe(startX); + await user.click(screen.getByRole('button', { name: '↺ Reset' })); + const leftDefaults = defaultStackPositions(lineup, 'left'); + expect(avery.style.left).toBe(`${leftDefaults.g1!.x}%`); + }); +}); diff --git a/src/components/PlayCardsModal.tsx b/src/components/PlayCardsModal.tsx new file mode 100644 index 0000000..7b139dc --- /dev/null +++ b/src/components/PlayCardsModal.tsx @@ -0,0 +1,393 @@ +import { useEffect, useRef, useState, type TouchEvent } from 'react'; +import type { + CourtPoint, + DefenseFormation, + LineupPlayCards, + OffenseFormation, + Player, + Position, + StackSide, +} from '../data/types'; +import { + CARD_ORDER, + animatedStackPositions, + computeStackPlan, + defaultDefensePositions, + defaultOffensePositions, + defaultStackPositions, + mirrorPositions, + resolvePlayCards, +} from '../domain/playCards'; +import type { Lineup, PlayerId } from '../engine'; +import { HalfCourt } from './HalfCourt'; + +const CARD_TITLES = { + offense: 'Offense', + defense: 'Defense', + stack: 'Inbounding Stack', +} as const; + +const OFFENSE_OPTIONS: { value: OffenseFormation; label: string }[] = [ + { value: '1-2-2', label: '1-2-2' }, + { value: '2-2-1', label: '2-2-1' }, +]; + +const DEFENSE_OPTIONS: { value: DefenseFormation; label: string }[] = [ + { value: '2-3', label: '2-3 Zone' }, + { value: '3-2', label: '3-2 Zone' }, + { value: 'box-1', label: 'Box & 1' }, +]; + +const STACK_SIDES: { value: StackSide; label: string }[] = [ + { value: 'left', label: 'Left lane' }, + { value: 'right', label: 'Right lane' }, +]; + +export type AnimStage = 0 | 1 | 2 | 3 | 4 | 'all'; + +interface PlayCardsModalProps { + lineup: Lineup; + byId: Map; + positions: Position[]; + segmentTitle: string; + saved: LineupPlayCards | undefined; + readOnly?: boolean; + onSave: (updater: (current: LineupPlayCards | undefined) => LineupPlayCards | undefined) => void; + onClose: () => void; +} + +/** + * Fullscreen play-card deck for a unique 5-player lineup: + * Offense → Defense → Inbounding Stack. Swipe left/right to step through cards; + * swiping past the last card returns to the lineup screen. + */ +export function PlayCardsModal({ + lineup, + byId, + positions, + segmentTitle, + saved, + readOnly = false, + onSave, + onClose, +}: PlayCardsModalProps) { + const [cardIndex, setCardIndex] = useState(0); + const [showAnnotations, setShowAnnotations] = useState(true); + const [animStage, setAnimStage] = useState(0); + const touchStart = useRef<{ x: number; y: number } | null>(null); + + const kind = CARD_ORDER[cardIndex]!; + const resolved = resolvePlayCards(lineup, saved); + const stackPlan = computeStackPlan(lineup, resolved.stack.positions, resolved.stack.side); + + const goCard = (next: number) => { + setAnimStage(0); + if (next >= CARD_ORDER.length) { + onClose(); + return; + } + setCardIndex(Math.max(0, next)); + }; + + // Keyboard navigation: Left/Right switches cards, Escape closes. + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') { + e.preventDefault(); + onClose(); + } else if (e.key === 'ArrowRight' && !(e.target as HTMLElement | null)?.closest('[data-player-token]')) { + goCard(cardIndex + 1); + } else if (e.key === 'ArrowLeft' && !(e.target as HTMLElement | null)?.closest('[data-player-token]')) { + if (cardIndex > 0) goCard(cardIndex - 1); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }); + + const handleTouchStart = (e: TouchEvent) => { + const target = e.target as HTMLElement | null; + if (target?.closest('[data-player-token]') || target?.closest('button')) { + touchStart.current = null; + return; + } + const t = e.touches[0]; + touchStart.current = t ? { x: t.clientX, y: t.clientY } : null; + }; + + const handleTouchEnd = (e: TouchEvent) => { + const start = touchStart.current; + touchStart.current = null; + const t = e.changedTouches[0]; + if (!start || !t) return; + const dx = t.clientX - start.x; + const dy = t.clientY - start.y; + if (Math.abs(dx) < 50 || Math.abs(dx) < Math.abs(dy) * 1.15) return; + if (dx < 0) goCard(cardIndex + 1); + else if (cardIndex > 0) goCard(cardIndex - 1); + }; + + // Persistence helpers + + const movePlayer = (playerId: PlayerId, point: CourtPoint) => { + if (readOnly) return; + if (kind === 'offense') { + const formation = resolved.offense.formation; + const nextPositions = { ...resolved.offense.positions, [playerId]: point }; + onSave((cur) => ({ ...cur, offense: { formation, positions: nextPositions } })); + } else if (kind === 'defense') { + const formation = resolved.defense.formation; + const nextPositions = { ...resolved.defense.positions, [playerId]: point }; + onSave((cur) => ({ ...cur, defense: { formation, positions: nextPositions } })); + } else { + const side = resolved.stack.side; + const nextPositions = { ...resolved.stack.positions, [playerId]: point }; + onSave((cur) => ({ ...cur, stack: { side, positions: nextPositions } })); + } + }; + + const setOffenseFormation = (formation: OffenseFormation) => { + if (readOnly) return; + const defaults = defaultOffensePositions(lineup, formation); + onSave((cur) => ({ ...cur, offense: { formation, positions: defaults } })); + }; + + const setDefenseFormation = (formation: DefenseFormation) => { + if (readOnly) return; + const defaults = defaultDefensePositions(lineup, formation); + onSave((cur) => ({ ...cur, defense: { formation, positions: defaults } })); + }; + + const setStackSide = (side: StackSide) => { + if (readOnly || side === resolved.stack.side) return; + setAnimStage(0); + const mirrored = mirrorPositions(resolved.stack.positions); + onSave((cur) => ({ ...cur, stack: { side, positions: mirrored } })); + }; + + const resetCurrentCard = () => { + setAnimStage(0); + if (readOnly) return; + if (kind === 'offense') { + const formation = resolved.offense.formation; + onSave((cur) => ({ ...cur, offense: { formation, positions: defaultOffensePositions(lineup, formation) } })); + } else if (kind === 'defense') { + const formation = resolved.defense.formation; + onSave((cur) => ({ ...cur, defense: { formation, positions: defaultDefensePositions(lineup, formation) } })); + } else { + const side = resolved.stack.side; + onSave((cur) => ({ ...cur, stack: { side, positions: defaultStackPositions(lineup, side) } })); + } + }; + + // Stack animation handlers + const togglePlayAll = () => { + setAnimStage((cur) => (cur === 'all' ? 0 : 'all')); + }; + + const stepNext = () => { + const maxStep = stackPlan.moves.length; + setAnimStage((cur) => { + if (cur === 'all') return 1; + if (cur >= maxStep) return 0; + return (cur + 1) as AnimStage; + }); + }; + + const displayedCoords = + kind === 'offense' + ? resolved.offense.positions + : kind === 'defense' + ? resolved.defense.positions + : animatedStackPositions(resolved.stack.positions, stackPlan, animStage); + + const activeMove = + kind === 'stack' && typeof animStage === 'number' && animStage > 0 + ? stackPlan.moves.find((m) => m.step === animStage) + : undefined; + const activeMoverName = activeMove ? (byId.get(activeMove.playerId)?.name ?? 'Player') : null; + + return ( +
+
+
+ {segmentTitle} +

{CARD_TITLES[kind]}

+
+ +
+ +
+ {kind === 'offense' && ( +
+
+ {OFFENSE_OPTIONS.map((opt) => ( + + ))} +
+ {!readOnly && ( + + )} +
+ )} + + {kind === 'defense' && ( +
+
+ {DEFENSE_OPTIONS.map((opt) => ( + + ))} +
+ {!readOnly && ( + + )} +
+ )} + + {kind === 'stack' && ( + <> +
+
+ {STACK_SIDES.map((opt) => ( + + ))} +
+ + {!readOnly && ( + + )} +
+
+ + + {animStage !== 0 && ( + + )} + {activeMove && activeMoverName && ( + + {activeMove.step}. {activeMoverName}: {activeMove.label} + + )} +
+ + )} +
+ +
+ { + if (animStage !== 0) setAnimStage(0); + }} + onMove={movePlayer} + /> +
+ +
+ +
+ {CARD_ORDER.map((card, i) => ( +
+ +
+
+ ); +} diff --git a/src/data/repo.ts b/src/data/repo.ts index cb5e765..93be1e4 100644 --- a/src/data/repo.ts +++ b/src/data/repo.ts @@ -2,7 +2,7 @@ import { db } from './db'; import { receivedHandoff, roleOf, type GameHandoff } from './handoff'; import { DEFAULT_FORMAT, DEFAULT_POSITIONS, DEFAULT_RULES, DEMO_PLAYERS } from './defaults'; import { STARTER_DRILLS } from './starterDrills'; -import type { Drill, Game, Player, Practice, Station, Team } from './types'; +import type { Drill, Game, LineupPlayCards, Player, Practice, Station, Team } from './types'; /** * The only module that reads and writes storage. Screens call these @@ -139,6 +139,30 @@ export async function updateGame(id: string, changes: Partial LineupPlayCards | undefined, +): Promise { + await db.transaction('rw', db.games, async () => { + const game = await db.games.get(gameId); + if (!game) return; + const nextMap: Partial<{ [k: string]: LineupPlayCards }> = { ...(game.playCards ?? {}) }; + const updated = change(nextMap[key]); + if (updated && (updated.offense || updated.defense || updated.stack)) { + nextMap[key] = updated; + } else { + delete nextMap[key]; + } + const playCards = Object.keys(nextMap).length > 0 ? nextMap : undefined; + await db.games.update(gameId, { playCards, updatedAt: Date.now() }); + }); +} + /** Adds or removes a player from the game's attendance; clears the plan and that player's locks (G1). */ export async function toggleAttending(gameId: string, playerId: string): Promise { await db.transaction('rw', db.games, async () => { diff --git a/src/data/types.ts b/src/data/types.ts index 03102c6..97700c4 100644 --- a/src/data/types.ts +++ b/src/data/types.ts @@ -113,6 +113,37 @@ export interface Game extends Record { * Missing: the last thing done was Next, or nothing yet. */ lastChange?: LastChange; + /** + * Custom play-card layouts keyed by unique 5-player lineup (`lineupKey`). + * Missing entries use deterministic defaults. + */ + playCards?: Partial<{ [lineupKey: string]: LineupPlayCards }>; +} + +export type PlayCardKind = 'offense' | 'defense' | 'stack'; +export type OffenseFormation = '1-2-2' | '2-2-1'; +export type DefenseFormation = '2-3' | '3-2' | 'box-1'; +export type StackSide = 'left' | 'right'; + +/** Normalized court point: x in [0, 100] (left→right), y in [0, 100] (baseline→half-court). */ +export interface CourtPoint { + x: number; + y: number; +} + +export interface LineupPlayCards { + offense?: { + formation: OffenseFormation; + positions: Partial<{ [playerId: PlayerId]: CourtPoint }>; + }; + defense?: { + formation: DefenseFormation; + positions: Partial<{ [playerId: PlayerId]: CourtPoint }>; + }; + stack?: { + side: StackSide; + positions: Partial<{ [playerId: PlayerId]: CourtPoint }>; + }; } /** The parts of a game a game-day change touches, kept for Undo (D2). */ diff --git a/src/data/validate.test.ts b/src/data/validate.test.ts index e43ae76..ef462d6 100644 --- a/src/data/validate.test.ts +++ b/src/data/validate.test.ts @@ -32,6 +32,13 @@ describe('shape checks for incoming data (C4)', () => { locks: [{ segment: 0, playerId: 'a', kind: 'in' }], events: [{ kind: 'swap-now', segment: 0, out: 'a', in: 'b' }], handoff: { n: 2, role: 'coach', away: true, sentAt: 5 }, + playCards: { + 'a|b|c|d|e': { + offense: { formation: '1-2-2', positions: { a: { x: 50, y: 66 } } }, + defense: { formation: 'box-1', positions: { a: { x: 50, y: 62 } } }, + stack: { side: 'left', positions: { a: { x: 37, y: 5.5 } } }, + }, + }, }; expect(isValidGame(live)).toBe(true); }); @@ -66,6 +73,10 @@ describe('shape checks for incoming data (C4)', () => { { ...game, attending: [1, 2] }, { ...game, format: { periodType: 'halves', segmentsPerPeriod: 0 } }, { ...game, handoff: { n: 1, role: 'referee', away: false } }, + { ...game, playCards: { 'a|b': { offense: { formation: '4-out', positions: {} } } } }, + { ...game, playCards: { 'a|b': { defense: { formation: '1-3-1', positions: {} } } } }, + { ...game, playCards: { 'a|b': { stack: { side: 'middle', positions: {} } } } }, + { ...game, playCards: { 'a|b': { offense: { formation: '1-2-2', positions: { a: { x: 150, y: 50 } } } } } }, [game], ]; for (const value of bad) expect(isValidGame(value)).toBe(false); diff --git a/src/data/validate.ts b/src/data/validate.ts index 0cfb72e..54bef52 100644 --- a/src/data/validate.ts +++ b/src/data/validate.ts @@ -63,6 +63,21 @@ const isStatus: Check = (value) => exact({ kind: oneOf('arrived'), at: isCount() })(value); const isEvent = exact({ kind: isString, segment: isCount() }); const isHandoff = exact({ n: isNumber, role: oneOf('coach', 'assistant'), away: isBoolean }); +const isCoord: Check = (v) => isNumber(v) && (v as number) >= 0 && (v as number) <= 100; +const isCourtPoint = exact({ x: isCoord, y: isCoord }); +const isPositionsMap: Check = (v) => isObject(v) && Object.keys(v).length <= 10 && recordOf(isCourtPoint)(v); +const isLineupPlayCards: Check = (value) => { + if (!isObject(value)) return false; + const { offense, defense, stack } = value; + const okOffense = + offense === undefined || exact({ formation: oneOf('1-2-2', '2-2-1'), positions: isPositionsMap })(offense); + const okDefense = + defense === undefined || exact({ formation: oneOf('2-3', '3-2', 'box-1'), positions: isPositionsMap })(defense); + const okStack = stack === undefined || exact({ side: oneOf('left', 'right'), positions: isPositionsMap })(stack); + return okOffense && okDefense && okStack; +}; +const isPlayCardsMap: Check = (value) => + isObject(value) && Object.keys(value).length <= MAX_SEGMENTS && recordOf(isLineupPlayCards)(value); const isLastChange = exact({ label: isString, before: exact({ @@ -114,6 +129,7 @@ const gameFields = shape({ locks: listOf(isLock), handoff: isHandoff, lastChange: isLastChange, + playCards: isPlayCardsMap, }); // Practice planning (PR11). Generous limits again: a practice has a few diff --git a/src/domain/playCards.test.ts b/src/domain/playCards.test.ts new file mode 100644 index 0000000..ff2df64 --- /dev/null +++ b/src/domain/playCards.test.ts @@ -0,0 +1,262 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import type { DefenseFormation, OffenseFormation, StackSide } from '../data/types'; +import type { Lineup } from '../engine'; +import { + COURT, + COURT_BOUNDS, + STACK_LINE_Y, + THIRD_HASH_Y, + animatedStackPositions, + clampPoint, + computeStackPlan, + defaultDefensePositions, + defaultOffenseFormation, + defaultOffensePositions, + defaultStackPositions, + lineupKey, + mirrorPositions, + resolvePlayCards, + stackLaneX, +} from './playCards'; + +const lineup2G2F1C: Lineup = [ + { playerId: 'g1', positionId: 'G' }, + { playerId: 'g2', positionId: 'G' }, + { playerId: 'f1', positionId: 'F' }, + { playerId: 'f2', positionId: 'F' }, + { playerId: 'c1', positionId: 'C' }, +]; + +const lineup1G2F2C: Lineup = [ + { playerId: 'g1', positionId: 'G' }, + { playerId: 'f1', positionId: 'F' }, + { playerId: 'f2', positionId: 'F' }, + { playerId: 'c1', positionId: 'C' }, + { playerId: 'c2', positionId: 'C' }, +]; + +describe('lineupKey', () => { + it('returns the same canonical key regardless of slot order', () => { + const a = lineupKey(lineup2G2F1C); + const b = lineupKey([...lineup2G2F1C].reverse()); + expect(a).toBe(b); + expect(a).toBe('c1|f1|f2|g1|g2'); + }); + + it('produces distinct keys when one player changes', () => { + expect(lineupKey(lineup2G2F1C)).not.toBe(lineupKey(lineup1G2F2C)); + }); +}); + +describe('offense default positions', () => { + it('auto-selects 1-2-2 for 2-center lineups and 2-2-1 for 1-center lineups', () => { + expect(defaultOffenseFormation(lineup1G2F2C)).toBe('1-2-2'); + expect(defaultOffenseFormation(lineup2G2F1C)).toBe('2-2-1'); + }); + + it('places 1-2-2 with guard at top of key, forwards on wings, centers on low blocks', () => { + const pos = defaultOffensePositions(lineup1G2F2C, '1-2-2'); + expect(pos.g1).toEqual({ x: 50, y: 66 }); + expect([pos.f1!.x, pos.f2!.x].sort((a, b) => a - b)).toEqual([15, 85]); + expect(pos.f1!.y).toBe(43); + expect(pos.f2!.y).toBe(43); + expect([pos.c1!.x, pos.c2!.x].sort((a, b) => a - b)).toEqual([33, 67]); + expect(pos.c1!.y).toBe(24); + expect(pos.c2!.y).toBe(24); + }); + + it('places 2-2-1 with 2 guards up top, 2 forwards on wings, 1 center on low block', () => { + const pos = defaultOffensePositions(lineup2G2F1C, '2-2-1'); + expect([pos.g1!.x, pos.g2!.x].sort((a, b) => a - b)).toEqual([34, 66]); + expect(pos.g1!.y).toBe(67); + expect([pos.f1!.x, pos.f2!.x].sort((a, b) => a - b)).toEqual([15, 85]); + expect(pos.c1).toEqual({ x: 67, y: 24 }); + }); +}); + +describe('defense default positions', () => { + it('places 2-3 zone with guards up top, center middle low, forwards low outside', () => { + const pos = defaultDefensePositions(lineup2G2F1C, '2-3'); + expect([pos.g1!.x, pos.g2!.x].sort((a, b) => a - b)).toEqual([35, 65]); + expect(pos.g1!.y).toBe(54); + expect(pos.c1).toEqual({ x: 50, y: 25 }); + expect([pos.f1!.x, pos.f2!.x].sort((a, b) => a - b)).toEqual([21, 79]); + expect(pos.f1!.y).toBe(29); + }); + + it('places 3-2 zone with guards and forwards up top, centers down low', () => { + const pos = defaultDefensePositions(lineup1G2F2C, '3-2'); + // Guard + 2 forwards up top (y >= 48), 2 centers down low (y = 26) + expect(pos.g1!.y).toBeGreaterThanOrEqual(48); + expect(pos.f1!.y).toBeGreaterThanOrEqual(48); + expect(pos.f2!.y).toBeGreaterThanOrEqual(48); + expect([pos.c1!.x, pos.c2!.x].sort((a, b) => a - b)).toEqual([35, 65]); + expect(pos.c1!.y).toBe(26); + expect(pos.c2!.y).toBe(26); + }); + + it('places Box & 1 with guard at top of key, forwards at elbows, centers on low blocks', () => { + const pos = defaultDefensePositions(lineup1G2F2C, 'box-1'); + expect(pos.g1).toEqual({ x: 50, y: 62 }); + expect([pos.f1!.x, pos.f2!.x].sort((a, b) => a - b)).toEqual([36, 64]); + expect(pos.f1!.y).toBe(46); + expect([pos.c1!.x, pos.c2!.x].sort((a, b) => a - b)).toEqual([36, 64]); + expect(pos.c1!.y).toBe(24); + }); +}); + +describe('inbounding stack defaults, mirroring, annotations and animation', () => { + it('defaults to a Center inbounding from the baseline and 4 players single-file starting at the 3rd hash mark', () => { + const pos = defaultStackPositions(lineup2G2F1C, 'right'); + const laneX = stackLaneX('right'); + expect(pos.c1).toEqual({ x: laneX, y: COURT.inbounderY }); + const stackYs = ['g1', 'g2', 'f1', 'f2'].map((id) => pos[id]!.y); + expect(stackYs).toEqual([...STACK_LINE_Y]); + expect(stackYs[0]).toBe(THIRD_HASH_Y); + for (const id of ['g1', 'g2', 'f1', 'f2']) { + expect(pos[id]!.x).toBe(laneX); + } + }); + + it('falls back gracefully when no Center is in the lineup', () => { + const noCenter: Lineup = [ + { playerId: 'g1', positionId: 'G' }, + { playerId: 'g2', positionId: 'G' }, + { playerId: 'f1', positionId: 'F' }, + { playerId: 'f2', positionId: 'F' }, + { playerId: 'g3', positionId: 'G' }, + ]; + const pos = defaultStackPositions(noCenter, 'left'); + expect(pos.f1).toEqual({ x: stackLaneX('left'), y: COURT.inbounderY }); + }); + + it('mirrors left and right stack positions across the basket (x = 50)', () => { + const right = defaultStackPositions(lineup2G2F1C, 'right'); + const mirrored = mirrorPositions(right); + const left = defaultStackPositions(lineup2G2F1C, 'left'); + expect(mirrored).toEqual(left); + }); + + it('computes the 4 stack movements accurately for both right and left lane', () => { + for (const side of ['right', 'left'] as StackSide[]) { + const pos = defaultStackPositions(lineup2G2F1C, side); + const plan = computeStackPlan(lineup2G2F1C, pos, side); + expect(plan.inbounderId).toBe('c1'); + expect(plan.moves).toHaveLength(4); + const [m1, m2, m3, m4] = plan.moves; + // 1st player: parallel to baseline AWAY from basket (x = 50) + expect(m1!.step).toBe(1); + expect(m1!.to.y).toBe(m1!.from.y); + expect(Math.abs(m1!.to.x - 50)).toBeGreaterThan(Math.abs(m1!.from.x - 50)); + // 2nd player: parallel to baseline TOWARD basket (across lane) + expect(m2!.step).toBe(2); + expect(m2!.to.y).toBe(m2!.from.y); + if (side === 'right') expect(m2!.to.x).toBeLessThan(m2!.from.x); + else expect(m2!.to.x).toBeGreaterThan(m2!.from.x); + // 3rd player: comes forward toward inbounder (smaller y) + expect(m3!.step).toBe(3); + expect(m3!.to.y).toBeLessThan(m3!.from.y); + expect(m3!.control).toBeDefined(); + // 4th player: pops back away from inbounder (larger y) + expect(m4!.step).toBe(4); + expect(m4!.to.y).toBeGreaterThan(m4!.from.y); + } + }); + + it('recomputes inbounder and stack order dynamically after dragging players', () => { + const pos = defaultStackPositions(lineup2G2F1C, 'right'); + // Drag g1 onto the baseline and c1 into the 4th spot at the bottom of the stack. + const reordered = { + ...pos, + g1: { x: 63, y: 5.5 }, + c1: { x: 63, y: 80 }, + }; + const plan = computeStackPlan(lineup2G2F1C, reordered, 'right'); + expect(plan.inbounderId).toBe('g1'); + expect(plan.moves.map((m) => m.playerId)).toEqual(['g2', 'f1', 'f2', 'c1']); + }); + + it('animates players step-by-step (1→4) and all at once', () => { + const pos = defaultStackPositions(lineup2G2F1C, 'right'); + const plan = computeStackPlan(lineup2G2F1C, pos, 'right'); + expect(animatedStackPositions(pos, plan, 0)).toEqual(pos); + + const step1 = animatedStackPositions(pos, plan, 1); + expect(step1[plan.moves[0]!.playerId]).toEqual(plan.moves[0]!.to); + expect(step1[plan.moves[1]!.playerId]).toEqual(plan.moves[1]!.from); + + const step2 = animatedStackPositions(pos, plan, 2); + expect(step2[plan.moves[0]!.playerId]).toEqual(plan.moves[0]!.to); + expect(step2[plan.moves[1]!.playerId]).toEqual(plan.moves[1]!.to); + expect(step2[plan.moves[2]!.playerId]).toEqual(plan.moves[2]!.from); + + const all = animatedStackPositions(pos, plan, 'all'); + for (const move of plan.moves) { + expect(all[move.playerId]).toEqual(move.to); + } + expect(all[plan.inbounderId!]).toEqual(pos[plan.inbounderId!]); + }); + + it('merges saved custom coordinates with defaults and clamps out-of-range coordinates', () => { + const resolved = resolvePlayCards(lineup2G2F1C, { + offense: { formation: '1-2-2', positions: { g1: { x: 120, y: 3 } } }, + defense: { formation: 'box-1', positions: { c1: { x: 40, y: 30 } } }, + stack: { side: 'left', positions: { c1: { x: 37, y: 5 } } }, + }); + expect(resolved.offense.formation).toBe('1-2-2'); + expect(resolved.offense.positions.g1).toEqual(clampPoint({ x: 120, y: 3 }, false)); + expect(resolved.defense.formation).toBe('box-1'); + expect(resolved.defense.positions.c1).toEqual({ x: 40, y: 30 }); + expect(resolved.stack.side).toBe('left'); + expect(resolved.stack.positions.c1).toEqual({ x: 37, y: 5 }); + }); +}); + +describe('play cards properties', () => { + const posArb = fc.constantFrom<'G' | 'F' | 'C' | null>('G', 'F', 'C', null); + const lineupArb = fc.tuple(posArb, posArb, posArb, posArb, posArb).map( + (positions): Lineup => positions.map((positionId, i) => ({ playerId: `p${i + 1}`, positionId })), + ); + + it('always produces 5 distinct in-bounds positions for every formation and valid animation endpoints', () => { + fc.assert( + fc.property( + lineupArb, + fc.constantFrom('1-2-2', '2-2-1'), + fc.constantFrom('2-3', '3-2', 'box-1'), + fc.constantFrom('left', 'right'), + (lineup, offForm, defForm, side) => { + const checkMap = (map: Record, minY: number) => { + const keys = Object.keys(map); + expect(keys).toHaveLength(5); + const seen = new Set(); + for (const pt of Object.values(map)) { + expect(pt.x).toBeGreaterThanOrEqual(COURT_BOUNDS.minX); + expect(pt.x).toBeLessThanOrEqual(COURT_BOUNDS.maxX); + expect(pt.y).toBeGreaterThanOrEqual(minY); + expect(pt.y).toBeLessThanOrEqual(COURT_BOUNDS.maxY); + seen.add(`${pt.x},${pt.y}`); + } + expect(seen.size).toBe(5); + }; + + checkMap(defaultOffensePositions(lineup, offForm), COURT_BOUNDS.minYInbounds); + checkMap(defaultDefensePositions(lineup, defForm), COURT_BOUNDS.minYInbounds); + const stack = defaultStackPositions(lineup, side); + checkMap(stack, COURT_BOUNDS.minYStack); + + const plan = computeStackPlan(lineup, stack, side); + expect(plan.inbounderId).not.toBeNull(); + expect(plan.moves).toHaveLength(4); + for (const move of plan.moves) { + expect(move.to.x).toBeGreaterThanOrEqual(COURT_BOUNDS.minX); + expect(move.to.x).toBeLessThanOrEqual(COURT_BOUNDS.maxX); + expect(move.to.y).toBeGreaterThanOrEqual(COURT_BOUNDS.minYInbounds); + expect(move.to.y).toBeLessThanOrEqual(COURT_BOUNDS.maxY); + } + }, + ), + ); + }); +}); diff --git a/src/domain/playCards.ts b/src/domain/playCards.ts new file mode 100644 index 0000000..31906b8 --- /dev/null +++ b/src/domain/playCards.ts @@ -0,0 +1,409 @@ +import type { + CourtPoint, + DefenseFormation, + LineupPlayCards, + OffenseFormation, + PlayCardKind, + StackSide, +} from '../data/types'; +import type { Lineup, PlayerId } from '../engine'; + +/** + * Pure geometry and default positioning for game play cards (Offense, Defense, + * Inbounding Stack). Coordinates live in a 0..100 × 0..100 half-court space + * with the basket at the top: + * - y = 0..10: baseline out-of-bounds strip (inbounder stands at y = 5.5) + * - y = 10: baseline + * - y = 96: half-court line + * - x = 4..96: sidelines; lane runs x = 37..63, y = 10..46 + */ + +export const CARD_ORDER: readonly PlayCardKind[] = ['offense', 'defense', 'stack']; + +export const COURT = { + baselineY: 10, + halfCourtY: 96, + leftSidelineX: 4, + rightSidelineX: 96, + hoopX: 50, + hoopY: 18.5, + backboardY: 14.5, + laneLeftX: 37, + laneRightX: 63, + freeThrowY: 46, + /** Three lane hash marks going away from the baseline toward the free-throw line. */ + laneHashesY: [22, 29, 36] as const, + /** Inbounder rests behind the baseline out-of-bounds. */ + inbounderY: 5.5, +} as const; + +export const THIRD_HASH_Y = COURT.laneHashesY[2]; + +/** Bounds when dragging a player token on Offense/Defense vs Stack (which allows out-of-bounds). */ +export const COURT_BOUNDS = { + minX: 7, + maxX: 93, + minYInbounds: 15, + minYStack: 4.5, + maxY: 92, +} as const; + +export function clamp(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)); +} + +export function roundCoord(value: number): number { + return Math.round(value * 10) / 10; +} + +export function clampPoint(point: CourtPoint, allowBaseline: boolean): CourtPoint { + return { + x: roundCoord(clamp(point.x, COURT_BOUNDS.minX, COURT_BOUNDS.maxX)), + y: roundCoord(clamp(point.y, allowBaseline ? COURT_BOUNDS.minYStack : COURT_BOUNDS.minYInbounds, COURT_BOUNDS.maxY)), + }; +} + +/** + * Canonical key for a unique set of on-court players, independent of display order. + * Two segments with the same five players share the same play cards. + */ +export function lineupKey(lineup: Lineup): string { + return [...lineup] + .map((s) => s.playerId) + .sort() + .join('|'); +} + +type RoleBucket = 'G' | 'F' | 'C' | 'other'; + +function bucketOf(positionId: string | null): RoleBucket { + if (positionId === 'G' || positionId === 'F' || positionId === 'C') return positionId; + return 'other'; +} + +interface WeightedSlot { + point: CourtPoint; + weights: Record; +} + +/** + * Assigns each player in a lineup (normally 5) to a distinct court slot by + * maximizing total position-fit weight. Exhaustive search over at most 5! = 120 + * permutations is instant and deterministic. + */ +function assignWeightedSlots(lineup: Lineup, slots: readonly WeightedSlot[]): Record { + const n = Math.min(lineup.length, slots.length); + const players = lineup.slice(0, n); + let bestScore = -1; + let bestOrder: number[] = []; + const used = new Array(n).fill(false); + const current = new Array(n).fill(0); + + const search = (slotIndex: number, score: number) => { + if (slotIndex === n) { + if (score > bestScore) { + bestScore = score; + bestOrder = [...current]; + } + return; + } + const slot = slots[slotIndex]!; + for (let p = 0; p < n; p++) { + if (used[p]) continue; + used[p] = true; + current[slotIndex] = p; + const bucket = bucketOf(players[p]!.positionId); + search(slotIndex + 1, score + slot.weights[bucket]); + used[p] = false; + } + }; + search(0, 0); + + const result: Record = {}; + for (let s = 0; s < n; s++) { + const player = players[bestOrder[s]!]!; + result[player.playerId] = { ...slots[s]!.point }; + } + // Defensive fallback if a lineup ever had more than 5 entries. + for (let i = n; i < lineup.length; i++) { + result[lineup[i]!.playerId] = { x: roundCoord(20 + ((i * 15) % 60)), y: 80 }; + } + return result; +} + +// Offense formations + +const OFFENSE_1_2_2: readonly WeightedSlot[] = [ + // 1 guard at top of the key + { point: { x: 50, y: 66 }, weights: { G: 30, F: 14, C: 1, other: 10 } }, + // 2 forwards on wings + { point: { x: 15, y: 43 }, weights: { G: 18, F: 30, C: 5, other: 10 } }, + { point: { x: 85, y: 43 }, weights: { G: 18, F: 30, C: 5, other: 10 } }, + // 2 centers on low blocks + { point: { x: 33, y: 24 }, weights: { G: 1, F: 18, C: 30, other: 10 } }, + { point: { x: 67, y: 24 }, weights: { G: 1, F: 18, C: 30, other: 10 } }, +]; + +const OFFENSE_2_2_1: readonly WeightedSlot[] = [ + // 2 guards up top + { point: { x: 34, y: 67 }, weights: { G: 30, F: 16, C: 1, other: 10 } }, + { point: { x: 66, y: 67 }, weights: { G: 30, F: 16, C: 1, other: 10 } }, + // 2 forwards on wings + { point: { x: 15, y: 43 }, weights: { G: 18, F: 30, C: 5, other: 10 } }, + { point: { x: 85, y: 43 }, weights: { G: 18, F: 30, C: 5, other: 10 } }, + // 1 center on low block + { point: { x: 67, y: 24 }, weights: { G: 1, F: 18, C: 30, other: 10 } }, +]; + +/** + * Picks 1-2-2 (1 guard, 2 forwards, 2 centers) when the lineup has 2+ centers; + * otherwise 2-2-1 (2 guards, 2 forwards, 1 center). + */ +export function defaultOffenseFormation(lineup: Lineup): OffenseFormation { + const centers = lineup.filter((s) => s.positionId === 'C').length; + return centers >= 2 ? '1-2-2' : '2-2-1'; +} + +export function defaultOffensePositions(lineup: Lineup, formation: OffenseFormation): Record { + return assignWeightedSlots(lineup, formation === '1-2-2' ? OFFENSE_1_2_2 : OFFENSE_2_2_1); +} + +// Defense formations + +const DEFENSE_2_3: readonly WeightedSlot[] = [ + // 2 guards up top + { point: { x: 35, y: 54 }, weights: { G: 30, F: 18, C: 1, other: 10 } }, + { point: { x: 65, y: 54 }, weights: { G: 30, F: 18, C: 1, other: 10 } }, + // 1 center middle low + { point: { x: 50, y: 25 }, weights: { G: 1, F: 15, C: 30, other: 10 } }, + // 2 forwards low outside + { point: { x: 21, y: 29 }, weights: { G: 5, F: 30, C: 20, other: 10 } }, + { point: { x: 79, y: 29 }, weights: { G: 5, F: 30, C: 20, other: 10 } }, +]; + +const DEFENSE_3_2: readonly WeightedSlot[] = [ + // 3 up top: guards and forwards + { point: { x: 50, y: 59 }, weights: { G: 30, F: 15, C: 1, other: 10 } }, + { point: { x: 22, y: 48 }, weights: { G: 26, F: 28, C: 1, other: 10 } }, + { point: { x: 78, y: 48 }, weights: { G: 26, F: 28, C: 1, other: 10 } }, + // 2 down low: centers + { point: { x: 35, y: 26 }, weights: { G: 1, F: 18, C: 30, other: 10 } }, + { point: { x: 65, y: 26 }, weights: { G: 1, F: 18, C: 30, other: 10 } }, +]; + +const DEFENSE_BOX_1: readonly WeightedSlot[] = [ + // Guard at top of the key (the "1") + { point: { x: 50, y: 62 }, weights: { G: 30, F: 10, C: 1, other: 10 } }, + // Forwards at elbows + { point: { x: 36, y: 46 }, weights: { G: 20, F: 30, C: 5, other: 10 } }, + { point: { x: 64, y: 46 }, weights: { G: 20, F: 30, C: 5, other: 10 } }, + // Centers on low blocks + { point: { x: 36, y: 24 }, weights: { G: 1, F: 20, C: 30, other: 10 } }, + { point: { x: 64, y: 24 }, weights: { G: 1, F: 20, C: 30, other: 10 } }, +]; + +export const DEFAULT_DEFENSE_FORMATION: DefenseFormation = '2-3'; + +export function defaultDefensePositions( + lineup: Lineup, + formation: DefenseFormation = DEFAULT_DEFENSE_FORMATION, +): Record { + const slots = + formation === '3-2' ? DEFENSE_3_2 : formation === 'box-1' ? DEFENSE_BOX_1 : DEFENSE_2_3; + return assignWeightedSlots(lineup, slots); +} + +// Inbounding stack + +export const DEFAULT_STACK_SIDE: StackSide = 'right'; + +/** Vertical coordinates of the 4 players in the stack, starting at the 3rd hash mark. */ +export const STACK_LINE_Y = [THIRD_HASH_Y, THIRD_HASH_Y + 11, THIRD_HASH_Y + 22, THIRD_HASH_Y + 33] as const; + +export function stackLaneX(side: StackSide): number { + return side === 'right' ? COURT.laneRightX : COURT.laneLeftX; +} + +/** + * Defaults to a Center inbounding from the baseline, and the other four players + * in a single-file line along the chosen side of the lane starting at the 3rd + * hash mark up from the baseline. + */ +export function defaultStackPositions( + lineup: Lineup, + side: StackSide = DEFAULT_STACK_SIDE, +): Record { + const laneX = stackLaneX(side); + const inbounder = + lineup.find((s) => s.positionId === 'C') ?? + lineup.find((s) => s.positionId === 'F') ?? + lineup[lineup.length - 1]; + const result: Record = {}; + if (!inbounder) return result; + result[inbounder.playerId] = { x: laneX, y: COURT.inbounderY }; + const line = lineup.filter((s) => s.playerId !== inbounder.playerId); + line.forEach((slot, i) => { + const y = STACK_LINE_Y[i] ?? Math.min(COURT_BOUNDS.maxY, THIRD_HASH_Y + i * 11); + result[slot.playerId] = { x: laneX, y }; + }); + return result; +} + +/** Mirrors all player x-coordinates horizontally across the basket (x = 50). */ +export function mirrorPositions(positions: Record): Record { + const mirrored: Record = {}; + for (const [id, pt] of Object.entries(positions)) { + mirrored[id] = { x: roundCoord(100 - pt.x), y: pt.y }; + } + return mirrored; +} + +export interface ResolvedPlayCards { + offense: { + formation: OffenseFormation; + positions: Record; + }; + defense: { + formation: DefenseFormation; + positions: Record; + }; + stack: { + side: StackSide; + positions: Record; + }; +} + +function mergePositions( + lineup: Lineup, + defaults: Record, + saved: Partial<{ [playerId: PlayerId]: CourtPoint }> | undefined, + allowBaseline: boolean, +): Record { + const out: Record = {}; + for (const slot of lineup) { + const custom = saved?.[slot.playerId]; + out[slot.playerId] = custom ? clampPoint(custom, allowBaseline) : defaults[slot.playerId]!; + } + return out; +} + +/** Resolves all three play cards for a lineup by combining saved customizations with defaults. */ +export function resolvePlayCards(lineup: Lineup, saved?: LineupPlayCards): ResolvedPlayCards { + const offenseFormation = saved?.offense?.formation ?? defaultOffenseFormation(lineup); + const defenseFormation = saved?.defense?.formation ?? DEFAULT_DEFENSE_FORMATION; + const stackSide = saved?.stack?.side ?? DEFAULT_STACK_SIDE; + + const offenseDefaults = defaultOffensePositions(lineup, offenseFormation); + const defenseDefaults = defaultDefensePositions(lineup, defenseFormation); + const stackDefaults = defaultStackPositions(lineup, stackSide); + + return { + offense: { + formation: offenseFormation, + positions: mergePositions(lineup, offenseDefaults, saved?.offense?.positions, false), + }, + defense: { + formation: defenseFormation, + positions: mergePositions(lineup, defenseDefaults, saved?.defense?.positions, false), + }, + stack: { + side: stackSide, + positions: mergePositions(lineup, stackDefaults, saved?.stack?.positions, true), + }, + }; +} + +// Stack movement annotations & animation + +export interface StackMove { + playerId: PlayerId; + /** 1 = closest to inbounder, 2 = second, 3 = third, 4 = fourth (furthest from inbounder). */ + step: 1 | 2 | 3 | 4; + from: CourtPoint; + to: CourtPoint; + /** Optional quadratic Bézier control point so #3's forward cut curves cleanly around the stack. */ + control?: CourtPoint; + label: string; +} + +export interface StackPlan { + inbounderId: PlayerId | null; + moves: StackMove[]; +} + +/** + * Derives the inbounder and ordered 1st–4th stack cuts dynamically from the + * players' current coordinates (ordered by distance from the baseline): + * - Closest to baseline: Inbounder + * - 1st player: parallel to baseline AWAY from the basket + * - 2nd player: parallel to baseline TOWARD the basket + * - 3rd player: forward TOWARD the inbounder + * - 4th player: pops back AWAY from the inbounder + */ +export function computeStackPlan( + lineup: Lineup, + positions: Record, + side: StackSide, +): StackPlan { + const ordered = [...lineup] + .filter((s) => positions[s.playerId] !== undefined) + .sort((a, b) => { + const pa = positions[a.playerId]!; + const pb = positions[b.playerId]!; + return pa.y - pb.y || pa.x - pb.x || a.playerId.localeCompare(b.playerId); + }); + + if (ordered.length === 0) return { inbounderId: null, moves: [] }; + + const inbounderId = ordered[0]!.playerId; + const stackPlayers = ordered.slice(1, 5); + // Direction away from the basket (x = 50): right side moves +x, left side moves -x. + const awayDir = side === 'right' ? 1 : -1; + + const moves: StackMove[] = stackPlayers.map((slot, index) => { + const step = (index + 1) as 1 | 2 | 3 | 4; + const from = positions[slot.playerId]!; + if (step === 1) { + const to = clampPoint({ x: from.x + awayDir * 24, y: from.y }, false); + return { playerId: slot.playerId, step, from, to, label: 'Away from basket' }; + } + if (step === 2) { + const to = clampPoint({ x: from.x - awayDir * 28, y: from.y }, false); + return { playerId: slot.playerId, step, from, to, label: 'Toward basket' }; + } + if (step === 3) { + const to = clampPoint({ x: from.x, y: Math.max(21, from.y - 34) }, false); + // Slight arc toward the outside of the stack so the arrow is clearly visible before players clear out. + const control = clampPoint( + { x: from.x + awayDir * 9, y: (from.y + to.y) / 2 }, + false, + ); + return { playerId: slot.playerId, step, from, to, control, label: 'Forward to inbounder' }; + } + const to = clampPoint({ x: from.x, y: from.y + 19 }, false); + return { playerId: slot.playerId, step, from, to, label: 'Pop back' }; + }); + + return { inbounderId, moves }; +} + +/** + * Computes displayed player coordinates for a given Stack animation state: + * - step 0: everyone at starting stack positions + * - step 1..4: players with move.step <= step are at their destination + * - 'all': all 4 stack players are at their destination + */ +export function animatedStackPositions( + positions: Record, + plan: StackPlan, + stage: 0 | 1 | 2 | 3 | 4 | 'all', +): Record { + if (stage === 0) return positions; + const out: Record = { ...positions }; + for (const move of plan.moves) { + if (stage === 'all' || move.step <= stage) { + out[move.playerId] = move.to; + } + } + return out; +} diff --git a/src/screens/GameDayScreen.test.tsx b/src/screens/GameDayScreen.test.tsx index e08bcce..1b47288 100644 --- a/src/screens/GameDayScreen.test.tsx +++ b/src/screens/GameDayScreen.test.tsx @@ -58,8 +58,8 @@ async function confirmIfWarned(user: ReturnType) { const savedGame = async (id: string) => (await db.games.get(id))!; const courtNames = () => within(screen.getByRole('region', { name: 'On court now' })) - .getAllByRole('button') - .map((b) => b.querySelector('.court-name')!.textContent); + .getAllByRole('listitem') + .map((li) => li.querySelector('.court-name')!.textContent); describe('game day changes', () => { it('subs a player out now and credits both players for the segment', async () => { @@ -380,4 +380,25 @@ describe('game day changes', () => { expect(courtNames()).not.toContain(centerName); expect((await savedGame(game.id)).events.at(-1)?.kind).toBe('swap-now'); }); + + it('opens play cards from the live game day screen and persists edits per unique lineup', async () => { + const user = userEvent.setup(); + const game = await startLiveGame(); + render(); + await user.click(await screen.findByRole('button', { name: 'Play cards' })); + expect(screen.getByRole('dialog', { name: 'Play cards: Offense' })).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Next ›' })); + expect(screen.getByRole('dialog', { name: 'Play cards: Defense' })).toBeInTheDocument(); + await user.click(screen.getByRole('radio', { name: '3-2 Zone' })); + await waitFor(async () => { + const saved = await savedGame(game.id); + expect(Object.values(saved.playCards ?? {})[0]?.defense?.formation).toBe('3-2'); + }); + + await user.click(screen.getByRole('button', { name: 'Next ›' })); + expect(screen.getByRole('dialog', { name: 'Play cards: Inbounding Stack' })).toBeInTheDocument(); + await user.click(screen.getAllByRole('button', { name: 'Done' }).at(-1)!); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); }); diff --git a/src/screens/GameDayScreen.tsx b/src/screens/GameDayScreen.tsx index 501d08b..8b632be 100644 --- a/src/screens/GameDayScreen.tsx +++ b/src/screens/GameDayScreen.tsx @@ -1,9 +1,11 @@ import { useState } from 'react'; +import { PlayCardsModal } from '../components/PlayCardsModal'; import { Empty, Jersey, PositionChip, PositionCounts, Section, TopBar } from '../components/ui'; import { slug } from '../data/backup'; -import { saveGame, sharedAway } from '../data/repo'; +import { saveGame, sharedAway, updateGamePlayCards } from '../data/repo'; import { shareCsv } from '../data/share'; import type { Game, GameEvent, Player, Team } from '../data/types'; +import { lineupKey } from '../domain/playCards'; import { addSegments, benchFor, @@ -119,6 +121,7 @@ function SharedLive({ game, team, byId }: { game: Game; team: Team; byId: Map -

On court

+
+

On court

+ +
    {current.map((slot) => (
  • @@ -375,6 +383,17 @@ function Live({ {sheet?.kind === 'share' && ( )} + {sheet?.kind === 'play-cards' && ( + void updateGamePlayCards(game.id, lineupKey(current), updater)} + onClose={close} + /> + )} {sheet?.kind === 'player' && player(sheet.playerId) && ( { expect(ids(saved.plan[0]!)).toEqual(ids(game.plan[0]!)); expect(saved.locks).toHaveLength(5); }); + + it('opens play cards from the plan screen and persists changes', async () => { + const user = userEvent.setup(); + const game = await openPlan(); + await user.click(screen.getByRole('button', { name: 'Play cards' })); + expect(screen.getByRole('dialog', { name: 'Play cards: Offense' })).toBeInTheDocument(); + await user.click(screen.getByRole('tab', { name: 'Defense' })); + await user.click(screen.getByRole('radio', { name: 'Box & 1' })); + await waitFor(async () => { + const saved = await savedGame(game.id); + expect(Object.values(saved.playCards ?? {})[0]?.defense?.formation).toBe('box-1'); + }); + await user.click(screen.getByRole('button', { name: 'Done' })); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); }); diff --git a/src/screens/PlanScreen.tsx b/src/screens/PlanScreen.tsx index 576b91a..a08d817 100644 --- a/src/screens/PlanScreen.tsx +++ b/src/screens/PlanScreen.tsx @@ -1,9 +1,11 @@ import { useState } from 'react'; +import { PlayCardsModal } from '../components/PlayCardsModal'; import { Empty, Info, Jersey, PositionChip, PositionChips, Section, Segmented, TopBar } from '../components/ui'; -import { changedSinceSent, getGame, saveGame, sharedAway, updateGame } from '../data/repo'; +import { changedSinceSent, getGame, saveGame, sharedAway, updateGame, updateGamePlayCards } from '../data/repo'; import { shareText } from '../data/share'; import type { Game, Player, Team } from '../data/types'; import { benchFor } from '../domain/changes'; +import { lineupKey } from '../domain/playCards'; import { planText } from '../domain/planText'; import { describeError, describeWarning, planGame, segmentLabel, sortLineup, startGame } from '../domain/game'; import { @@ -65,6 +67,7 @@ interface Notice { type Sheet = | { kind: 'player'; playerId: string } | { kind: 'share' } + | { kind: 'play-cards' } /** Pick the other half of a swap for `playerId`, who is on the court or the bench. */ | { kind: 'swap'; playerId: string; onCourt: boolean }; @@ -227,7 +230,7 @@ function Plan({ game, team, roster, byId }: { game: Game; team: Team; roster: Pl const onCourtIds = new Set(lineup.map((s) => s.playerId)); const bench = players.filter((p) => !onCourtIds.has(p.id)); const hasLocks = (s: number) => game.locks.some((l) => l.segment === s && game.attending.includes(l.playerId)); - const sheetPlayer = sheet && sheet.kind !== 'share' ? byId.get(sheet.playerId) : undefined; + const sheetPlayer = sheet && sheet.kind !== 'share' && sheet.kind !== 'play-cards' ? byId.get(sheet.playerId) : undefined; // Segments grouped by period for the jump strip: Q1 [1 2], Q2 [1 2]… const periods: { label: string; segments: number[] }[] = []; game.plan.forEach((_, i) => { @@ -382,7 +385,12 @@ function Plan({ game, team, roster, byId }: { game: Game; team: Team; roster: Pl )} -

    {isLive && at === game.current ? 'On court now' : 'On court'}

    +
    +

    {isLive && at === game.current ? 'On court now' : 'On court'}

    + +
      {lineup.map((slot) => (
    • @@ -567,6 +575,18 @@ function Plan({ game, team, roster, byId }: { game: Game; team: Team; roster: Pl onClose={close} /> )} + {sheet?.kind === 'play-cards' && label && lineup.length > 0 && ( + void updateGamePlayCards(game.id, lineupKey(lineup), updater)} + onClose={close} + /> + )} {sheet?.kind === 'player' && sheetPlayer && label && ( Date: Thu, 3 Dec 2026 07:37:01 -0600 Subject: [PATCH 2/3] Polish play cards layout, stack clarity, 2-3 spacing, and animation speed --- e2e/playcards.spec.ts | 11 ++- src/components/HalfCourt.tsx | 125 ++++++++++++------------- src/components/PlayCardsModal.test.tsx | 7 +- src/components/PlayCardsModal.tsx | 2 +- src/domain/playCards.test.ts | 12 +-- src/domain/playCards.ts | 42 ++++----- src/styles.css | 91 +++++++----------- 7 files changed, 131 insertions(+), 159 deletions(-) diff --git a/e2e/playcards.spec.ts b/e2e/playcards.spec.ts index 85bd35f..44552b6 100644 --- a/e2e/playcards.spec.ts +++ b/e2e/playcards.spec.ts @@ -25,14 +25,15 @@ test.describe('Play cards on iPhone', () => { await dialog.getByRole('radio', { name: 'Box & 1' }).click(); await expect(dialog.getByRole('radio', { name: 'Box & 1' })).toBeChecked(); - // Move to Inbounding Stack: verify arrows toggle, left/right side, and step animation + // Move to Inbounding Stack: arrows default to off, toggle on/off, left/right side, and step animation await dialog.getByRole('button', { name: 'Next ›' }).click(); await expect(dialog.getByRole('heading', { name: 'Inbounding Stack' })).toBeVisible(); - await expect(dialog.getByTestId('stack-arrow-1')).toBeVisible(); - await dialog.getByRole('button', { name: 'Arrows: On' }).click(); - await expect(dialog.getByTestId('stack-arrow-1')).toHaveCount(0); + await expect(dialog.locator('[data-testid^="stack-arrow-"]')).toHaveCount(0); await dialog.getByRole('button', { name: 'Arrows: Off' }).click(); - await expect(dialog.getByTestId('stack-arrow-1')).toBeVisible(); + await expect(dialog.locator('[data-testid^="stack-arrow-"]')).toHaveCount(4); + await expect(dialog.getByTestId('stack-arrow-3')).toBeVisible(); + await dialog.getByRole('button', { name: 'Arrows: On' }).click(); + await expect(dialog.locator('[data-testid^="stack-arrow-"]')).toHaveCount(0); await dialog.getByRole('radio', { name: 'Left lane' }).click(); await expect(dialog.getByRole('radio', { name: 'Left lane' })).toBeChecked(); diff --git a/src/components/HalfCourt.tsx b/src/components/HalfCourt.tsx index 7b6718e..3735160 100644 --- a/src/components/HalfCourt.tsx +++ b/src/components/HalfCourt.tsx @@ -25,26 +25,32 @@ interface HalfCourtProps { onMove: (playerId: PlayerId, point: CourtPoint) => void; } +/** + * SVG height for a 100-unit-wide half court. Slightly taller than square + * (100×112) so the baseline out-of-bounds strip has headroom and a 4-player + * stack has clean vertical room for larger player names on small phones. + */ +const VIEW_H = 112; +const sy = (y: number) => (y * VIEW_H) / 100; + function arrowPath(move: StackMove): string { const { from, to, control } = move; - if (control) return `M ${from.x} ${from.y} Q ${control.x} ${control.y} ${to.x} ${to.y}`; - return `M ${from.x} ${from.y} L ${to.x} ${to.y}`; -} + const fx = from.x; + const fy = sy(from.y); + const tx = to.x; + const ty = sy(to.y); + const cx = control ? control.x : tx; + const cy = control ? sy(control.y) : ty; + // Pull the start outside the player disc so arrows stay clean and uncluttered. + const sdx = cx - fx; + const sdy = cy - fy; + const slen = Math.hypot(sdx, sdy) || 1; + const padStart = Math.min(6.2, slen * 0.25); + const sx = fx + (sdx / slen) * padStart; + const syStart = fy + (sdy / slen) * padStart; -/** Label point for the small 1–4 step badge along a movement arrow. */ -function badgePoint(move: StackMove): CourtPoint { - const { from, to, control } = move; - if (control) { - // Midpoint of quadratic Bézier at t = 0.5 - return { - x: 0.25 * from.x + 0.5 * control.x + 0.25 * to.x, - y: 0.25 * from.y + 0.5 * control.y + 0.25 * to.y, - }; - } - return { - x: from.x + (to.x - from.x) * 0.58, - y: from.y + (to.y - from.y) * 0.58, - }; + if (control) return `M ${sx} ${syStart} Q ${cx} ${cy} ${tx} ${ty}`; + return `M ${sx} ${syStart} L ${tx} ${ty}`; } /** @@ -135,89 +141,84 @@ export function HalfCourt({ return (
      - {number || pos || '•'} - {number && pos && {pos}} + {!stackPlan && number && pos && {pos}} {isInbounder && ( )} - {showAnnotations && move && ( - - )} {name} diff --git a/src/components/PlayCardsModal.test.tsx b/src/components/PlayCardsModal.test.tsx index e2f8baa..9e35012 100644 --- a/src/components/PlayCardsModal.test.tsx +++ b/src/components/PlayCardsModal.test.tsx @@ -168,14 +168,13 @@ describe('PlayCardsModal', () => { await user.click(screen.getByRole('tab', { name: 'Inbounding Stack' })); expect(screen.getByRole('heading', { name: 'Inbounding Stack' })).toBeInTheDocument(); expect(screen.getByRole('radio', { name: 'Right lane' })).toBeChecked(); + // Arrows default to off for a clean court; toggle on and back off. + expect(screen.queryByTestId('stack-arrow-1')).not.toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Arrows: Off' })); expect(screen.getByTestId('stack-arrow-1')).toBeInTheDocument(); expect(screen.getByTestId('stack-arrow-4')).toBeInTheDocument(); - - // Toggle arrows off and back on await user.click(screen.getByRole('button', { name: 'Arrows: On' })); expect(screen.queryByTestId('stack-arrow-1')).not.toBeInTheDocument(); - await user.click(screen.getByRole('button', { name: 'Arrows: Off' })); - expect(screen.getByTestId('stack-arrow-1')).toBeInTheDocument(); // Toggle Left lane mirrors coordinates const harper = screen.getByRole('button', { name: /Harper/ }); diff --git a/src/components/PlayCardsModal.tsx b/src/components/PlayCardsModal.tsx index 7b139dc..fd92f71 100644 --- a/src/components/PlayCardsModal.tsx +++ b/src/components/PlayCardsModal.tsx @@ -72,7 +72,7 @@ export function PlayCardsModal({ onClose, }: PlayCardsModalProps) { const [cardIndex, setCardIndex] = useState(0); - const [showAnnotations, setShowAnnotations] = useState(true); + const [showAnnotations, setShowAnnotations] = useState(false); const [animStage, setAnimStage] = useState(0); const touchStart = useRef<{ x: number; y: number } | null>(null); diff --git a/src/domain/playCards.test.ts b/src/domain/playCards.test.ts index ff2df64..beb4399 100644 --- a/src/domain/playCards.test.ts +++ b/src/domain/playCards.test.ts @@ -76,13 +76,13 @@ describe('offense default positions', () => { }); describe('defense default positions', () => { - it('places 2-3 zone with guards up top, center middle low, forwards low outside', () => { + it('places 2-3 zone with guards up top, center middle low, forwards tight to the lane and low block', () => { const pos = defaultDefensePositions(lineup2G2F1C, '2-3'); expect([pos.g1!.x, pos.g2!.x].sort((a, b) => a - b)).toEqual([35, 65]); expect(pos.g1!.y).toBe(54); - expect(pos.c1).toEqual({ x: 50, y: 25 }); - expect([pos.f1!.x, pos.f2!.x].sort((a, b) => a - b)).toEqual([21, 79]); - expect(pos.f1!.y).toBe(29); + expect(pos.c1).toEqual({ x: 50, y: 29 }); + expect([pos.f1!.x, pos.f2!.x].sort((a, b) => a - b)).toEqual([28, 72]); + expect(pos.f1!.y).toBe(30); }); it('places 3-2 zone with guards and forwards up top, centers down low', () => { @@ -202,14 +202,14 @@ describe('inbounding stack defaults, mirroring, annotations and animation', () = const resolved = resolvePlayCards(lineup2G2F1C, { offense: { formation: '1-2-2', positions: { g1: { x: 120, y: 3 } } }, defense: { formation: 'box-1', positions: { c1: { x: 40, y: 30 } } }, - stack: { side: 'left', positions: { c1: { x: 37, y: 5 } } }, + stack: { side: 'left', positions: { c1: { x: 37, y: 7.5 } } }, }); expect(resolved.offense.formation).toBe('1-2-2'); expect(resolved.offense.positions.g1).toEqual(clampPoint({ x: 120, y: 3 }, false)); expect(resolved.defense.formation).toBe('box-1'); expect(resolved.defense.positions.c1).toEqual({ x: 40, y: 30 }); expect(resolved.stack.side).toBe('left'); - expect(resolved.stack.positions.c1).toEqual({ x: 37, y: 5 }); + expect(resolved.stack.positions.c1).toEqual({ x: 37, y: 7.5 }); }); }); diff --git a/src/domain/playCards.ts b/src/domain/playCards.ts index 31906b8..04bd71c 100644 --- a/src/domain/playCards.ts +++ b/src/domain/playCards.ts @@ -21,30 +21,30 @@ import type { Lineup, PlayerId } from '../engine'; export const CARD_ORDER: readonly PlayCardKind[] = ['offense', 'defense', 'stack']; export const COURT = { - baselineY: 10, + baselineY: 13.5, halfCourtY: 96, leftSidelineX: 4, rightSidelineX: 96, hoopX: 50, - hoopY: 18.5, - backboardY: 14.5, + hoopY: 21.5, + backboardY: 17.5, laneLeftX: 37, laneRightX: 63, - freeThrowY: 46, + freeThrowY: 47, /** Three lane hash marks going away from the baseline toward the free-throw line. */ - laneHashesY: [22, 29, 36] as const, - /** Inbounder rests behind the baseline out-of-bounds. */ - inbounderY: 5.5, + laneHashesY: [24, 30, 36] as const, + /** Inbounder rests behind the baseline out-of-bounds with headroom so the icon never clips. */ + inbounderY: 7.5, } as const; export const THIRD_HASH_Y = COURT.laneHashesY[2]; /** Bounds when dragging a player token on Offense/Defense vs Stack (which allows out-of-bounds). */ export const COURT_BOUNDS = { - minX: 7, - maxX: 93, - minYInbounds: 15, - minYStack: 4.5, + minX: 8, + maxX: 92, + minYInbounds: 18, + minYStack: 6.5, maxY: 92, } as const; @@ -175,10 +175,10 @@ const DEFENSE_2_3: readonly WeightedSlot[] = [ { point: { x: 35, y: 54 }, weights: { G: 30, F: 18, C: 1, other: 10 } }, { point: { x: 65, y: 54 }, weights: { G: 30, F: 18, C: 1, other: 10 } }, // 1 center middle low - { point: { x: 50, y: 25 }, weights: { G: 1, F: 15, C: 30, other: 10 } }, - // 2 forwards low outside - { point: { x: 21, y: 29 }, weights: { G: 5, F: 30, C: 20, other: 10 } }, - { point: { x: 79, y: 29 }, weights: { G: 5, F: 30, C: 20, other: 10 } }, + { point: { x: 50, y: 29 }, weights: { G: 1, F: 15, C: 30, other: 10 } }, + // 2 forwards low outside, tight to the lane and low block + { point: { x: 28, y: 30 }, weights: { G: 5, F: 30, C: 20, other: 10 } }, + { point: { x: 72, y: 30 }, weights: { G: 5, F: 30, C: 20, other: 10 } }, ]; const DEFENSE_3_2: readonly WeightedSlot[] = [ @@ -217,8 +217,8 @@ export function defaultDefensePositions( export const DEFAULT_STACK_SIDE: StackSide = 'right'; -/** Vertical coordinates of the 4 players in the stack, starting at the 3rd hash mark. */ -export const STACK_LINE_Y = [THIRD_HASH_Y, THIRD_HASH_Y + 11, THIRD_HASH_Y + 22, THIRD_HASH_Y + 33] as const; +/** Vertical coordinates of the 4 players in the stack, starting at the 3rd hash mark with generous spacing so names never overlap. */ +export const STACK_LINE_Y = [THIRD_HASH_Y, THIRD_HASH_Y + 14.5, THIRD_HASH_Y + 29, THIRD_HASH_Y + 43.5] as const; export function stackLaneX(side: StackSide): number { return side === 'right' ? COURT.laneRightX : COURT.laneLeftX; @@ -372,15 +372,15 @@ export function computeStackPlan( return { playerId: slot.playerId, step, from, to, label: 'Toward basket' }; } if (step === 3) { - const to = clampPoint({ x: from.x, y: Math.max(21, from.y - 34) }, false); - // Slight arc toward the outside of the stack so the arrow is clearly visible before players clear out. + const to = clampPoint({ x: from.x, y: Math.max(23, from.y - 40) }, false); + // Gentle arc outside the stack so the arrow stays clear of stacked players. const control = clampPoint( - { x: from.x + awayDir * 9, y: (from.y + to.y) / 2 }, + { x: from.x + awayDir * 11, y: (from.y + to.y) / 2 }, false, ); return { playerId: slot.playerId, step, from, to, control, label: 'Forward to inbounder' }; } - const to = clampPoint({ x: from.x, y: from.y + 19 }, false); + const to = clampPoint({ x: from.x, y: from.y + 13 }, false); return { playerId: slot.playerId, step, from, to, label: 'Pop back' }; }); diff --git a/src/styles.css b/src/styles.css index 8e6a445..0424d71 100644 --- a/src/styles.css +++ b/src/styles.css @@ -2633,7 +2633,8 @@ textarea:focus { flex-direction: column; gap: 8px; height: var(--app-height, 100dvh); - padding: calc(var(--safe-top) + 10px) 12px calc(var(--safe-bottom) + 12px); + /* Extra top clearance below iOS's status-bar blur haze so the top row stays sharp. */ + padding: calc(var(--safe-top) + 22px) 10px calc(var(--safe-bottom) + 12px); background: var(--bg); color: var(--text); overflow: hidden; @@ -2641,6 +2642,12 @@ textarea:focus { user-select: none; } +@media (max-height: 600px) { + .play-cards { + padding-top: calc(var(--safe-top) + 10px); + } +} + :root[data-theme='light'] .play-cards { --court-bg: #f6ead7; --court-oob: #e5ecf4; @@ -2778,11 +2785,11 @@ textarea:focus { .court-stage { position: relative; - width: min(100cqw, 100cqh); - height: min(100cqw, 100cqh); + width: min(100cqw, calc(100cqh * 100 / 112)); + height: min(100cqh, calc(100cqw * 112 / 100)); max-width: 100%; max-height: 100%; - aspect-ratio: 1 / 1; + aspect-ratio: 100 / 112; border-radius: 14px; overflow: hidden; border: 1px solid var(--line); @@ -2861,21 +2868,19 @@ textarea:focus { .court-arrow { fill: none; stroke: var(--court-arrow); - stroke-width: 1.05; - stroke-dasharray: 2.2 1.5; + stroke-width: 0.9; stroke-linecap: round; - opacity: 0.9; + opacity: 0.78; } .court-annotation.active .court-arrow { stroke: var(--court-arrow-active); - stroke-width: 1.4; - stroke-dasharray: none; + stroke-width: 1.25; opacity: 1; } .court-annotation.done .court-arrow { - opacity: 0.45; + opacity: 0.25; } .court-arrow-head { @@ -2886,20 +2891,6 @@ textarea:focus { fill: var(--court-arrow-active); } -.court-step-bg { - fill: var(--court-arrow); -} - -.court-annotation.active .court-step-bg { - fill: var(--court-arrow-active); -} - -.court-step-num { - fill: #ffffff; - font-size: 3.1px; - font-weight: 800; -} - /* Draggable player tokens on the half court */ .player-token { position: absolute; @@ -2914,7 +2905,11 @@ textarea:focus { cursor: grab; touch-action: none; z-index: 2; - transition: left 550ms cubic-bezier(0.22, 1, 0.36, 1), top 550ms cubic-bezier(0.22, 1, 0.36, 1); + transition: left 350ms cubic-bezier(0.22, 1, 0.36, 1), top 350ms cubic-bezier(0.22, 1, 0.36, 1); +} + +.court-stage[data-animating='true'] .player-token { + transition: left 1400ms cubic-bezier(0.25, 0.8, 0.25, 1), top 1400ms cubic-bezier(0.25, 0.8, 0.25, 1); } .player-token.dragging { @@ -2933,8 +2928,8 @@ textarea:focus { display: flex; align-items: center; justify-content: center; - width: clamp(32px, 8.5cqw, 42px); - height: clamp(32px, 8.5cqw, 42px); + width: clamp(34px, 9.2cqw, 42px); + height: clamp(34px, 9.2cqw, 42px); border-radius: 50%; background: var(--surface); border: 2.5px solid var(--accent); @@ -2960,7 +2955,7 @@ textarea:focus { } .token-badge { - font-size: clamp(12px, 3.3cqw, 15px); + font-size: clamp(14px, 3.8cqw, 17px); line-height: 1; } @@ -2973,53 +2968,33 @@ textarea:focus { background: var(--surface-2); border: 1px solid var(--line); color: var(--text-2); - font-size: 9px; + font-size: 10px; font-weight: 800; line-height: 1.1; } .token-ball { position: absolute; - top: -7px; + top: -6px; right: -7px; font-size: 13px; line-height: 1; } -.token-step { - position: absolute; - top: -6px; - left: -6px; - display: inline-flex; - align-items: center; - justify-content: center; - width: 16px; - height: 16px; - border-radius: 50%; - background: var(--court-arrow); - color: #ffffff; - font-size: 10px; - font-weight: 800; - line-height: 1; -} - -.player-token.moving .token-step { - background: var(--court-arrow-active); -} - .token-name { - max-width: 74px; - padding: 1px 6px; + max-width: 96px; + padding: 2px 8px; border-radius: 999px; - background: rgba(11, 15, 23, 0.86); + background: rgba(11, 15, 23, 0.92); + border: 1px solid rgba(255, 255, 255, 0.14); color: #f4f6fb; - font-size: clamp(10px, 2.7cqw, 12px); - font-weight: 700; - line-height: 1.25; + font-size: clamp(13px, 3.8cqw, 15px); + font-weight: 800; + line-height: 1.2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35); + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4); } :root[data-theme='light'] .token-name { From bd92b2ed59718357a8eb8289015b858dff093371 Mon Sep 17 00:00:00 2001 From: Matt Batchelder Date: Thu, 3 Dec 2026 07:50:25 -0600 Subject: [PATCH 3/3] Make play cards court edge-to-edge and enlarge player icons and names --- src/components/HalfCourt.tsx | 9 ++++---- src/domain/playCards.ts | 12 +++++------ src/styles.css | 41 ++++++++++++++++++++++-------------- 3 files changed, 35 insertions(+), 27 deletions(-) diff --git a/src/components/HalfCourt.tsx b/src/components/HalfCourt.tsx index 3735160..502a656 100644 --- a/src/components/HalfCourt.tsx +++ b/src/components/HalfCourt.tsx @@ -26,11 +26,10 @@ interface HalfCourtProps { } /** - * SVG height for a 100-unit-wide half court. Slightly taller than square - * (100×112) so the baseline out-of-bounds strip has headroom and a 4-player - * stack has clean vertical room for larger player names on small phones. + * SVG height for a 100-unit-wide half court (100×130) so the court fills the + * phone screen generously and player discs + names stay large and huddle-readable. */ -const VIEW_H = 112; +const VIEW_H = 130; const sy = (y: number) => (y * VIEW_H) / 100; function arrowPath(move: StackMove): string { @@ -200,7 +199,7 @@ export function HalfCourt({ {/* 3-point arc */} diff --git a/src/domain/playCards.ts b/src/domain/playCards.ts index 04bd71c..217a8a2 100644 --- a/src/domain/playCards.ts +++ b/src/domain/playCards.ts @@ -22,15 +22,15 @@ export const CARD_ORDER: readonly PlayCardKind[] = ['offense', 'defense', 'stack export const COURT = { baselineY: 13.5, - halfCourtY: 96, - leftSidelineX: 4, - rightSidelineX: 96, + halfCourtY: 97.5, + leftSidelineX: 1.5, + rightSidelineX: 98.5, hoopX: 50, - hoopY: 21.5, - backboardY: 17.5, + hoopY: 20.5, + backboardY: 17, laneLeftX: 37, laneRightX: 63, - freeThrowY: 47, + freeThrowY: 46, /** Three lane hash marks going away from the baseline toward the free-throw line. */ laneHashesY: [24, 30, 36] as const, /** Inbounder rests behind the baseline out-of-bounds with headroom so the icon never clips. */ diff --git a/src/styles.css b/src/styles.css index 0424d71..0c115a9 100644 --- a/src/styles.css +++ b/src/styles.css @@ -2779,18 +2779,27 @@ textarea:focus { justify-content: center; container-type: size; max-width: 680px; - width: 100%; - margin: 0 auto; + /* Full-bleed horizontally on phones so the court and player tokens are as large as possible. */ + width: calc(100% + 20px); + margin: 0 -10px; +} + +@media (min-width: 700px) { + .play-cards-body { + width: 100%; + margin: 0 auto; + } } .court-stage { position: relative; - width: min(100cqw, calc(100cqh * 100 / 112)); - height: min(100cqh, calc(100cqw * 112 / 100)); + container-type: inline-size; + width: min(100cqw, calc(100cqh * 100 / 130)); + height: min(100cqh, calc(100cqw * 130 / 100)); max-width: 100%; max-height: 100%; - aspect-ratio: 100 / 112; - border-radius: 14px; + aspect-ratio: 100 / 130; + border-radius: 12px; overflow: hidden; border: 1px solid var(--line); background: var(--court-oob); @@ -2928,11 +2937,11 @@ textarea:focus { display: flex; align-items: center; justify-content: center; - width: clamp(34px, 9.2cqw, 42px); - height: clamp(34px, 9.2cqw, 42px); + width: clamp(32px, 11.4cqw, 52px); + height: clamp(32px, 11.4cqw, 52px); border-radius: 50%; background: var(--surface); - border: 2.5px solid var(--accent); + border: 3px solid var(--accent); box-shadow: 0 3px 10px rgba(0, 0, 0, 0.45); color: var(--text); font-weight: 800; @@ -2955,7 +2964,7 @@ textarea:focus { } .token-badge { - font-size: clamp(14px, 3.8cqw, 17px); + font-size: clamp(14px, 4.7cqw, 21px); line-height: 1; } @@ -2963,12 +2972,12 @@ textarea:focus { position: absolute; bottom: -4px; right: -6px; - padding: 1px 4px; + padding: 1px 5px; border-radius: 5px; background: var(--surface-2); border: 1px solid var(--line); color: var(--text-2); - font-size: 10px; + font-size: 11px; font-weight: 800; line-height: 1.1; } @@ -2977,18 +2986,18 @@ textarea:focus { position: absolute; top: -6px; right: -7px; - font-size: 13px; + font-size: 15px; line-height: 1; } .token-name { - max-width: 96px; - padding: 2px 8px; + max-width: 114px; + padding: 2px 10px; border-radius: 999px; background: rgba(11, 15, 23, 0.92); border: 1px solid rgba(255, 255, 255, 0.14); color: #f4f6fb; - font-size: clamp(13px, 3.8cqw, 15px); + font-size: clamp(13px, 4.4cqw, 18px); font-weight: 800; line-height: 1.2; white-space: nowrap;