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 | /** * Hook for managing player curriculum progress * * Provides access to curriculum position, skill mastery, and practice sessions * for the currently selected student (player). * * Uses React Query for data fetching and caching, enabling SSR prefetching. */ 'use client' import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query' import { api } from '@/lib/queryClient' import { curriculumKeys } from '@/lib/queryKeys' // Re-export query keys for consumers export { curriculumKeys } from '@/lib/queryKeys' // ============================================================================ // Types // ============================================================================ export interface CurriculumPosition { playerId: string currentLevel: number currentPhaseId: string worksheetPreset: string | null visualizationMode: boolean } export interface SkillMasteryData { skillId: string attempts: number correct: number /** Whether this skill is in the student's active practice rotation */ isPracticing: boolean /** Practice level: 'none' | 'abacus' | 'visual' */ practiceLevel: import('@/db/schema/player-skill-mastery').PracticeLevel lastPracticedAt: Date | null } export interface PracticeSessionData { id: string phaseId: string problemsAttempted: number problemsCorrect: number skillsUsed: string[] visualizationMode: boolean startedAt: Date completedAt: Date | null } export interface CurriculumData { curriculum: CurriculumPosition | null skills: SkillMasteryData[] recentSessions: PracticeSessionData[] } // ============================================================================ // API Functions // ============================================================================ async function fetchCurriculum(playerId: string): Promise<CurriculumData> { const response = await api(`curriculum/${playerId}`) if (!response.ok) { throw new Error(`Failed to fetch curriculum: ${response.statusText}`) } const data = await response.json() return { curriculum: data.curriculum, skills: data.skills || [], recentSessions: data.recentSessions || [], } } // ============================================================================ // Hooks // ============================================================================ /** * Hook for fetching curriculum data (useQuery version) * Use this when you need loading/error states */ export function usePlayerCurriculumQuery(playerId: string | null) { return useQuery({ queryKey: curriculumKeys.detail(playerId ?? ''), queryFn: () => fetchCurriculum(playerId!), enabled: !!playerId, }) } /** * Hook for fetching curriculum data (useSuspenseQuery version) * Use this in SSR contexts where data is prefetched */ export function usePlayerCurriculumSuspense(playerId: string) { return useSuspenseQuery({ queryKey: curriculumKeys.detail(playerId), queryFn: () => fetchCurriculum(playerId), }) } /** * Hook for curriculum mutations (advance phase, record attempts, etc.) */ export function usePlayerCurriculumMutations(playerId: string | null) { const queryClient = useQueryClient() const invalidate = () => { if (playerId) { queryClient.invalidateQueries({ queryKey: curriculumKeys.detail(playerId), }) } } // Advance to next phase const advancePhase = useMutation({ mutationFn: async ({ nextPhaseId, nextLevel }: { nextPhaseId: string; nextLevel?: number }) => { if (!playerId) throw new Error('No player selected') const response = await api(`curriculum/${playerId}/advance`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ nextPhaseId, nextLevel }), }) if (!response.ok) { throw new Error(`Failed to advance phase: ${response.statusText}`) } return response.json() }, onSuccess: invalidate, }) // Record a single skill attempt const recordAttempt = useMutation({ mutationFn: async ({ skillId, isCorrect }: { skillId: string; isCorrect: boolean }) => { if (!playerId) throw new Error('No player selected') const response = await api(`curriculum/${playerId}/skills`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ skillId, isCorrect }), }) if (!response.ok) { throw new Error(`Failed to record attempt: ${response.statusText}`) } return response.json() }, onSuccess: (updatedSkill) => { // Optimistically update the skill in cache if (playerId) { queryClient.setQueryData<CurriculumData>(curriculumKeys.detail(playerId), (old) => { if (!old) return old return { ...old, skills: old.skills.some((s) => s.skillId === updatedSkill.skillId) ? old.skills.map((s) => (s.skillId === updatedSkill.skillId ? updatedSkill : s)) : [...old.skills, updatedSkill], } }) } }, }) // Record multiple skill attempts const recordAttempts = useMutation({ mutationFn: async (results: Array<{ skillId: string; isCorrect: boolean }>) => { if (!playerId) throw new Error('No player selected') const response = await api(`curriculum/${playerId}/skills/batch`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ results }), }) if (!response.ok) { throw new Error(`Failed to record attempts: ${response.statusText}`) } return response.json() }, onSuccess: invalidate, }) // Start a practice session const startSession = useMutation({ mutationFn: async ({ phaseId, visualizationMode = false, }: { phaseId: string visualizationMode?: boolean }) => { if (!playerId) throw new Error('No player selected') const response = await api(`curriculum/${playerId}/sessions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ phaseId, visualizationMode }), }) if (!response.ok) { throw new Error(`Failed to start session: ${response.statusText}`) } return response.json() }, onSuccess: (session) => { if (playerId) { queryClient.setQueryData<CurriculumData>(curriculumKeys.detail(playerId), (old) => { if (!old) return old return { ...old, recentSessions: [session, ...old.recentSessions].slice(0, 200), } }) } }, }) // Complete a practice session const completeSession = useMutation({ mutationFn: async ({ sessionId, data, }: { sessionId: string data?: { problemsAttempted?: number problemsCorrect?: number skillsUsed?: string[] } }) => { if (!playerId) throw new Error('No player selected') const response = await api(`curriculum/${playerId}/sessions/${sessionId}/complete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data || {}), }) if (!response.ok) { throw new Error(`Failed to complete session: ${response.statusText}`) } return response.json() }, onSuccess: invalidate, }) // Update curriculum settings (worksheet preset, visualization mode) const updateSettings = useMutation({ mutationFn: async (settings: { worksheetPreset?: string | null visualizationMode?: boolean }) => { if (!playerId) throw new Error('No player selected') const response = await api(`curriculum/${playerId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(settings), }) if (!response.ok) { throw new Error(`Failed to update settings: ${response.statusText}`) } return response.json() }, onSuccess: (updated) => { if (playerId) { queryClient.setQueryData<CurriculumData>(curriculumKeys.detail(playerId), (old) => { if (!old) return old return { ...old, curriculum: updated } }) } }, }) return { advancePhase, recordAttempt, recordAttempts, startSession, completeSession, updateSettings, } } /** * Combined hook that provides both query and mutations * This maintains backwards compatibility with existing code */ export function usePlayerCurriculum(playerId: string | null) { const query = usePlayerCurriculumQuery(playerId) const mutations = usePlayerCurriculumMutations(playerId) const queryClient = useQueryClient() // Refresh function for backwards compatibility const refresh = async () => { if (playerId) { await queryClient.invalidateQueries({ queryKey: curriculumKeys.detail(playerId), }) } } // Convenience wrappers for backwards compatibility const advancePhase = async (nextPhaseId: string, nextLevel?: number) => { await mutations.advancePhase.mutateAsync({ nextPhaseId, nextLevel }) } const recordAttempt = async (skillId: string, isCorrect: boolean) => { await mutations.recordAttempt.mutateAsync({ skillId, isCorrect }) } const recordAttempts = async (results: Array<{ skillId: string; isCorrect: boolean }>) => { await mutations.recordAttempts.mutateAsync(results) } const startSession = async ( phaseId: string, visualizationMode: boolean = false ): Promise<string | null> => { try { const session = await mutations.startSession.mutateAsync({ phaseId, visualizationMode, }) return session.id } catch { return null } } const completeSession = async ( sessionId: string, data?: { problemsAttempted?: number problemsCorrect?: number skillsUsed?: string[] } ) => { await mutations.completeSession.mutateAsync({ sessionId, data }) } const updateWorksheetPreset = async (preset: string | null) => { await mutations.updateSettings.mutateAsync({ worksheetPreset: preset }) } const toggleVisualizationMode = async () => { const current = query.data?.curriculum?.visualizationMode ?? false await mutations.updateSettings.mutateAsync({ visualizationMode: !current }) } return { // Data from query curriculum: query.data?.curriculum ?? null, skills: query.data?.skills ?? [], recentSessions: query.data?.recentSessions ?? [], isLoading: query.isLoading, error: query.error?.message ?? null, // Actions refresh, advancePhase, recordAttempt, recordAttempts, startSession, completeSession, updateWorksheetPreset, toggleVisualizationMode, } } // ============================================================================ // Standalone Mutations (for use outside of combined hook) // ============================================================================ /** * Hook: Set skill practice levels (manual skill management) * Used by dashboard to set per-skill practice levels (none/abacus/visual) * * Uses optimistic updates for instant UI feedback: * - Cache is updated immediately when mutation starts * - Rolled back if the API call fails * - Refetched on settle to ensure sync with server */ export function useSetSkillLevels() { const queryClient = useQueryClient() return useMutation({ mutationFn: async ({ playerId, skillLevels, }: { playerId: string skillLevels: Record<string, import('@/db/schema/player-skill-mastery').PracticeLevel> }) => { const response = await api(`curriculum/${playerId}/skills`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ skillLevels }), }) if (!response.ok) { const error = await response.json().catch(() => ({})) throw new Error(error.error || 'Failed to set skill levels') } return response.json() }, // Optimistic update: update cache immediately before API call onMutate: async ({ playerId, skillLevels }) => { // Cancel any outgoing refetches so they don't overwrite our optimistic update await queryClient.cancelQueries({ queryKey: curriculumKeys.detail(playerId), }) // Snapshot the previous value for rollback const previousData = queryClient.getQueryData(curriculumKeys.detail(playerId)) // Optimistically update the cache queryClient.setQueryData( curriculumKeys.detail(playerId), (old: CurriculumData | undefined) => { if (!old?.skills) return old return { ...old, skills: old.skills.map((skill) => ({ ...skill, practiceLevel: skillLevels[skill.skillId] ?? skill.practiceLevel, isPracticing: (skillLevels[skill.skillId] ?? skill.practiceLevel) !== 'none', })), } } ) // Return context with the previous value for rollback return { previousData } }, // Rollback on error onError: (_err, { playerId }, context) => { if (context?.previousData) { queryClient.setQueryData(curriculumKeys.detail(playerId), context.previousData) } }, // Always refetch after mutation to ensure sync with server onSettled: (_, __, { playerId }) => { queryClient.invalidateQueries({ queryKey: curriculumKeys.detail(playerId), }) }, }) } /** * @deprecated Use useSetSkillLevels instead. Kept for backwards compatibility. */ export function useSetMasteredSkills() { const queryClient = useQueryClient() return useMutation({ mutationFn: async ({ playerId, masteredSkillIds, }: { playerId: string masteredSkillIds: string[] }) => { const response = await api(`curriculum/${playerId}/skills`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ masteredSkillIds }), }) if (!response.ok) { const error = await response.json().catch(() => ({})) throw new Error(error.error || 'Failed to set mastered skills') } return response.json() }, onSettled: (_, __, { playerId }) => { queryClient.invalidateQueries({ queryKey: curriculumKeys.detail(playerId), }) }, }) } /** * Hook: Refresh skill recency (mark as recently practiced) * Used by dashboard to clear staleness warnings */ export function useRefreshSkillRecency() { const queryClient = useQueryClient() return useMutation({ mutationFn: async ({ playerId, skillId }: { playerId: string; skillId: string }) => { const response = await api(`curriculum/${playerId}/skills`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ skillId }), }) if (!response.ok) { const error = await response.json().catch(() => ({})) throw new Error(error.error || 'Failed to refresh skill') } return response.json() }, onSuccess: (_, { playerId }) => { queryClient.invalidateQueries({ queryKey: curriculumKeys.detail(playerId), }) }, }) } export default usePlayerCurriculum |