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 | 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 19x 16x 16x 16x 27x 27x 27x 27x 2x 2x 2x 27x 27x 27x 27x 15x 2x 2x 2x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 5x 5x 5x 5x 5x 5x 13x 13x 13x 1x 1x 1x 13x 13x 13x 1x 1x 1x 13x 13x 13x 13x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 13x 13x 13x 13x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x | 'use client'
/**
* Hook for real-time session time estimates via WebSocket
*
* Subscribes to session state updates and computes time estimates
* using the shared calculation functions. Falls back to static data
* when WebSocket isn't connected.
*/
import { useCallback, useEffect, useRef, useState } from 'react'
import type { Socket } from 'socket.io-client'
import { createSocket } from '@/lib/socket'
import type { SessionPart, SlotResult } from '@/db/schema/session-plans'
import type { PracticeStateEvent } from '@/lib/classroom/socket-events'
import {
calculateTimingStats,
calculateEstimatedTimeRemainingMs,
formatEstimatedTimeRemaining,
type SessionTimeEstimate,
} from './useSessionTimeEstimate'
// ============================================================================
// Types
// ============================================================================
export interface LiveSessionTimeEstimateOptions {
/** Session ID to subscribe to */
sessionId: string | undefined
/** Initial results (used before WebSocket connects) */
initialResults?: SlotResult[]
/** Initial parts (used before WebSocket connects) */
initialParts?: SessionPart[]
/** Whether to enable the WebSocket subscription */
enabled?: boolean
}
export interface LiveSessionTimeEstimateResult extends SessionTimeEstimate {
/** Number of correct answers */
correctCount: number
/** Accuracy as a decimal (0-1) */
accuracy: number
/** Whether connected to WebSocket */
isConnected: boolean
/** Whether receiving live updates */
isLive: boolean
/** Last activity timestamp from live updates */
lastActivityAt: Date | null
/** Error if connection failed */
error: string | null
}
// ============================================================================
// Hook
// ============================================================================
/**
* Hook to get real-time session time estimates via WebSocket
*
* Connects to the session's socket channel and receives practice state updates.
* Computes time estimates using the same functions as the student's practice view.
*
* @example
* ```tsx
* const estimate = useLiveSessionTimeEstimate({
* sessionId: session.id,
* initialResults: session.results,
* initialParts: session.parts,
* })
*
* return (
* <span>
* {estimate.isLive ? '🔴 Live: ' : ''}
* {estimate.estimatedTimeRemainingFormatted} left
* </span>
* )
* ```
*/
export function useLiveSessionTimeEstimate({
sessionId,
initialResults = [],
initialParts = [],
enabled = true,
}: LiveSessionTimeEstimateOptions): LiveSessionTimeEstimateResult {
// State for live data
const [liveResults, setLiveResults] = useState<SlotResult[]>(initialResults)
const [liveParts, setLiveParts] = useState<SessionPart[]>(initialParts)
const [lastActivityAt, setLastActivityAt] = useState<Date | null>(null)
const [isConnected, setIsConnected] = useState(false)
const [isLive, setIsLive] = useState(false)
const [error, setError] = useState<string | null>(null)
const socketRef = useRef<Socket | null>(null)
// Update initial data when props change (before WebSocket connects)
useEffect(() => {
if (!isLive) {
setLiveResults(initialResults)
setLiveParts(initialParts)
}
}, [initialResults, initialParts, isLive])
// Cleanup function
const cleanup = useCallback(() => {
if (socketRef.current) {
socketRef.current.disconnect()
socketRef.current = null
}
setIsConnected(false)
setIsLive(false)
}, [])
// WebSocket subscription
useEffect(() => {
if (!sessionId || !enabled) {
cleanup()
return
}
// Create socket connection
const socket = createSocket({
reconnection: true,
reconnectionDelay: 1000,
reconnectionAttempts: 5,
})
socketRef.current = socket
socket.on('connect', () => {
console.log('[LiveSessionTimeEstimate] Connected, subscribing to session:', sessionId)
setIsConnected(true)
setError(null)
// Subscribe to session updates (read-only, no observer auth needed)
socket.emit('subscribe-session-stats', { sessionId })
})
socket.on('disconnect', () => {
console.log('[LiveSessionTimeEstimate] Disconnected')
setIsConnected(false)
setIsLive(false)
})
socket.on('connect_error', (err) => {
console.error('[LiveSessionTimeEstimate] Connection error:', err)
setError('Failed to connect')
setIsConnected(false)
})
// Listen for practice state updates
socket.on('practice-state', (data: PracticeStateEvent) => {
console.log('[LiveSessionTimeEstimate] Received practice-state:', {
problemNumber: data.currentProblemNumber,
totalProblems: data.totalProblems,
resultsCount: (data.slotResults as SlotResult[] | undefined)?.length ?? 0,
})
// Update parts if provided
if (data.sessionParts) {
setLiveParts(data.sessionParts as SessionPart[])
}
// Update results if provided
if (data.slotResults) {
setLiveResults(data.slotResults as SlotResult[])
}
// Update last activity time
setLastActivityAt(new Date())
setIsLive(true)
})
// Listen for session ended
socket.on('session-ended', () => {
console.log('[LiveSessionTimeEstimate] Session ended')
setIsLive(false)
})
return () => {
console.log('[LiveSessionTimeEstimate] Cleaning up')
socket.emit('unsubscribe-session-stats', { sessionId })
socket.disconnect()
socketRef.current = null
}
}, [sessionId, enabled, cleanup])
// Compute time estimates from current data
const results = liveResults
const parts = liveParts
const totalProblems = parts.reduce((sum, p) => sum + (p.slots?.length ?? 0), 0)
const completedProblems = results.length
const problemsRemaining = totalProblems - completedProblems
// Calculate correctness stats
const correctCount = results.filter((r) => r.isCorrect).length
const accuracy = completedProblems > 0 ? correctCount / completedProblems : 0
const timingStats = calculateTimingStats(results, parts)
const estimatedTimeRemainingMs = calculateEstimatedTimeRemainingMs(timingStats, problemsRemaining)
const estimatedTimeRemainingFormatted = formatEstimatedTimeRemaining(estimatedTimeRemainingMs)
return {
timingStats,
problemsRemaining,
totalProblems,
completedProblems,
correctCount,
accuracy,
estimatedTimeRemainingMs,
estimatedTimeRemainingFormatted,
isConnected,
isLive,
lastActivityAt,
error,
}
}
|