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..44552b6 --- /dev/null +++ b/e2e/playcards.spec.ts @@ -0,0 +1,65 @@ +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: 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.locator('[data-testid^="stack-arrow-"]')).toHaveCount(0); + await dialog.getByRole('button', { name: 'Arrows: Off' }).click(); + 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(); + + // 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..502a656 --- /dev/null +++ b/src/components/HalfCourt.tsx @@ -0,0 +1,331 @@ +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; +} + +/** + * 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 = 130; +const sy = (y: number) => (y * VIEW_H) / 100; + +function arrowPath(move: StackMove): string { + const { from, to, control } = move; + 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; + + if (control) return `M ${sx} ${syStart} Q ${cx} ${cy} ${tx} ${ty}`; + return `M ${sx} ${syStart} L ${tx} ${ty}`; +} + +/** + * 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..9e35012 --- /dev/null +++ b/src/components/PlayCardsModal.test.tsx @@ -0,0 +1,208 @@ +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(); + // 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(); + await user.click(screen.getByRole('button', { name: 'Arrows: On' })); + expect(screen.queryByTestId('stack-arrow-1')).not.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..fd92f71 --- /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(false); + 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..beb4399 --- /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 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: 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', () => { + 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: 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: 7.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..217a8a2 --- /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: 13.5, + halfCourtY: 97.5, + leftSidelineX: 1.5, + rightSidelineX: 98.5, + hoopX: 50, + hoopY: 20.5, + backboardY: 17, + laneLeftX: 37, + laneRightX: 63, + 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. */ + 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: 8, + maxX: 92, + minYInbounds: 18, + minYStack: 6.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: 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[] = [ + // 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 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; +} + +/** + * 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(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 * 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 + 13 }, 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 && (