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 | 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, useRef, useState, useMemo } from 'react'
import type { Socket } from 'socket.io-client'
import { createSocket } from '@/lib/socket'
import { api } from '@/lib/queryClient'
import type { SessionStartedEvent, SessionEndedEvent } from '@/lib/classroom/socket-events'
/**
* Active session information for a child
*/
export interface ChildActiveSession {
/** Session plan ID */
planId: string
/** Session status */
status: string
/** Number of completed problems */
completedSlots: number
/** Total number of problems */
totalSlots: number
/** When the session started (ISO string) */
startedAt: string
}
/**
* Hook: Subscribe to real-time session updates for children via WebSocket
*
* Instead of polling every 10 seconds, this hook:
* 1. Fetches initial session state for all children (or uses pre-seeded data)
* 2. Subscribes to real-time session-started/session-ended events
* 3. Maintains a Map of playerId -> session info that updates instantly
*
* @param userId - The parent's user ID (for socket subscription)
* @param childIds - Array of player IDs to subscribe to
* @param initialSessions - Optional pre-seeded session data (skips N per-child HTTP fetches)
* @returns sessionMap (playerId -> session), isLoading, connected
*/
export function useChildSessionsSocket(
userId: string | undefined,
childIds: string[],
initialSessions?: Map<string, ChildActiveSession>
) {
// Session state maintained from socket events
const [sessions, setSessions] = useState<Map<string, ChildActiveSession>>(
() => initialSessions ?? new Map()
)
const [isLoading, setIsLoading] = useState(!initialSessions)
const [connected, setConnected] = useState(false)
const socketRef = useRef<Socket | null>(null)
const subscribedIdsRef = useRef<Set<string>>(new Set())
// Fetch initial session state for a child
const fetchSession = useCallback(async (playerId: string): Promise<ChildActiveSession | null> => {
try {
const res = await api(`players/${playerId}/active-session`)
if (!res.ok) {
if (res.status === 403) return null // Not authorized
throw new Error('Failed to fetch session')
}
const data = await res.json()
if (!data.session) return null
// Convert API response to ChildActiveSession format
return {
planId: data.session.sessionId,
status: data.session.status,
completedSlots: data.session.completedProblems,
totalSlots: data.session.totalProblems,
startedAt: new Date().toISOString(), // API doesn't return startedAt, use now as fallback
}
} catch (error) {
console.error(`[ChildSessionsSocket] Failed to fetch session for ${playerId}:`, error)
return null
}
}, [])
// Fetch initial state for all children (skipped when initialSessions provided)
useEffect(() => {
if (childIds.length === 0) {
setIsLoading(false)
setSessions(new Map())
return
}
// Skip fetch when pre-seeded data was provided.
// Using initialSessions as a dep (stable ref from useMemo) instead of a mutable ref,
// which breaks under React Strict Mode's double-mount.
if (initialSessions) return
let cancelled = false
async function fetchAll() {
setIsLoading(true)
const newSessions = new Map<string, ChildActiveSession>()
await Promise.all(
childIds.map(async (playerId) => {
const session = await fetchSession(playerId)
if (session && !cancelled) {
newSessions.set(playerId, session)
}
})
)
if (!cancelled) {
setSessions(newSessions)
setIsLoading(false)
}
}
fetchAll()
return () => {
cancelled = true
}
}, [childIds, fetchSession, initialSessions])
// Setup socket connection and subscriptions
useEffect(() => {
if (!userId || childIds.length === 0) return
// Create socket connection
const socket = createSocket({
reconnection: true,
reconnectionDelay: 1000,
reconnectionAttempts: 5,
})
socketRef.current = socket
socket.on('connect', () => {
console.log('[ChildSessionsSocket] Connected')
setConnected(true)
// Subscribe to child sessions
socket.emit('subscribe-child-sessions', { userId, childIds })
subscribedIdsRef.current = new Set(childIds)
})
socket.on('disconnect', () => {
console.log('[ChildSessionsSocket] Disconnected')
setConnected(false)
})
// Handle session started
socket.on('session-started', (data: SessionStartedEvent) => {
console.log(
'[ChildSessionsSocket] Session started:',
data.playerName,
'session:',
data.sessionId
)
// Fetch the full session details (including progress)
fetchSession(data.playerId).then((session) => {
if (session) {
setSessions((prev) => {
const next = new Map(prev)
next.set(data.playerId, session)
return next
})
}
})
})
// Handle session ended
socket.on('session-ended', (data: SessionEndedEvent) => {
console.log('[ChildSessionsSocket] Session ended:', data.playerName, 'reason:', data.reason)
setSessions((prev) => {
const next = new Map(prev)
next.delete(data.playerId)
return next
})
})
// Cleanup on unmount
return () => {
if (subscribedIdsRef.current.size > 0) {
socket.emit('unsubscribe-child-sessions', {
userId,
childIds: Array.from(subscribedIdsRef.current),
})
}
socket.disconnect()
socketRef.current = null
subscribedIdsRef.current.clear()
}
}, [userId, childIds, fetchSession])
// Handle changes to childIds (subscribe to new, unsubscribe from removed)
useEffect(() => {
const socket = socketRef.current
if (!socket || !connected || !userId) return
const currentIds = new Set(childIds)
const subscribedIds = subscribedIdsRef.current
// Find new IDs to subscribe
const toSubscribe = childIds.filter((id) => !subscribedIds.has(id))
// Find removed IDs to unsubscribe
const toUnsubscribe = Array.from(subscribedIds).filter((id) => !currentIds.has(id))
if (toSubscribe.length > 0) {
socket.emit('subscribe-child-sessions', {
userId,
childIds: toSubscribe,
})
toSubscribe.forEach((id) => subscribedIds.add(id))
}
if (toUnsubscribe.length > 0) {
socket.emit('unsubscribe-child-sessions', {
userId,
childIds: toUnsubscribe,
})
toUnsubscribe.forEach((id) => subscribedIds.delete(id))
// Remove sessions for unsubscribed children
setSessions((prev) => {
const next = new Map(prev)
toUnsubscribe.forEach((id) => next.delete(id))
return next
})
}
}, [childIds, connected, userId])
// Memoize the return value to avoid unnecessary re-renders
const result = useMemo(
() => ({
sessionMap: sessions,
isLoading,
connected,
}),
[sessions, isLoading, connected]
)
return result
}
|