Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 1x 8x 8x 8x 2x 2x 1x 1x 1x 13x 13x 36x 125x 125x 125x 125x 36x 13x 13x 1x 1x 1x 8x 8x 24x 61x 61x 61x 61x 24x 8x 8x 1x 1x 1x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | 'use client'
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from 'react'
import { css } from '../../../styled-system/css'
import { HoverAvatar } from './HoverAvatar'
/** Pixel dimensions for a single card, computed from available container space */
type CardSize = { w: number; h: number }
/**
* Compute optimal card pixel size given available container space and grid dimensions.
* Respects 3:4 aspect ratio, gap spacing, and min/max constraints.
*/
export function computeCardSize(
availW: number,
availH: number,
cols: number,
rows: number,
gap: number = 6
): CardSize {
const hGaps = (cols - 1) * gap + 16 // 8px padding each side on grid
const vGaps = (rows - 1) * gap
const maxFromWidth = (availW - hGaps) / cols
// aspect ratio 3:4 → card height = cardW * 4/3, so cardW = availH_per_row * 3/4
const maxFromHeight = ((availH - vGaps) / rows) * (3 / 4)
let cardW = Math.min(maxFromWidth, maxFromHeight)
cardW = Math.max(cardW, 60) // floor: still usable
cardW = Math.min(cardW, 200) // ceiling: existing maxWidth
return { w: cardW, h: cardW * (4 / 3) }
}
// Grid calculation utilities
function calculateOptimalGrid(cards: number, aspectRatio: number, config: any) {
// For consistent grid layout, we need to ensure r×c = totalCards
// Choose columns based on viewport, then calculate exact rows needed
let targetColumns
const width = typeof window !== 'undefined' ? window.innerWidth : 1024
// Choose column count based on viewport
if (aspectRatio >= 1.6 && width >= 1200) {
// Ultra-wide: prefer wider grids
targetColumns = config.landscapeColumns || config.desktopColumns || 6
} else if (aspectRatio >= 1.33 && width >= 768) {
// Desktop/landscape: use desktop columns
targetColumns = config.desktopColumns || config.landscapeColumns || 6
} else if (aspectRatio >= 1.0 && width >= 600) {
// Tablet: use tablet columns
targetColumns = config.tabletColumns || config.desktopColumns || 4
} else {
// Mobile: use mobile columns
targetColumns = config.mobileColumns || 3
}
// Calculate exact rows needed for this column count
const rows = Math.ceil(cards / targetColumns)
// If we have leftover cards that would create an uneven bottom row,
// try to redistribute for a more balanced grid
const leftoverCards = cards % targetColumns
if (leftoverCards > 0 && leftoverCards < targetColumns / 2 && targetColumns > 3) {
// Try one less column for a more balanced grid
const altColumns = targetColumns - 1
const altRows = Math.ceil(cards / altColumns)
const altLeftover = cards % altColumns
// Use alternative if it creates a more balanced grid
if (altLeftover === 0 || altLeftover > leftoverCards) {
return { columns: altColumns, rows: altRows }
}
}
return { columns: targetColumns, rows }
}
// Orientation rotation utilities
export function normalizeAngleDelta(from: number, to: number): 90 | -90 | 180 {
const delta = ((((to - from) % 360) + 540) % 360) - 180
if (delta === 90) return 90
if (delta === -90) return -90
return 180
}
/** Counter-clockwise rotation (counters CW device rotation): (c, r) → (cols-1-c)*rows + r */
export function rotateCCW<T>(items: T[], cols: number, rows: number): T[] {
const result = new Array<T>(items.length)
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const srcIdx = r * cols + c
const dstIdx = (cols - 1 - c) * rows + r
result[dstIdx] = items[srcIdx]
}
}
return result
}
/** Clockwise rotation (counters CCW device rotation): (c, r) → c*rows + (rows-1-r) */
export function rotateCW<T>(items: T[], cols: number, rows: number): T[] {
const result = new Array<T>(items.length)
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const srcIdx = r * cols + c
const dstIdx = c * rows + (rows - 1 - r)
result[dstIdx] = items[srcIdx]
}
}
return result
}
/** 180° rotation: reverse the array */
export function rotate180<T>(items: T[]): T[] {
return [...items].reverse()
}
// FLIP animation hook for smooth card position transitions
function useFlipAnimation(cardRefs: React.RefObject<Map<string, HTMLElement>>, triggerKey: number) {
const positionsRef = useRef<Map<string, DOMRect>>(new Map())
const capturePositions = useCallback(() => {
const positions = new Map<string, DOMRect>()
cardRefs.current?.forEach((el, id) => {
positions.set(id, el.getBoundingClientRect())
})
positionsRef.current = positions
}, [cardRefs])
// Play FLIP animation after state update causes re-render
useLayoutEffect(() => {
if (triggerKey === 0) return // Skip initial render
const oldPositions = positionsRef.current
if (oldPositions.size === 0) return
cardRefs.current?.forEach((el, id) => {
const oldRect = oldPositions.get(id)
if (!oldRect) return
const newRect = el.getBoundingClientRect()
const dx = oldRect.left - newRect.left
const dy = oldRect.top - newRect.top
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return
el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'translate(0, 0)' }], {
duration: 400,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
})
})
}, [triggerKey, cardRefs])
return { capturePositions }
}
// Custom hook to calculate proper grid dimensions for consistent r×c layout
function useGridDimensions(gridConfig: any, totalCards: number, locked: boolean) {
const [gridDimensions, setGridDimensions] = useState(() => {
// Calculate optimal rows and columns based on total cards and viewport
if (typeof window !== 'undefined') {
const aspectRatio = window.innerWidth / window.innerHeight
return calculateOptimalGrid(totalCards, aspectRatio, gridConfig)
}
return {
columns: gridConfig.mobileColumns || 3,
rows: Math.ceil(totalCards / (gridConfig.mobileColumns || 3)),
}
})
useEffect(() => {
if (locked) return // Don't recalculate during gameplay
const updateGrid = () => {
if (typeof window === 'undefined') return
const aspectRatio = window.innerWidth / window.innerHeight
setGridDimensions(calculateOptimalGrid(totalCards, aspectRatio, gridConfig))
}
updateGrid()
window.addEventListener('resize', updateGrid)
return () => window.removeEventListener('resize', updateGrid)
}, [gridConfig, totalCards, locked])
return gridDimensions
}
// Type definitions
export interface MemoryGridState<TCard = any> {
gameCards: TCard[]
flippedCards: TCard[]
showMismatchFeedback: boolean
isProcessingMove: boolean
playerMetadata?: Record<string, { emoji: string; name: string; color?: string; userId?: string }>
playerHovers?: Record<string, string | null>
currentPlayer?: string
}
export interface MemoryGridProps<TCard = any> {
// Core game state and actions
state: MemoryGridState<TCard>
gridConfig: any
flipCard: (cardId: string) => void
// Multiplayer presence features (optional)
enableMultiplayerPresence?: boolean
hoverCard?: (cardId: string | null) => void
viewerId?: string | null
gameMode?: 'single' | 'multiplayer'
// Smart dimming (optional) — externalizes game-specific dimming logic
shouldDimCard?: (card: TCard, firstFlippedCard: TCard) => boolean
/** Lock grid dimensions to prevent reshuffle during gameplay (default: true) */
isLocked?: boolean
// Card rendering
renderCard: (props: {
card: TCard
isFlipped: boolean
isMatched: boolean
onClick: () => void
disabled: boolean
}) => ReactNode
}
/**
* Unified MemoryGrid component that works for both single-player and multiplayer modes.
* Conditionally enables multiplayer presence features (hover avatars) when configured.
*/
export function MemoryGrid<TCard extends { id: string; matched: boolean }>({
state,
gridConfig,
flipCard,
renderCard,
enableMultiplayerPresence = false,
hoverCard,
viewerId,
gameMode = 'single',
shouldDimCard,
isLocked,
}: MemoryGridProps<TCard>) {
const locked = isLocked ?? true
const cardRefs = useRef<Map<string, HTMLElement>>(new Map())
const gridDimensions = useGridDimensions(gridConfig, state.gameCards.length, locked)
// --- Orientation-aware grid rotation state ---
const [orientationState, setOrientationState] = useState<{
cardOrder: (string | null)[] // Card IDs (null = empty cell spacer)
cols: number
rows: number
} | null>(null)
const [rotationCount, setRotationCount] = useState(0)
const prevAngleRef = useRef<number | null>(null)
// FLIP animation
const { capturePositions } = useFlipAnimation(cardRefs, rotationCount)
// --- Container-aware card sizing ---
const [cardSize, setCardSize] = useState<CardSize | null>(null)
const gridContainerRef = useRef<HTMLDivElement>(null)
const outerContainerRef = useRef<HTMLDivElement>(null)
// Check if it's the local player's turn (for multiplayer mode)
const isMyTurn = useMemo(() => {
if (!enableMultiplayerPresence || gameMode === 'single') return true
const currentPlayerMetadata = state.playerMetadata?.[state.currentPlayer || '']
return currentPlayerMetadata?.userId === viewerId
}, [enableMultiplayerPresence, gameMode, state.currentPlayer, state.playerMetadata, viewerId])
// Build card ID → card lookup for rendering orientation-reordered cards
const cardById = useMemo(() => {
const map = new Map<string, TCard>()
for (const card of state.gameCards) {
map.set(card.id, card)
}
return map
}, [state.gameCards])
// Effective grid dimensions and card order
const effectiveCols = orientationState?.cols ?? gridDimensions.columns
const effectiveRows = orientationState?.rows ?? gridDimensions.rows
const displayOrder: (string | null)[] = useMemo(() => {
if (orientationState) return orientationState.cardOrder
// Pad with nulls for uneven grids
const totalCells = gridDimensions.columns * gridDimensions.rows
const order: (string | null)[] = state.gameCards.map((c) => c.id)
while (order.length < totalCells) order.push(null)
return order
}, [orientationState, gridDimensions.columns, gridDimensions.rows, state.gameCards])
// --- Orientation change listener ---
useEffect(() => {
if (!locked) return
if (typeof screen === 'undefined' || !screen.orientation) return
const handleOrientationChange = () => {
const newAngle = screen.orientation.angle
const prevAngle = prevAngleRef.current
if (prevAngle === null) {
prevAngleRef.current = newAngle
return
}
prevAngleRef.current = newAngle
const delta = normalizeAngleDelta(prevAngle, newAngle)
// Capture current card positions for FLIP
capturePositions()
setOrientationState((prev) => {
const currentCols = prev?.cols ?? gridDimensions.columns
const currentRows = prev?.rows ?? gridDimensions.rows
const totalCells = currentCols * currentRows
const currentOrder: (string | null)[] =
prev?.cardOrder ??
(() => {
const order: (string | null)[] = state.gameCards.map((c) => c.id)
while (order.length < totalCells) order.push(null)
return order
})()
let newOrder: (string | null)[]
let newCols: number
let newRows: number
if (delta === 90) {
// Device rotated CW → counter-rotate CCW
newOrder = rotateCCW(currentOrder, currentCols, currentRows)
newCols = currentRows
newRows = currentCols
} else if (delta === -90) {
// Device rotated CCW → counter-rotate CW
newOrder = rotateCW(currentOrder, currentCols, currentRows)
newCols = currentRows
newRows = currentCols
} else {
// 180°
newOrder = rotate180(currentOrder)
newCols = currentCols
newRows = currentRows
}
return { cardOrder: newOrder, cols: newCols, rows: newRows }
})
setRotationCount((c) => c + 1)
}
// Initialize angle tracking
prevAngleRef.current = screen.orientation.angle
screen.orientation.addEventListener('change', handleOrientationChange)
return () => {
screen.orientation.removeEventListener('change', handleOrientationChange)
}
}, [locked, gridDimensions.columns, gridDimensions.rows, state.gameCards, capturePositions])
// Reset orientation state when unlocked (game reset)
useEffect(() => {
if (!locked) {
setOrientationState(null)
setRotationCount(0)
}
}, [locked])
// --- Compute card pixel size from available container space ---
useEffect(() => {
const outer = outerContainerRef.current
if (!outer) return
const onResize = () => {
const styles = getComputedStyle(outer)
const padX = (parseFloat(styles.paddingLeft) || 0) + (parseFloat(styles.paddingRight) || 0)
const padY = (parseFloat(styles.paddingTop) || 0) + (parseFloat(styles.paddingBottom) || 0)
const availW = Math.max(0, outer.clientWidth - padX)
const availH = Math.max(0, outer.clientHeight - padY)
setCardSize(computeCardSize(availW, availH, effectiveCols, effectiveRows))
}
const observer = new ResizeObserver(onResize)
observer.observe(outer)
return () => observer.disconnect()
}, [effectiveCols, effectiveRows])
if (!state.gameCards.length) {
return null
}
const handleCardClick = (cardId: string) => {
flipCard(cardId)
}
// Get player metadata for hover avatars
const getPlayerHoverInfo = (playerId: string) => {
const player = state.playerMetadata?.[playerId]
return player
? {
emoji: player.emoji,
name: player.name,
color: player.color,
}
: null
}
// Set card ref callback — always populate for FLIP animation
const setCardRef = (cardId: string) => (element: HTMLDivElement | null) => {
if (element) {
cardRefs.current.set(cardId, element)
} else {
cardRefs.current.delete(cardId)
}
}
return (
<div
ref={outerContainerRef}
className={css({
padding: { base: '12px', sm: '16px', md: '20px' },
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: { base: '12px', sm: '16px', md: '20px' },
// Fill parent so ResizeObserver tracks available space on viewport resize
flex: 1,
minHeight: 0,
width: '100%',
overflow: 'hidden',
})}
>
{/* Cards Grid - Consistent r×c Layout */}
<div
ref={gridContainerRef}
data-element="matching-grid"
data-game-idle={
!state.isProcessingMove && !state.showMismatchFeedback && state.flippedCards.length === 0
? 'true'
: 'false'
}
data-game-processing={state.isProcessingMove ? 'true' : 'false'}
data-game-mismatch-feedback={state.showMismatchFeedback ? 'true' : 'false'}
data-game-flipped-count={state.flippedCards.length}
style={{
display: 'grid',
gap: '6px',
justifyContent: 'center',
maxWidth: '100%',
margin: '0 auto',
padding: '0 8px',
gridTemplateColumns: cardSize
? `repeat(${effectiveCols}, ${cardSize.w}px)`
: `repeat(${effectiveCols}, 1fr)`,
gridTemplateRows: cardSize
? `repeat(${effectiveRows}, ${cardSize.h}px)`
: `repeat(${effectiveRows}, 1fr)`,
}}
>
{displayOrder.map((cardId, idx) => {
if (cardId === null) {
// Invisible spacer for uneven grid rotation
return <div key={`spacer-${idx}`} style={{ visibility: 'hidden' }} />
}
const card = cardById.get(cardId)
if (!card) return null
const isFlipped = state.flippedCards.some((c) => c.id === card.id) || card.matched
const isMatched = card.matched
const shouldShake =
state.showMismatchFeedback && state.flippedCards.some((c) => c.id === card.id)
// Smart card filtering via shouldDimCard prop
let isValidForSelection = true
let isDimmed = false
if (shouldDimCard && state.flippedCards.length === 1 && !isFlipped && !isMatched) {
const firstFlippedCard = state.flippedCards[0]
isDimmed = shouldDimCard(card, firstFlippedCard)
isValidForSelection = !isDimmed
}
return (
<div
key={card.id}
ref={setCardRef(card.id)}
data-component="matching-card"
data-card-id={card.id}
data-card-number={(card as any).number}
data-card-type={(card as any).type}
data-card-matched={isMatched ? 'true' : 'false'}
data-card-flipped={isFlipped ? 'true' : 'false'}
className={css({
width: '100%',
height: '100%',
opacity: isDimmed ? 0.3 : 1,
transition: 'opacity 0.3s ease',
filter: isDimmed ? 'grayscale(0.7)' : 'none',
position: 'relative',
animation: shouldShake ? 'cardShake 0.5s ease-in-out' : 'none',
})}
onMouseEnter={
enableMultiplayerPresence && hoverCard
? () => {
if (!isMatched && isMyTurn) {
hoverCard(card.id)
}
}
: undefined
}
onMouseLeave={
enableMultiplayerPresence && hoverCard
? () => {
if (!isMatched && isMyTurn) {
hoverCard(null)
}
}
: undefined
}
>
{renderCard({
card,
isFlipped,
isMatched,
onClick: () => (isValidForSelection ? handleCardClick(card.id) : undefined),
disabled: state.isProcessingMove || !isValidForSelection,
})}
</div>
)
})}
</div>
{/* Processing Overlay */}
{state.isProcessingMove && (
<div
className={css({
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: 'rgba(0,0,0,0.1)',
zIndex: 999,
pointerEvents: 'none',
})}
/>
)}
{/* Animated Hover Avatars (multiplayer only) */}
{enableMultiplayerPresence &&
state.playerHovers &&
Object.entries(state.playerHovers)
.filter(([playerId]) => {
const playerMetadata = state.playerMetadata?.[playerId]
const isRemotePlayer = playerMetadata?.userId !== viewerId
const isCurrentPlayer = playerId === state.currentPlayer
return isRemotePlayer && isCurrentPlayer
})
.map(([playerId, cardId]) => {
const playerInfo = getPlayerHoverInfo(playerId)
const cardElement = cardId ? (cardRefs.current.get(cardId) ?? null) : null
const isPlayersTurn = state.currentPlayer === playerId
const hoveredCard = cardId ? state.gameCards.find((c) => c.id === cardId) : null
const isCardFlipped = hoveredCard
? state.flippedCards.some((c) => c.id === hoveredCard.id) || hoveredCard.matched
: false
if (!playerInfo) return null
return (
<HoverAvatar
key={playerId}
playerId={playerId}
playerInfo={playerInfo}
cardElement={cardElement}
isPlayersTurn={isPlayersTurn}
isCardFlipped={isCardFlipped}
/>
)
})}
</div>
)
}
// Add shake animation for mismatched cards
const cardShakeAnimation = `
@keyframes cardShake {
0%, 100% { transform: translateX(0) rotate(0deg); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-8px) rotate(-2deg); }
20%, 40%, 60%, 80% { transform: translateX(8px) rotate(2deg); }
}
`
// Inject animation styles
if (typeof document !== 'undefined' && !document.getElementById('memory-grid-animations')) {
const style = document.createElement('style')
style.id = 'memory-grid-animations'
style.textContent = cardShakeAnimation
document.head.appendChild(style)
}
|