Compare commits

...

12 Commits

Author SHA1 Message Date
semantic-release-bot
b5d0bee120 chore(release): 2.7.3 [skip ci]
## [2.7.3](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.7.2...v2.7.3) (2025-10-08)

### Bug Fixes

* set room sessions to use /arcade/room URL ([9dac431](9dac431c1f))
2025-10-08 15:44:46 +00:00
Thomas Hallock
9dac431c1f fix: set room sessions to use /arcade/room URL
When creating an arcade session for a room-based game, the gameUrl was
hardcoded to '/arcade/matching'. This caused useArcadeRedirect to
redirect users from /arcade/room to /arcade/matching, breaking the
simplified room addressing model.

Fix:
- Changed gameUrl to '/arcade/room' for room-based sessions
- Now users stay on /arcade/room for the duration of room gameplay
- Solo sessions still use game-specific URLs like /arcade/matching

This ensures the user experience matches the intended design:
- /arcade/room - room-based multiplayer (regardless of game type)
- /arcade/[game] - solo/local multiplayer for specific games

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-08 10:43:48 -05:00
semantic-release-bot
5bbb212da9 chore(release): 2.7.2 [skip ci]
## [2.7.2](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.7.1...v2.7.2) (2025-10-08)

### Bug Fixes

* add hasAttemptedFetch flag to prevent premature redirect ([c30f585](c30f585810))
2025-10-08 15:40:52 +00:00
Thomas Hallock
c30f585810 fix: add hasAttemptedFetch flag to prevent premature redirect
The previous fix didn't fully resolve the race condition. When userId
finished loading, there was a brief moment where:
- isUserIdPending = false (userId loaded)
- isLoading = false (fetch hasn't started yet)
- roomData = null

This triggered the redirect before the room fetch even began.

Solution:
- Added hasAttemptedFetch flag to track fetch attempt state
- Updated isLoading to include: isUserIdPending || isLoading || (!!userId && !hasAttemptedFetch)
- Now the page stays in loading state until we've both loaded userId AND attempted the room fetch

This ensures we never redirect while a fetch is pending.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-08 10:39:54 -05:00
semantic-release-bot
0a768c65fb chore(release): 2.7.1 [skip ci]
## [2.7.1](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.7.0...v2.7.1) (2025-10-08)

### Bug Fixes

* resolve race condition in /arcade/room redirect ([5ed2ab2](5ed2ab21ca))
2025-10-08 15:26:51 +00:00
Thomas Hallock
5ed2ab21ca fix: resolve race condition in /arcade/room redirect
The /arcade/room page was redirecting to /arcade before userId loaded,
causing a race condition where the page would redirect even when the user
was in a valid room.

Root cause:
- useViewerId() loads asynchronously
- useRoomData depended on userId but didn't expose userId loading state
- Page checked !isLoading && !roomData and redirected immediately
- By the time userId loaded and room data fetched, redirect already happened

Fix:
- Track isPending from useViewerId in useRoomData
- Combine isUserIdPending with room data loading state
- Page now waits for both userId and room data before redirecting

Added debug logging to help diagnose future issues.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-08 10:25:53 -05:00
semantic-release-bot
1cb175982a chore(release): 2.7.0 [skip ci]
## [2.7.0](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.6.0...v2.7.0) (2025-10-08)

### Features

* extend GameModeContext to support room-based multiplayer ([ee6094d](ee6094d59d))
2025-10-08 15:14:28 +00:00
Thomas Hallock
ee6094d59d feat: extend GameModeContext to support room-based multiplayer
When a user is in a room, GameModeContext now merges players from all
room members to create a unified player set for gameplay. This enables
true multiplayer where all participants' active players participate
together in the game.

Key changes:
- Added useRoomData and useViewerId to GameModeContext
- Local players (from DB) are marked with isLocal: true
- Remote players (from other room members) are marked with isLocal: false
- Players map merges local + remote players when in a room
- activePlayers set includes all active players from all room members
- Edit operations (update/remove/setActive) only work on local players
- Socket broadcast when local players change to notify room members
- When not in a room, behavior is unchanged (solo/local multiplayer)

This implements the "players is the union of all active players for all
members of the room" requirement for room-based gameplay.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-08 10:13:33 -05:00
semantic-release-bot
9d0c488f2b chore(release): 2.6.0 [skip ci]
## [2.6.0](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.5.0...v2.6.0) (2025-10-08)

### Features

* refactor room addressing to /arcade/room ([e7d2a73](e7d2a73ddf))
2025-10-08 15:08:52 +00:00
Thomas Hallock
e7d2a73ddf feat: refactor room addressing to /arcade/room
Simplify room URL structure so users access their room's game at
/arcade/room instead of /arcade/rooms/[roomId]/[game]. Since users can
only be in one room at a time (modal room enforcement), this provides a
cleaner addressing model.

Changes:
- useRoomData now fetches user's current room from /api/arcade/rooms/current
- Created /api/arcade/rooms/current endpoint to get user's active room
- Created /arcade/room page that renders the appropriate game for the room
- Removed URL parsing logic in favor of backend room lookup
- Socket connection and real-time updates still work with new structure

Next step: Extend GameModeContext to merge players from all room members
so gameplay uses the union of all active players in the room.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-08 10:07:58 -05:00
semantic-release-bot
63517cf45d chore(release): 2.5.0 [skip ci]
## [2.5.0](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.4.6...v2.5.0) (2025-10-08)

### Features

* display room info and network players in mini app nav ([5e3261f](5e3261f3be))
2025-10-08 14:43:33 +00:00
Thomas Hallock
5e3261f3be feat: display room info and network players in mini app nav
When users are in a room (/arcade/rooms/[roomId]/*), the mini app nav now shows:
1. Room name and game type in RoomInfo component
2. Other members' player avatars with "network" indicators
3. Clear distinction between local players and network players

Implementation:
- Created useRoomData hook to fetch room data and listen to real-time updates
- Updated PageWithNav to use room data and compute network players
- Enhanced RoomInfo component to display room name when available
- Network players shown with special borders and connection indicators

The nav automatically detects room context from the URL and fetches:
- Room details (name, game, member count)
- All room members and their players
- Real-time updates via socket events (member-joined, member-left, players-updated)

Network players are filtered to exclude the current user and show each other
member's players with their display names for clear identification.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-08 09:42:34 -05:00
11 changed files with 517 additions and 27 deletions

View File

@@ -1,3 +1,45 @@
## [2.7.3](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.7.2...v2.7.3) (2025-10-08)
### Bug Fixes
* set room sessions to use /arcade/room URL ([9dac431](https://github.com/antialias/soroban-abacus-flashcards/commit/9dac431c1f91c246f67a059cda3cff6cbef40a43))
## [2.7.2](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.7.1...v2.7.2) (2025-10-08)
### Bug Fixes
* add hasAttemptedFetch flag to prevent premature redirect ([c30f585](https://github.com/antialias/soroban-abacus-flashcards/commit/c30f58581028878350282cad5231d614590d9f2b))
## [2.7.1](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.7.0...v2.7.1) (2025-10-08)
### Bug Fixes
* resolve race condition in /arcade/room redirect ([5ed2ab2](https://github.com/antialias/soroban-abacus-flashcards/commit/5ed2ab21cab408147081a493c8dd6b1de48b2d01))
## [2.7.0](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.6.0...v2.7.0) (2025-10-08)
### Features
* extend GameModeContext to support room-based multiplayer ([ee6094d](https://github.com/antialias/soroban-abacus-flashcards/commit/ee6094d59d26a9e80ba5d023ca6dc13143bea308))
## [2.6.0](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.5.0...v2.6.0) (2025-10-08)
### Features
* refactor room addressing to /arcade/room ([e7d2a73](https://github.com/antialias/soroban-abacus-flashcards/commit/e7d2a73ddf2048691325a18e3d71a7ece444c131))
## [2.5.0](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.4.6...v2.5.0) (2025-10-08)
### Features
* display room info and network players in mini app nav ([5e3261f](https://github.com/antialias/soroban-abacus-flashcards/commit/5e3261f3bec8c19ec88c9a35a7e6ef8eda88a55e))
## [2.4.6](https://github.com/antialias/soroban-abacus-flashcards/compare/v2.4.5...v2.4.6) (2025-10-08)

View File

@@ -34,7 +34,8 @@
"Bash(npm run pre-commit:*)",
"Bash(npm run:*)",
"Bash(git pull:*)",
"Bash(git stash:*)"
"Bash(git stash:*)",
"Bash(members of the room\" requirement for room-based gameplay.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <noreply@anthropic.com>\nEOF\n)\")"
],
"deny": [],
"ask": []

View File

@@ -142,7 +142,7 @@ export function initializeSocketServer(httpServer: HTTPServer) {
await createArcadeSession({
userId: data.userId,
gameName: 'matching',
gameUrl: '/arcade/matching',
gameUrl: '/arcade/room', // Room-based sessions use /arcade/room
initialState,
activePlayers,
roomId: room.id,

View File

@@ -0,0 +1,62 @@
import { NextResponse } from 'next/server'
import { getUserRooms } from '@/lib/arcade/room-membership'
import { getRoomById } from '@/lib/arcade/room-manager'
import { getRoomMembers } from '@/lib/arcade/room-membership'
import { getRoomActivePlayers } from '@/lib/arcade/player-manager'
import { getViewerId } from '@/lib/viewer'
/**
* GET /api/arcade/rooms/current
* Returns the user's current room (if any)
*/
export async function GET() {
try {
const userId = await getViewerId()
console.log('[Current Room API] Fetching for user:', userId)
// Get all rooms user is in (should be at most 1 due to modal room enforcement)
const roomIds = await getUserRooms(userId)
console.log('[Current Room API] User rooms:', roomIds)
if (roomIds.length === 0) {
console.log('[Current Room API] User is not in any room')
return NextResponse.json({ room: null }, { status: 200 })
}
const roomId = roomIds[0]
// Get room data
const room = await getRoomById(roomId)
if (!room) {
console.log('[Current Room API] Room not found:', roomId)
return NextResponse.json({ error: 'Room not found' }, { status: 404 })
}
// Get members
const members = await getRoomMembers(roomId)
// Get active players for all members
const memberPlayers = await getRoomActivePlayers(roomId)
// Convert Map to object for JSON serialization
const memberPlayersObj: Record<string, any[]> = {}
for (const [uid, players] of memberPlayers.entries()) {
memberPlayersObj[uid] = players
}
console.log('[Current Room API] Returning room:', {
roomId: room.id,
roomName: room.name,
memberCount: members.length,
})
return NextResponse.json({
room,
members,
memberPlayers: memberPlayersObj,
})
} catch (error) {
console.error('[Current Room API] Error:', error)
return NextResponse.json({ error: 'Failed to fetch current room' }, { status: 500 })
}
}

View File

@@ -0,0 +1,82 @@
'use client'
import { useRouter } from 'next/navigation'
import { useEffect } from 'react'
import { ArcadeGuardedPage } from '@/components/ArcadeGuardedPage'
import { useRoomData } from '@/hooks/useRoomData'
import { MemoryPairsGame } from '../matching/components/MemoryPairsGame'
import { ArcadeMemoryPairsProvider } from '../matching/context/ArcadeMemoryPairsContext'
/**
* /arcade/room - Renders the game for the user's current room
* Since users can only be in one room at a time, this is a simple singular route
*/
export default function RoomPage() {
const router = useRouter()
const { roomData, isLoading } = useRoomData()
// Debug logging
useEffect(() => {
console.log('[RoomPage] State:', { isLoading, hasRoomData: !!roomData, roomData })
}, [isLoading, roomData])
// Redirect to arcade if no room
useEffect(() => {
if (!isLoading && !roomData) {
console.log('[RoomPage] No active room, redirecting to /arcade')
router.push('/arcade')
}
}, [isLoading, roomData, router])
// Show loading state
if (isLoading) {
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
fontSize: '18px',
color: '#666',
}}
>
Loading room...
</div>
)
}
// Show nothing while redirecting
if (!roomData) {
return null
}
// Render the appropriate game based on room's gameName
switch (roomData.gameName) {
case 'matching':
return (
<ArcadeGuardedPage>
<ArcadeMemoryPairsProvider>
<MemoryPairsGame />
</ArcadeMemoryPairsProvider>
</ArcadeGuardedPage>
)
// TODO: Add other games (complement-race, memory-quiz, etc.)
default:
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
fontSize: '18px',
color: '#666',
}}
>
Game "{roomData.gameName}" not yet supported
</div>
)
}
}

