All files / web/src/arcade-games/yjs-demo Provider.tsx

0% Statements 0/299
0% Branches 0/1
0% Functions 0/1
0% Lines 0/299

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client'

import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import type * as Y from 'yjs'
import { useArcadeSession } from '@/hooks/useArcadeSession'
import { useArcadeSocket } from '@/hooks/useArcadeSocket'
import { useGameMode } from '@/contexts/GameModeContext'
import { useUserId } from '@/hooks/useUserId'
import type { GridCell, YjsDemoState } from './types'

interface YjsDemoContextValue {
  state: YjsDemoState
  yjsState: {
    cells: Y.Array<GridCell> | null
    awareness: any
  }
  addCell: (x: number, y: number) => void
  startGame: () => void
  endGame: () => void
  goToSetup: () => void
  exitSession: () => void
  lastError: string | null
  clearError: () => void
}

const YjsDemoContext = createContext<YjsDemoContextValue | null>(null)

export function useYjsDemo() {
  const context = useContext(YjsDemoContext)
  if (!context) {
    throw new Error('useYjsDemo must be used within YjsDemoProvider')
  }
  return context
}

export function YjsDemoProvider({ children }: { children: React.ReactNode }) {
  const { data: viewerId } = useUserId()
  const { activePlayers: activePlayerIds, roomData } = useGameMode()
  const [forceUpdate, setForceUpdate] = useState(0)

  // Initial state for arcade session
  const initialState: YjsDemoState = {
    gamePhase: 'setup',
    gridSize: 8,
    duration: 60,
    activePlayers: [],
    playerScores: {},
  }

  // Use arcade session for phase transitions
  const { state, sendMove, exitSession, lastError, clearError } = useArcadeSession<YjsDemoState>({
    userId: viewerId || '',
    roomId: roomData?.id,
    initialState,
    applyMove: (currentState) => currentState, // Server handles state
  })

  // Yjs setup - Socket.IO based sync
  const docRef = useRef<Y.Doc | null>(null)
  const awarenessRef = useRef<any>(null)
  const cellsRef = useRef<Y.Array<GridCell> | null>(null)

  // Get socket from arcade socket hook
  const { socket } = useArcadeSocket()

  useEffect(() => {
    if (!roomData?.id || !socket) return

    let doc: Y.Doc
    let awareness: any
    let cells: Y.Array<GridCell>

    // Dynamic import to avoid loading Yjs in server bundle
    const initYjs = async () => {
      const Y = await import('yjs')
      const awarenessProtocol = await import('y-protocols/awareness')
      const syncProtocol = await import('y-protocols/sync')
      const encoding = await import('lib0/encoding')
      const decoding = await import('lib0/decoding')

      doc = new Y.Doc()
      docRef.current = doc

      // Create awareness
      awareness = new awarenessProtocol.Awareness(doc)
      awarenessRef.current = awareness

      cells = doc.getArray<GridCell>('cells')
      cellsRef.current = cells

      // Listen for changes in cells array to trigger re-renders
      const observer = () => {
        setForceUpdate((n) => n + 1)
      }
      cells.observe(observer)

      // Set up Socket.IO handlers for Yjs sync

      // Handle incoming sync/update messages from server
      const handleYjsMessage = (data: number[]) => {
        const message = new Uint8Array(data)
        const decoder = decoding.createDecoder(message)
        const messageType = decoding.readVarUint(decoder)

        if (messageType === 0) {
          // Sync protocol message (sync step or update)
          const encoder = encoding.createEncoder()
          encoding.writeVarUint(encoder, 0)
          syncProtocol.readSyncMessage(decoder, encoder, doc, socket.id)

          // Send response if there's content
          if (encoding.length(encoder) > 1) {
            socket.emit('yjs-update', Array.from(encoding.toUint8Array(encoder)))
          }
        }
      }

      // Handle incoming awareness updates
      const handleYjsAwareness = (data: number[]) => {
        const message = new Uint8Array(data)
        const decoder = decoding.createDecoder(message)
        const messageType = decoding.readVarUint(decoder)

        if (messageType === 0) {
          // Read the awareness update from the message
          const awarenessUpdate = decoding.readVarUint8Array(decoder)
          awarenessProtocol.applyAwarenessUpdate(awareness, awarenessUpdate, socket.id)
        }
      }

      // Register Socket.IO event handlers
      // Both sync and update events use the same handler since readSyncMessage handles both
      socket.on('yjs-sync', handleYjsMessage)
      socket.on('yjs-update', handleYjsMessage)
      socket.on('yjs-awareness', handleYjsAwareness)

      // Send updates to server when document changes
      const updateHandler = (update: Uint8Array, origin: any) => {
        // Don't send updates that came from the server
        if (origin === socket.id) return

        const encoder = encoding.createEncoder()
        encoding.writeVarUint(encoder, 0) // Message type: sync
        syncProtocol.writeUpdate(encoder, update)
        const message = encoding.toUint8Array(encoder)

        socket.emit('yjs-update', Array.from(message))
      }
      doc.on('update', updateHandler)

      // Send awareness updates to server
      const awarenessUpdateHandler = ({ added, updated, removed }: any) => {
        const changedClients = added.concat(updated).concat(removed)
        const update = awarenessProtocol.encodeAwarenessUpdate(awareness, changedClients)
        socket.emit('yjs-awareness', Array.from(update))
      }
      awareness.on('update', awarenessUpdateHandler)

      // Set local awareness state
      if (viewerId) {
        awareness.setLocalStateField('user', {
          id: viewerId,
          timestamp: Date.now(),
        })
      }

      // Join the Yjs room
      console.log('[YjsDemo] Joining Yjs room:', roomData.id)
      socket.emit('yjs-join', roomData.id)

      // Cleanup function stored for later
      return () => {
        socket.off('yjs-sync', handleYjsMessage)
        socket.off('yjs-update', handleYjsMessage)
        socket.off('yjs-awareness', handleYjsAwareness)
        doc.off('update', updateHandler)
        awareness.off('update', awarenessUpdateHandler)
      }
    }

    let cleanup: (() => void) | undefined

    void initYjs().then((cleanupFn) => {
      cleanup = cleanupFn
    })

    return () => {
      if (cleanup) {
        cleanup()
      }
      if (awarenessRef.current) {
        awarenessRef.current.setLocalState(null)
        awarenessRef.current.destroy()
      }
      if (docRef.current) {
        docRef.current.destroy()
      }
      docRef.current = null
      awarenessRef.current = null
      cellsRef.current = null
    }
  }, [roomData?.id, viewerId, socket])

  // Player colors
  const playerColors = useMemo(() => {
    const colors = [
      '#FF6B6B',
      '#4ECDC4',
      '#45B7D1',
      '#FFA07A',
      '#98D8C8',
      '#F7DC6F',
      '#BB8FCE',
      '#85C1E2',
    ]
    const playerList = Array.from(activePlayerIds)
    const colorMap: Record<string, string> = {}
    for (let i = 0; i < playerList.length; i++) {
      colorMap[playerList[i]] = colors[i % colors.length]
    }
    return colorMap
  }, [activePlayerIds])

  // Actions
  const addCell = useCallback(
    (x: number, y: number) => {
      if (!cellsRef.current || !viewerId || !docRef.current) return
      if (state.gamePhase !== 'playing') return

      const cell: GridCell = {
        id: `${viewerId}-${Date.now()}`,
        x,
        y,
        playerId: viewerId,
        timestamp: Date.now(),
        color: playerColors[viewerId] || '#999999',
      }

      docRef.current.transact(() => {
        cellsRef.current?.push([cell])
      })

      // Update score in local state (this would be synced via Yjs in a real impl)
      // For now, we're just showing the concept
    },
    [viewerId, state.gamePhase, playerColors]
  )

  const startGame = useCallback(() => {
    const players = Array.from(activePlayerIds)
    sendMove({
      type: 'START_GAME',
      playerId: players[0] || viewerId || '',
      userId: viewerId || '',
      data: { activePlayers: players },
    })
  }, [activePlayerIds, viewerId, sendMove])

  const endGame = useCallback(() => {
    sendMove({
      type: 'END_GAME',
      playerId: viewerId || '',
      userId: viewerId || '',
      data: {},
    })
  }, [viewerId, sendMove])

  const goToSetup = useCallback(() => {
    sendMove({
      type: 'GO_TO_SETUP',
      playerId: viewerId || '',
      userId: viewerId || '',
      data: {},
    })
  }, [viewerId, sendMove])

  const yjsState = {
    cells: cellsRef.current,
    awareness: awarenessRef.current || null,
  }

  return (
    <YjsDemoContext.Provider
      value={{
        state,
        yjsState,
        addCell,
        startGame,
        endGame,
        goToSetup,
        exitSession,
        lastError,
        clearError,
      }}
    >
      {children}
    </YjsDemoContext.Provider>
  )
}