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 | 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 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 3x 3x 3x 6x 6x 6x 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 1x 1x 2x 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 23x 23x 23x 23x 23x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 8x 8x 8x 8x 8x 10x 10x 10x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10x 10x 10x 23x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 4x 23x 10x 10x 10x 10x 23x 23x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 2x 2x 2x 1x 1x 2x 5x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 1x 1x 1x 1x 1x 5x 2x 2x 2x 2x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | 'use client'
import { useRef } from 'react'
import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import type { Player } from '@/db/schema/players'
import { api } from '@/lib/queryClient'
import { playerKeys } from '@/lib/queryKeys'
import type { StudentWithSkillData } from '@/utils/studentGrouping'
// Re-export query keys for consumers
export { playerKeys } from '@/lib/queryKeys'
/**
* Fetch all players for the current user
*/
async function fetchPlayers(): Promise<Player[]> {
const res = await api('players')
if (!res.ok) throw new Error('Failed to fetch players')
const data = await res.json()
return data.players
}
/**
* Fetch all players with skill data for the current user
*/
async function fetchPlayersWithSkillData(): Promise<StudentWithSkillData[]> {
const res = await api('players/with-skill-data')
if (!res.ok) throw new Error('Failed to fetch players with skill data')
const data = await res.json()
return data.players
}
/**
* Create a new player
*/
/** Error with a machine-readable code for limit-reached responses */
export class ApiError extends Error {
code?: string
constructor(message: string, code?: string) {
super(message)
this.code = code
}
}
async function createPlayer(
newPlayer: Pick<Player, 'name' | 'emoji' | 'color'> & {
birthday?: Player['birthday']
isActive?: boolean
isPracticeStudent?: boolean
}
): Promise<Player> {
const res = await api('players', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newPlayer),
})
if (!res.ok) {
const data = await res.json().catch(() => ({}))
throw new ApiError(data.error || 'Failed to create player', data.code)
}
const data = await res.json()
return data.player
}
/**
* Update a player
*/
async function updatePlayer({
id,
updates,
}: {
id: string
updates: Partial<
Pick<Player, 'name' | 'emoji' | 'color' | 'isActive' | 'isArchived' | 'notes' | 'birthday'>
>
}): Promise<Player> {
const res = await api(`players/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updates),
})
if (!res.ok) {
// Extract error message from response if available
try {
const errorData = await res.json()
throw new Error(errorData.error || 'Failed to update player')
} catch (_jsonError) {
throw new Error('Failed to update player')
}
}
const data = await res.json()
return data.player
}
/**
* Delete a player
*/
async function deletePlayer(id: string): Promise<void> {
const res = await api(`players/${id}`, {
method: 'DELETE',
})
if (!res.ok) throw new Error('Failed to delete player')
}
/**
* Hook: Fetch all players
*/
export function useUserPlayers() {
return useQuery({
queryKey: playerKeys.list(),
queryFn: fetchPlayers,
})
}
/**
* Hook: Fetch all players with Suspense (for SSR contexts)
*/
export function useUserPlayersSuspense() {
return useSuspenseQuery({
queryKey: playerKeys.list(),
queryFn: fetchPlayers,
})
}
/**
* Hook: Fetch all players with skill data
* Used by the practice page for grouping/filtering
*
* When data arrives with batch-fetched enrichment fields, seeds per-student
* React Query caches so downstream hooks (useEnrolledClassrooms, useStudentPresence)
* find cached data and skip individual HTTP requests.
*/
export function usePlayersWithSkillData(options?: { initialData?: StudentWithSkillData[] }) {
const queryClient = useQueryClient()
const query = useQuery({
queryKey: playerKeys.listWithSkillData(),
queryFn: fetchPlayersWithSkillData,
initialData: options?.initialData,
// Keep data fresh but don't refetch too aggressively
staleTime: 30_000, // 30 seconds
})
// Seed per-student caches synchronously during render.
// This MUST happen before child components (StudentActionMenu) mount and fire
// their useEnrolledClassrooms/useStudentPresence hooks. useEffect is too late.
const lastSeededDataRef = useRef<StudentWithSkillData[] | undefined>()
if (query.data && query.data !== lastSeededDataRef.current) {
lastSeededDataRef.current = query.data
for (const player of query.data) {
if (player.enrolledClassrooms !== undefined) {
queryClient.setQueryData(
playerKeys.enrolledClassrooms(player.id),
player.enrolledClassrooms
)
}
if (player.currentPresence !== undefined) {
queryClient.setQueryData(playerKeys.presence(player.id), player.currentPresence)
}
}
}
return query
}
/**
* Hook: Fetch a single player with Suspense (for SSR contexts)
*/
export function usePlayerSuspense(playerId: string) {
return useSuspenseQuery({
queryKey: playerKeys.detail(playerId),
queryFn: async () => {
const res = await api(`players/${playerId}`)
if (!res.ok) throw new Error('Failed to fetch player')
const data = await res.json()
return data.player as Player
},
})
}
/**
* Hook: Create a new player
*/
export function useCreatePlayer() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: createPlayer,
onMutate: async (newPlayer) => {
// Cancel outgoing refetches for all player queries
await queryClient.cancelQueries({ queryKey: playerKeys.all })
// Snapshot previous values
const previousPlayers = queryClient.getQueryData<Player[]>(playerKeys.list())
const previousPlayersWithSkillData = queryClient.getQueryData<StudentWithSkillData[]>(
playerKeys.listWithSkillData()
)
// Create optimistic player
const optimisticPlayer: Player = {
id: `temp-${Date.now()}`, // Temporary ID
...newPlayer,
createdAt: new Date(),
isActive: newPlayer.isActive ?? false,
isPracticeStudent: newPlayer.isPracticeStudent ?? true,
isArchived: false,
userId: 'temp-user', // Temporary userId, will be replaced by server response
helpSettings: null, // Will be set by server with default values
notes: null,
birthday: newPlayer.birthday ?? null,
isExpungeable: false,
familyCode: null, // Will be generated by server
familyCodeGeneratedAt: null,
}
// Optimistically update player list
if (previousPlayers) {
queryClient.setQueryData<Player[]>(playerKeys.list(), [
...previousPlayers,
optimisticPlayer,
])
}
// Optimistically update players with skill data (used by practice page)
if (previousPlayersWithSkillData) {
const optimisticPlayerWithSkillData: StudentWithSkillData = {
...optimisticPlayer,
practicingSkills: [],
lastPracticedAt: null,
skillCategory: null,
intervention: null,
enrolledClassrooms: [],
currentPresence: null,
activeSession: null,
}
queryClient.setQueryData<StudentWithSkillData[]>(playerKeys.listWithSkillData(), [
...previousPlayersWithSkillData,
optimisticPlayerWithSkillData,
])
}
return { previousPlayers, previousPlayersWithSkillData }
},
onError: (_err, _newPlayer, context) => {
// Rollback on error
if (context?.previousPlayers) {
queryClient.setQueryData(playerKeys.list(), context.previousPlayers)
}
if (context?.previousPlayersWithSkillData) {
queryClient.setQueryData(
playerKeys.listWithSkillData(),
context.previousPlayersWithSkillData
)
}
},
onSettled: () => {
// Always refetch after error or success
// Invalidate ALL player queries (including listWithSkillData used by practice page)
queryClient.invalidateQueries({ queryKey: playerKeys.all })
},
})
}
/**
* Hook: Update a player
*/
export function useUpdatePlayer() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: updatePlayer,
onMutate: async ({ id, updates }) => {
// Cancel outgoing refetches for all player lists
await queryClient.cancelQueries({ queryKey: playerKeys.all })
// Snapshot previous values
const previousPlayers = queryClient.getQueryData<Player[]>(playerKeys.list())
const previousPlayersWithSkillData = queryClient.getQueryData<StudentWithSkillData[]>(
playerKeys.listWithSkillData()
)
// Optimistically update player list
if (previousPlayers) {
const optimisticPlayers = previousPlayers.map((player) =>
player.id === id ? { ...player, ...updates } : player
)
queryClient.setQueryData<Player[]>(playerKeys.list(), optimisticPlayers)
}
// Optimistically update players with skill data
if (previousPlayersWithSkillData) {
const optimisticPlayers = previousPlayersWithSkillData.map((player) =>
player.id === id ? { ...player, ...updates } : player
)
queryClient.setQueryData<StudentWithSkillData[]>(
playerKeys.listWithSkillData(),
optimisticPlayers
)
}
return { previousPlayers, previousPlayersWithSkillData }
},
onError: (err, _variables, context) => {
// Log error for debugging
console.error('Failed to update player:', err.message)
// Rollback on error
if (context?.previousPlayers) {
queryClient.setQueryData(playerKeys.list(), context.previousPlayers)
}
if (context?.previousPlayersWithSkillData) {
queryClient.setQueryData(
playerKeys.listWithSkillData(),
context.previousPlayersWithSkillData
)
}
},
onSettled: (_data, _error, { id }) => {
// Refetch after error or success - invalidate all player queries
queryClient.invalidateQueries({ queryKey: playerKeys.all })
if (_data) {
queryClient.setQueryData(playerKeys.detail(id), _data)
}
},
})
}
/**
* Hook: Delete a player
*/
export function useDeletePlayer() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: deletePlayer,
onMutate: async (id) => {
// Cancel outgoing refetches
await queryClient.cancelQueries({ queryKey: playerKeys.lists() })
// Snapshot previous value
const previousPlayers = queryClient.getQueryData<Player[]>(playerKeys.list())
// Optimistically remove from list
if (previousPlayers) {
const optimisticPlayers = previousPlayers.filter((player) => player.id !== id)
queryClient.setQueryData<Player[]>(playerKeys.list(), optimisticPlayers)
}
return { previousPlayers }
},
onError: (_err, _id, context) => {
// Rollback on error
if (context?.previousPlayers) {
queryClient.setQueryData(playerKeys.list(), context.previousPlayers)
}
},
onSettled: () => {
// Refetch after error or success
// Invalidate ALL player queries (including listWithSkillData used by practice page)
queryClient.invalidateQueries({ queryKey: playerKeys.all })
},
})
}
/**
* Hook: Set player active status
*/
export function useSetPlayerActive() {
const { mutate: updatePlayer } = useUpdatePlayer()
return {
setActive: (id: string, isActive: boolean) => {
updatePlayer({ id, updates: { isActive } })
},
}
}
/**
* Link to an existing child via family code
*/
interface LinkChildResult {
success: boolean
player?: Player
error?: string
}
async function linkChild(familyCode: string): Promise<LinkChildResult> {
const res = await api('family/link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ familyCode }),
})
const data = await res.json()
if (!res.ok || !data.success) {
return { success: false, error: data.error || 'Failed to link child' }
}
return { success: true, player: data.player }
}
/**
* Hook: Link to an existing child via family code
*/
export function useLinkChild() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: linkChild,
onSuccess: (data) => {
if (data.success) {
// Invalidate ALL player queries to show the newly linked child
// This includes both playerKeys.list() and playerKeys.listWithSkillData()
queryClient.invalidateQueries({ queryKey: playerKeys.all })
}
},
})
}
|