View File

@@ -3,6 +3,8 @@
import React from 'react'
import { useGameMode } from '../contexts/GameModeContext'
import { useArcadeGuard } from '../hooks/useArcadeGuard'
import { useRoomData } from '../hooks/useRoomData'
import { useViewerId } from '../hooks/useViewerId'
import { AppNavBar } from './AppNavBar'
import { GameContextNav } from './nav/GameContextNav'
import { PlayerConfigDialog } from './nav/PlayerConfigDialog'
@@ -30,6 +32,8 @@ export function PageWithNav({
}: PageWithNavProps) {
const { players, activePlayers, setActive, activePlayerCount } = useGameMode()
const { hasActiveSession, activeSession } = useArcadeGuard({ enabled: false }) // Don't redirect, just get info
const { roomData, isInRoom } = useRoomData()
const { data: viewerId } = useViewerId()
const [mounted, setMounted] = React.useState(false)
const [configurePlayerId, setConfigurePlayerId] = React.useState<string | null>(null)
@@ -80,17 +84,33 @@ export function PageWithNav({
// Compute arcade session info for display
const roomInfo =
hasActiveSession && activeSession
isInRoom && roomData
? {
gameName: activeSession.currentGame,
playerCount: activePlayerCount, // TODO: Get actual player count from session when available
roomName: roomData.name,
gameName: roomData.gameName,
playerCount: roomData.members.length,
}
: undefined
: hasActiveSession && activeSession
? {
gameName: activeSession.currentGame,
playerCount: activePlayerCount,
}
: undefined
// Compute network players (other players in the arcade session)
// For now, we don't have this info in activeSession, so return empty array
// TODO: When arcade room system is implemented, fetch other players from session
const networkPlayers: Array<{ id: string; emoji?: string; name?: string }> = []
// Compute network players (other players in the room, excluding current user)
const networkPlayers: Array<{ id: string; emoji?: string; name?: string }> =
isInRoom && roomData
? roomData.members
.filter((member) => member.userId !== viewerId)
.flatMap((member) => {
const memberPlayerList = roomData.memberPlayers[member.userId] || []
return memberPlayerList.map((player) => ({
id: player.id,
emoji: player.emoji,
name: `${player.name} (${member.displayName})`,
}))
})
: []
// Create nav content if title is provided
const navContent = navTitle ? (

View File

@@ -22,6 +22,7 @@ interface NetworkPlayer {
}
interface ArcadeRoomInfo {
roomName?: string
gameName: string
playerCount: number
}
@@ -134,6 +135,7 @@ export function GameContextNav({
{/* Room Info - show when in arcade session */}
{roomInfo && !showFullscreenSelection && (
<RoomInfo
roomName={roomInfo.roomName}
gameName={roomInfo.gameName}
playerCount={roomInfo.playerCount}
shouldEmphasize={shouldEmphasize}

View File

@@ -1,4 +1,5 @@
interface RoomInfoProps {
roomName?: string
gameName: string
playerCount: number
shouldEmphasize: boolean
@@ -7,7 +8,7 @@ interface RoomInfoProps {
/**
* Displays current arcade room/session information
*/
export function RoomInfo({ gameName, playerCount, shouldEmphasize }: RoomInfoProps) {
export function RoomInfo({ roomName, gameName, playerCount, shouldEmphasize }: RoomInfoProps) {
return (
<div
style={{
@@ -53,7 +54,7 @@ export function RoomInfo({ gameName, playerCount, shouldEmphasize }: RoomInfoPro
letterSpacing: '0.5px',
}}
>
Arcade Session
{roomName ? 'Room' : 'Arcade Session'}
</div>
<div
style={{
@@ -61,7 +62,7 @@ export function RoomInfo({ gameName, playerCount, shouldEmphasize }: RoomInfoPro
fontWeight: 'bold',
}}
>
{gameName}
{roomName || gameName}
</div>
</div>

View File

@@ -8,6 +8,8 @@ import {
useUpdatePlayer,
useUserPlayers,
} from '@/hooks/useUserPlayers'
import { useRoomData } from '@/hooks/useRoomData'
import { useViewerId } from '@/hooks/useViewerId'
import { getNextPlayerColor } from '../types/player'
// Client-side Player type (compatible with old type)
@@ -66,28 +68,72 @@ export function GameModeProvider({ children }: { children: ReactNode }) {
const { mutate: createPlayer } = useCreatePlayer()
const { mutate: updatePlayerMutation } = useUpdatePlayer()
const { mutate: deletePlayer } = useDeletePlayer()
const { roomData } = useRoomData()
const { data: viewerId } = useViewerId()
const [isInitialized, setIsInitialized] = useState(false)
// Convert DB players to Map
const players = useMemo(() => {
// Convert DB players to Map (local players)
const localPlayers = useMemo(() => {
const map = new Map<string, Player>()
dbPlayers.forEach((dbPlayer) => {
map.set(dbPlayer.id, toClientPlayer(dbPlayer))
map.set(dbPlayer.id, {
...toClientPlayer(dbPlayer),
isLocal: true,
})
})
return map
}, [dbPlayers])
// Track active players from DB isActive status
// When in a room, merge all players from all room members
const players = useMemo(() => {
const map = new Map<string, Player>(localPlayers)
if (roomData) {
// Add players from other room members (marked as remote)
Object.entries(roomData.memberPlayers).forEach(([userId, memberPlayers]) => {
// Skip the current user's players (already in localPlayers)
if (userId === viewerId) return
memberPlayers.forEach((roomPlayer) => {
map.set(roomPlayer.id, {
id: roomPlayer.id,
name: roomPlayer.name,
emoji: roomPlayer.emoji,
color: roomPlayer.color,
createdAt: Date.now(),
isActive: true, // Players in memberPlayers are active
isLocal: false, // Remote player
})
})
})
}
return map
}, [localPlayers, roomData, viewerId])
// Track active players (local + room members when in a room)
const activePlayers = useMemo(() => {
const set = new Set<string>()
dbPlayers.forEach((player) => {
if (player.isActive) {
set.add(player.id)
}
})
if (roomData) {
// In room mode: all players from all members are active
Object.values(roomData.memberPlayers).forEach((memberPlayers) => {
memberPlayers.forEach((player) => {
set.add(player.id)
})
})
} else {
// Solo mode: only local active players
dbPlayers.forEach((player) => {
if (player.isActive) {
set.add(player.id)
}
})
}
return set
}, [dbPlayers])
}, [dbPlayers, roomData])
// Initialize with default players if none exist
useEffect(() => {
@@ -125,15 +171,33 @@ export function GameModeProvider({ children }: { children: ReactNode }) {
}
const updatePlayer = (id: string, updates: Partial<Player>) => {
updatePlayerMutation({ id, updates })
const player = players.get(id)
// Only allow updating local players
if (player?.isLocal) {
updatePlayerMutation({ id, updates })
} else {
console.warn('[GameModeContext] Cannot update remote player:', id)
}
}
const removePlayer = (id: string) => {
deletePlayer(id)
const player = players.get(id)
// Only allow removing local players
if (player?.isLocal) {
deletePlayer(id)
} else {
console.warn('[GameModeContext] Cannot remove remote player:', id)
}
}
const setActive = (id: string, active: boolean) => {
updatePlayerMutation({ id, updates: { isActive: active } })
const player = players.get(id)
// Only allow changing active status of local players
if (player?.isLocal) {
updatePlayerMutation({ id, updates: { isActive: active } })
} else {
console.warn('[GameModeContext] Cannot change active status of remote player:', id)
}
}
const getActivePlayers = (): Player[] => {

View File

@@ -0,0 +1,216 @@
import { useEffect, useState } from 'react'
import { io, type Socket } from 'socket.io-client'
import { useViewerId } from './useViewerId'
export interface RoomMember {
id: string
userId: string
displayName: string
isOnline: boolean
isCreator: boolean
}
export interface RoomPlayer {
id: string
name: string
emoji: string
color: string
}
export interface RoomData {
id: string
name: string
code: string
gameName: string
members: RoomMember[]
memberPlayers: Record<string, RoomPlayer[]> // userId -> players
}
/**
* Hook to fetch and subscribe to the user's current room data
* Returns null if user is not in any room
*/
export function useRoomData() {
const { data: userId, isPending: isUserIdPending } = useViewerId()
const [socket, setSocket] = useState<Socket | null>(null)
const [roomData, setRoomData] = useState<RoomData | null>(null)
const [isLoading, setIsLoading] = useState(false)
const [hasAttemptedFetch, setHasAttemptedFetch] = useState(false)
// Fetch the user's current room
useEffect(() => {
if (!userId) {
console.log('[useRoomData] No userId, clearing room data')
setRoomData(null)
setHasAttemptedFetch(false)
return
}
console.log('[useRoomData] Fetching current room for user:', userId)
setIsLoading(true)
setHasAttemptedFetch(false)
// Fetch current room data
fetch('/api/arcade/rooms/current')
.then((res) => {
console.log('[useRoomData] API response status:', res.status)
if (!res.ok) throw new Error('Failed to fetch current room')
return res.json()
})
.then((data) => {
console.log('[useRoomData] API response data:', data)
if (data.room) {
const roomData = {
id: data.room.id,
name: data.room.name,
code: data.room.code,
gameName: data.room.gameName,
members: data.members || [],
memberPlayers: data.memberPlayers || {},
}
console.log('[useRoomData] Setting room data:', roomData)
setRoomData(roomData)
} else {
console.log('[useRoomData] No room in response, clearing room data')
setRoomData(null)
}
setIsLoading(false)
setHasAttemptedFetch(true)
})
.catch((error) => {
console.error('[useRoomData] Failed to fetch room data:', error)
setRoomData(null)
setIsLoading(false)
setHasAttemptedFetch(true)
})
}, [userId])
// Initialize socket connection when user has a room
useEffect(() => {
if (!roomData?.id || !userId) {
if (socket) {
socket.disconnect()
setSocket(null)
}
return
}
const sock = io({ path: '/api/socket' })
sock.on('connect', () => {
console.log('[useRoomData] Socket connected, joining room:', roomData.id)
// Join the room to receive updates
sock.emit('join-room', { roomId: roomData.id, userId })
})
sock.on('disconnect', () => {
console.log('[useRoomData] Socket disconnected')
})
setSocket(sock)
return () => {
if (sock.connected) {
// Leave the room before disconnecting
sock.emit('leave-room', { roomId: roomData.id, userId })
sock.disconnect()
}
}
}, [roomData?.id, userId])
// Subscribe to real-time updates via socket
useEffect(() => {
if (!socket || !roomData?.id) return
const handleRoomJoined = (data: {
roomId: string
members: RoomMember[]
memberPlayers: Record<string, RoomPlayer[]>
}) => {
console.log('[useRoomData] Received room-joined event:', data)
if (data.roomId === roomData.id) {
setRoomData((prev) => {
if (!prev) return null
return {
...prev,
members: data.members,
memberPlayers: data.memberPlayers,
}
})
}
}
const handleMemberJoined = (data: {
roomId: string
userId: string
members: RoomMember[]
memberPlayers: Record<string, RoomPlayer[]>
}) => {
console.log('[useRoomData] Received member-joined event:', data)
if (data.roomId === roomData.id) {
setRoomData((prev) => {
if (!prev) return null
return {
...prev,
members: data.members,
memberPlayers: data.memberPlayers,
}
})
}
}
const handleMemberLeft = (data: {
roomId: string
userId: string
members: RoomMember[]
memberPlayers: Record<string, RoomPlayer[]>
}) => {
console.log('[useRoomData] Received member-left event:', data)
if (data.roomId === roomData.id) {
setRoomData((prev) => {
if (!prev) return null
return {
...prev,
members: data.members,
memberPlayers: data.memberPlayers,
}
})
}
}
const handleRoomPlayersUpdated = (data: {
roomId: string
memberPlayers: Record<string, RoomPlayer[]>
}) => {
console.log('[useRoomData] Received room-players-updated event:', data)
if (data.roomId === roomData.id) {
setRoomData((prev) => {
if (!prev) return null
return {
...prev,
memberPlayers: data.memberPlayers,
}
})
}
}
socket.on('room-joined', handleRoomJoined)
socket.on('member-joined', handleMemberJoined)
socket.on('member-left', handleMemberLeft)
socket.on('room-players-updated', handleRoomPlayersUpdated)
return () => {
socket.off('room-joined', handleRoomJoined)
socket.off('member-joined', handleMemberJoined)
socket.off('member-left', handleMemberLeft)
socket.off('room-players-updated', handleRoomPlayersUpdated)
}
}, [socket, roomData?.id])
return {
roomData,
// Loading if: userId is pending, currently fetching, or have userId but haven't tried fetching yet
isLoading: isUserIdPending || isLoading || (!!userId && !hasAttemptedFetch),
isInRoom: !!roomData,
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "soroban-monorepo",
"version": "2.4.6",
"version": "2.7.3",
"private": true,
"description": "Beautiful Soroban Flashcard Generator - Monorepo",
"workspaces": [