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 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 | 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 1x 1x 1x 3x 3x 3x 1x 1x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 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 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 8x 8x 8x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 2x 2x 2x 2x 2x 2x 17x 17x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 1x 1x 1x 15x 15x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 15x 15x 15x 15x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 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 | import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useCallback, useEffect, useState } from 'react'
import type { Socket } from 'socket.io-client'
import { createSocket } from '@/lib/socket'
import { useUserId } from './useUserId'
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 | null // Nullable to support game selection in room
gameConfig?: Record<string, unknown> | null // Game-specific settings
accessMode: 'open' | 'password' | 'approval-only' | 'restricted' | 'locked' | 'retired'
members: RoomMember[]
memberPlayers: Record<string, RoomPlayer[]> // userId -> players
}
export interface CreateRoomParams {
name: string | null
gameName?: string | null // Optional - rooms can be created without a game
creatorName?: string
gameConfig?: Record<string, unknown>
accessMode?: 'open' | 'password' | 'approval-only' | 'restricted' | 'locked' | 'retired'
password?: string
}
export interface AutoLeaveInfo {
roomIds: string[]
message: string
}
export interface JoinRoomResult {
member: RoomMember
room: RoomData
activePlayers: RoomPlayer[]
autoLeave?: AutoLeaveInfo
}
export interface CreateRoomResult {
room: RoomData
autoLeave?: AutoLeaveInfo
}
/**
* Query key factory for rooms
*/
export const roomKeys = {
all: ['rooms'] as const,
current: () => [...roomKeys.all, 'current'] as const,
}
/**
* Fetch the user's current room
*/
async function fetchCurrentRoom(): Promise<RoomData | null> {
const response = await fetch('/api/arcade/rooms/current')
if (!response.ok) {
if (response.status === 404) return null
throw new Error('Failed to fetch current room')
}
const data = await response.json()
if (!data.room) return null
return {
id: data.room.id,
name: data.room.name,
code: data.room.code,
gameName: data.room.gameName,
gameConfig: data.room.gameConfig || null,
accessMode: data.room.accessMode || 'open',
members: data.members || [],
memberPlayers: data.memberPlayers || {},
}
}
/**
* Create a new room
*/
async function createRoomApi(params: CreateRoomParams): Promise<CreateRoomResult> {
const response = await fetch('/api/arcade/rooms', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: params.name,
gameName: params.gameName || null,
creatorName: params.creatorName || 'Player',
gameConfig: params.gameConfig || null,
accessMode: params.accessMode,
password: params.password,
}),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to create room')
}
const data = await response.json()
return {
room: {
id: data.room.id,
name: data.room.name,
code: data.room.code,
gameName: data.room.gameName,
gameConfig: data.room.gameConfig || null,
accessMode: data.room.accessMode || 'open',
members: data.members || [],
memberPlayers: data.memberPlayers || {},
},
autoLeave: data.autoLeave,
}
}
/**
* Join a room
*/
async function joinRoomApi(params: {
roomId: string
displayName?: string
password?: string
}): Promise<JoinRoomResult> {
const response = await fetch(`/api/arcade/rooms/${params.roomId}/join`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
displayName: params.displayName || 'Player',
password: params.password,
}),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to join room')
}
const data = await response.json()
return {
...data,
room: {
id: data.room.id,
name: data.room.name,
code: data.room.code,
gameName: data.room.gameName,
gameConfig: data.room.gameConfig || null,
accessMode: data.room.accessMode || 'open',
members: data.members || [],
memberPlayers: data.memberPlayers || {},
},
}
}
/**
* Leave a room
*/
async function leaveRoomApi(roomId: string): Promise<void> {
const response = await fetch(`/api/arcade/rooms/${roomId}/leave`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to leave room')
}
}
/**
* Get room by join code
*/
async function getRoomByCodeApi(code: string): Promise<RoomData> {
const response = await fetch(`/api/arcade/rooms/code/${code}`)
if (!response.ok) {
if (response.status === 404) {
throw new Error('Room not found')
}
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to find room')
}
const data = await response.json()
return {
id: data.room.id,
name: data.room.name,
code: data.room.code,
gameName: data.room.gameName,
gameConfig: data.room.gameConfig || null,
accessMode: data.room.accessMode || 'open',
members: data.members || [],
memberPlayers: data.memberPlayers || {},
}
}
export interface ModerationEvent {
type: 'kicked' | 'banned' | 'report' | 'invitation' | 'join-request'
data: {
roomId?: string
kickedBy?: string
bannedBy?: string
reason?: string
reportId?: string
reporterName?: string
reportedUserName?: string
reportedUserId?: string
// Invitation fields
invitationId?: string
invitedBy?: string
invitedByName?: string
invitationType?: 'manual' | 'auto-unban' | 'auto-create'
message?: string
// Join request fields
requestId?: string
requesterId?: string
requesterName?: string
}
}
/**
* 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 } = useUserId()
const queryClient = useQueryClient()
const [socket, setSocket] = useState<Socket | null>(null)
const [moderationEvent, setModerationEvent] = useState<ModerationEvent | null>(null)
// Fetch current room with TanStack Query
const {
data: roomData,
isLoading,
refetch,
} = useQuery({
queryKey: roomKeys.current(),
queryFn: fetchCurrentRoom,
enabled: !!userId,
staleTime: 30000, // Consider data fresh for 30 seconds
})
// Initialize socket connection when user is authenticated (regardless of room membership)
useEffect(() => {
if (!userId) {
if (socket) {
socket.disconnect()
setSocket(null)
}
return
}
const sock = createSocket()
sock.on('connect', () => {
// Always join user-specific channel for personal notifications (invitations, bans, kicks)
sock.emit('join-user-channel', { userId })
// Join room channel only if user is in a room
if (roomData?.id) {
sock.emit('join-room', { roomId: roomData.id, userId })
}
})
sock.on('disconnect', () => {
// Socket disconnected
})
setSocket(sock)
return () => {
if (sock.connected) {
// Leave the room before disconnecting (if in a room)
if (roomData?.id) {
sock.emit('leave-room', { roomId: roomData.id, userId })
}
sock.disconnect()
}
}
}, [userId, roomData?.id])
// Subscribe to real-time updates via socket
useEffect(() => {
if (!socket) return
const handleRoomJoined = (data: {
roomId: string
members: RoomMember[]
memberPlayers: Record<string, RoomPlayer[]>
}) => {
if (data.roomId === roomData?.id) {
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (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[]>
}) => {
if (data.roomId === roomData?.id) {
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (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[]>
}) => {
if (data.roomId === roomData?.id) {
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (prev) => {
if (!prev) return null
return {
...prev,
members: data.members,
memberPlayers: data.memberPlayers,
}
})
}
}
const handleRoomPlayersUpdated = (data: {
roomId: string
memberPlayers: Record<string, RoomPlayer[]>
}) => {
if (data.roomId === roomData?.id) {
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (prev) => {
if (!prev) return null
return {
...prev,
memberPlayers: data.memberPlayers,
}
})
}
}
const handlePlayerDeactivated = (data: {
roomId: string
playerId: string
playerName: string
deactivatedBy: string
memberPlayers: Record<string, RoomPlayer[]>
}) => {
if (data.roomId === roomData?.id) {
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (prev) => {
if (!prev) return null
return {
...prev,
memberPlayers: data.memberPlayers,
}
})
}
}
// Moderation event handlers
const handleKickedFromRoom = (data: { roomId: string; kickedBy: string; reason?: string }) => {
setModerationEvent({
type: 'kicked',
data: {
roomId: data.roomId,
kickedBy: data.kickedBy,
reason: data.reason,
},
})
// Clear room data since user was kicked
queryClient.setQueryData(roomKeys.current(), null)
}
const handleBannedFromRoom = (data: { roomId: string; bannedBy: string; reason: string }) => {
setModerationEvent({
type: 'banned',
data: {
roomId: data.roomId,
bannedBy: data.bannedBy,
reason: data.reason,
},
})
// Clear room data since user was banned
queryClient.setQueryData(roomKeys.current(), null)
}
const handleReportSubmitted = (data: {
roomId: string
report: {
id: string
reporterName: string
reportedUserName: string
reportedUserId: string
reason: string
createdAt: Date
}
}) => {
setModerationEvent({
type: 'report',
data: {
roomId: data.roomId,
reportId: data.report.id,
reporterName: data.report.reporterName,
reportedUserName: data.report.reportedUserName,
reportedUserId: data.report.reportedUserId,
reason: data.report.reason,
},
})
}
const handleInvitationReceived = (data: {
invitation: {
id: string
roomId: string
invitedBy: string
invitedByName: string
invitationType?: 'manual' | 'auto-unban' | 'auto-create'
message?: string
createdAt: Date
}
}) => {
setModerationEvent({
type: 'invitation',
data: {
roomId: data.invitation.roomId,
invitationId: data.invitation.id,
invitedBy: data.invitation.invitedBy,
invitedByName: data.invitation.invitedByName,
invitationType: data.invitation.invitationType,
message: data.invitation.message,
},
})
}
const handleJoinRequestSubmitted = (data: {
roomId: string
request: {
id: string
userId: string
userName: string
createdAt: Date
}
}) => {
setModerationEvent({
type: 'join-request',
data: {
roomId: data.roomId,
requestId: data.request.id,
requesterId: data.request.userId,
requesterName: data.request.userName,
},
})
}
const handleRoomGameChanged = (data: {
roomId: string
gameName: string | null
gameConfig?: Record<string, unknown>
}) => {
if (data.roomId === roomData?.id) {
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (prev) => {
if (!prev) return null
return {
...prev,
gameName: data.gameName,
// Only update gameConfig if it was provided in the broadcast
...(data.gameConfig !== undefined ? { gameConfig: data.gameConfig } : {}),
}
})
}
}
const handleOwnershipTransferred = (data: {
roomId: string
oldOwnerId: string
newOwnerId: string
newOwnerName: string
members: RoomMember[]
}) => {
if (data.roomId === roomData?.id) {
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (prev) => {
if (!prev) return null
return {
...prev,
members: data.members,
}
})
}
}
socket.on('room-joined', handleRoomJoined)
socket.on('member-joined', handleMemberJoined)
socket.on('member-left', handleMemberLeft)
socket.on('room-players-updated', handleRoomPlayersUpdated)
socket.on('player-deactivated', handlePlayerDeactivated)
socket.on('kicked-from-room', handleKickedFromRoom)
socket.on('banned-from-room', handleBannedFromRoom)
socket.on('report-submitted', handleReportSubmitted)
socket.on('room-invitation-received', handleInvitationReceived)
socket.on('join-request-submitted', handleJoinRequestSubmitted)
socket.on('room-game-changed', handleRoomGameChanged)
socket.on('ownership-transferred', handleOwnershipTransferred)
return () => {
socket.off('room-joined', handleRoomJoined)
socket.off('member-joined', handleMemberJoined)
socket.off('member-left', handleMemberLeft)
socket.off('room-players-updated', handleRoomPlayersUpdated)
socket.off('player-deactivated', handlePlayerDeactivated)
socket.off('kicked-from-room', handleKickedFromRoom)
socket.off('banned-from-room', handleBannedFromRoom)
socket.off('report-submitted', handleReportSubmitted)
socket.off('room-invitation-received', handleInvitationReceived)
socket.off('join-request-submitted', handleJoinRequestSubmitted)
socket.off('room-game-changed', handleRoomGameChanged)
socket.off('ownership-transferred', handleOwnershipTransferred)
}
}, [socket, roomData?.id, queryClient])
// Function to notify room members of player updates
const notifyRoomOfPlayerUpdate = useCallback(() => {
if (socket && roomData?.id && userId) {
socket.emit('players-updated', { roomId: roomData.id, userId })
}
}, [socket, roomData?.id, userId])
/**
* Generate a shareable URL for the room using the join code
*/
const getRoomShareUrl = useCallback((code: string): string => {
return `${window.location.origin}/join/${code.toUpperCase()}`
}, [])
/**
* Clear the moderation event after it's been handled
*/
const clearModerationEvent = useCallback(() => {
setModerationEvent(null)
}, [])
return {
// Data
roomData: roomData ?? null,
isLoading,
isInRoom: !!roomData,
moderationEvent,
// Actions
refetch,
getRoomShareUrl,
notifyRoomOfPlayerUpdate,
clearModerationEvent,
}
}
/**
* Hook: Create a room
*/
export function useCreateRoom() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: createRoomApi,
onSuccess: (result) => {
// Optimistically set the cache with the new room data
queryClient.setQueryData(roomKeys.current(), result.room)
// Log auto-leave info if any rooms were left
if (result.autoLeave && result.autoLeave.roomIds.length > 0) {
console.log(
`[useCreateRoom] Auto-left ${result.autoLeave.roomIds.length} room(s):`,
result.autoLeave.roomIds
)
}
},
})
}
/**
* Hook: Join a room
*/
export function useJoinRoom() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: joinRoomApi,
onSuccess: (result) => {
// Optimistically set the cache with the joined room data
queryClient.setQueryData(roomKeys.current(), result.room)
},
})
}
/**
* Hook: Leave a room
*/
export function useLeaveRoom() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: leaveRoomApi,
onSuccess: () => {
// Optimistically clear the room data
queryClient.setQueryData(roomKeys.current(), null)
},
})
}
/**
* Hook: Get room by code
*/
export function useGetRoomByCode() {
return useMutation({
mutationFn: getRoomByCodeApi,
})
}
/**
* Set game for a room
*/
async function setRoomGameApi(params: {
roomId: string
gameName: string
gameConfig?: Record<string, unknown>
}): Promise<void> {
// Only include gameConfig in the request if it was explicitly provided
// Otherwise, we preserve the existing gameConfig in the database
const body: { gameName: string; gameConfig?: Record<string, unknown> } = {
gameName: params.gameName,
}
if (params.gameConfig !== undefined) {
body.gameConfig = params.gameConfig
}
const response = await fetch(`/api/arcade/rooms/${params.roomId}/settings`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to set room game')
}
}
/**
* Hook: Set game for a room
*/
export function useSetRoomGame() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: setRoomGameApi,
onSuccess: (_, variables) => {
// Update the cache with the new game (include gameConfig if provided)
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (prev) => {
if (!prev) return null
return {
...prev,
gameName: variables.gameName,
...(variables.gameConfig !== undefined ? { gameConfig: variables.gameConfig } : {}),
}
})
// Refetch to get the full updated room data
queryClient.invalidateQueries({ queryKey: roomKeys.current() })
},
})
}
/**
* Clear/reset game for a room (host only)
* This only clears gameName (returns to game selection) but preserves gameConfig
* so settings persist when the user selects a game again.
*/
async function clearRoomGameApi(roomId: string): Promise<void> {
const response = await fetch(`/api/arcade/rooms/${roomId}/settings`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
gameName: null,
// DO NOT send gameConfig: null - we want to preserve settings!
}),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to clear room game')
}
}
/**
* Hook: Clear/reset game for a room (returns to game selection screen)
*/
export function useClearRoomGame() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: clearRoomGameApi,
onSuccess: () => {
// Update the cache to clear the game
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (prev) => {
if (!prev) return null
return {
...prev,
gameName: null,
}
})
// Refetch to get the full updated room data
queryClient.invalidateQueries({ queryKey: roomKeys.current() })
},
})
}
/**
* Update game config for current room (game-specific settings)
*/
async function updateGameConfigApi(params: {
roomId: string
gameConfig: Record<string, unknown>
}): Promise<void> {
const response = await fetch(`/api/arcade/rooms/${params.roomId}/settings`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
gameConfig: params.gameConfig,
}),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to update game config')
}
}
/**
* Hook: Update game config for current room
* This allows games to persist their settings (e.g., difficulty, card count)
*/
export function useUpdateGameConfig() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: updateGameConfigApi,
onSuccess: (_, variables) => {
// Update the cache with the new gameConfig
queryClient.setQueryData<RoomData | null>(roomKeys.current(), (prev) => {
if (!prev) return null
return {
...prev,
gameConfig: variables.gameConfig,
}
})
},
})
}
/**
* Kick a user from the room (host only)
*/
async function kickUserFromRoomApi(params: { roomId: string; userId: string }): Promise<void> {
const response = await fetch(`/api/arcade/rooms/${params.roomId}/kick`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: params.userId }),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to kick user')
}
}
/**
* Hook: Kick a user from the room (host only)
*/
export function useKickUser() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: kickUserFromRoomApi,
onSuccess: () => {
// The socket will handle updating members, but invalidate just in case
queryClient.invalidateQueries({ queryKey: roomKeys.current() })
},
})
}
/**
* Deactivate a specific player in the room (host only)
*/
async function deactivatePlayerInRoomApi(params: {
roomId: string
playerId: string
}): Promise<void> {
const url = `/api/arcade/rooms/${params.roomId}/deactivate-player`
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ playerId: params.playerId }),
})
if (!response.ok) {
const errorData = await response.json()
console.error('[useRoomData] Error response:', errorData)
throw new Error(errorData.error || 'Failed to deactivate player')
}
}
/**
* Hook: Deactivate a specific player in the room (host only)
*/
export function useDeactivatePlayer() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: deactivatePlayerInRoomApi,
onSuccess: () => {
// The socket will handle updating players, but invalidate just in case
queryClient.invalidateQueries({ queryKey: roomKeys.current() })
},
})
}
|