Spaces:
Running
Running
Download algospaced-ui/src/hooks/useReviewQueue.ts from iamfebin/algospaced-dsa: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/src/hooks/useReviewQueue.ts
- Command line
-
hf download hf://spaces/iamfebin/algospaced-dsa/algospaced-ui/src/hooks/useReviewQueue.ts
-
curl -L -o useReviewQueue.ts https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/src/hooks/useReviewQueue.ts
18.4 kB
| import { useState, useRef, useCallback, useEffect } from 'react'; | |
| import { supabase, getStoredSession } from '../firebaseClient'; | |
| import confetti from 'canvas-confetti'; | |
| import { companionStore } from '../features/companion'; | |
| import { | |
| findCatalogProblem, | |
| getNextUnsolvedProblem, | |
| type CatalogProblem | |
| } from '../services/catalogService'; | |
| import { activateCatalogProblem } from '../services/reviewService'; | |
| import { getGitHubConfig, pushSolutionToGitHub } from '../services/githubSyncService'; | |
| import type { ReviewItem } from '../types/reviewTypes'; | |
| import { useEconomyStore } from '../stores/useEconomyStore'; | |
| function getEffectiveUid(currentUid?: string): string { | |
| if (currentUid && currentUid !== 'sandbox-user-id') { | |
| return currentUid; | |
| } | |
| try { | |
| const session = getStoredSession(); | |
| if (session?.user?.id && session.user.id !== 'sandbox-user-id') { | |
| return session.user.id; | |
| } | |
| } catch { | |
| // Graceful fallback | |
| } | |
| return 'guest'; | |
| } | |
| interface UseReviewQueueOptions { | |
| overrideProblemId?: string | null; | |
| refreshTrigger?: number; | |
| onClearOverride?: () => void; | |
| } | |
| export function useReviewQueue({ | |
| overrideProblemId, | |
| refreshTrigger, | |
| onClearOverride | |
| }: UseReviewQueueOptions) { | |
| const [reviews, setReviews] = useState<ReviewItem[]>([]); | |
| const [loading, setLoading] = useState(true); | |
| const [queueError, setQueueError] = useState<string | null>(null); | |
| const [submitting, setSubmitting] = useState(false); | |
| const [submittingRating, setSubmittingRating] = useState<number | null>(null); | |
| const [gradeError, setGradeError] = useState<string | null>(null); | |
| const [code, setCode] = useState(''); | |
| const [nextMilestone, setNextMilestone] = useState<CatalogProblem | null>(null); | |
| const [activatingMilestone, setActivatingMilestone] = useState(false); | |
| const [currentUserId, setCurrentUserId] = useState<string | undefined>(() => { | |
| try { | |
| return getStoredSession()?.user?.id; | |
| } catch { | |
| return undefined; | |
| } | |
| }); | |
| const confettiTriggeredRef = useRef(false); | |
| // Keep refs for callback props to guarantee referential stability across parent re-renders | |
| const onClearOverrideRef = useRef(onClearOverride); | |
| const isTransitioningOverrideRef = useRef(false); | |
| useEffect(() => { | |
| onClearOverrideRef.current = onClearOverride; | |
| }); | |
| const fetchQueue = useCallback(async (showLoading = true) => { | |
| if (showLoading) { | |
| setLoading(true); | |
| setGradeError(null); | |
| setQueueError(null); | |
| setCode(''); | |
| confettiTriggeredRef.current = false; | |
| } else { | |
| setGradeError(null); | |
| } | |
| let uidKey = getEffectiveUid(currentUserId); | |
| try { | |
| if (typeof navigator !== 'undefined' && !navigator.onLine) { | |
| throw new Error('Network connection offline.'); | |
| } | |
| const { data: { session } } = await supabase.auth.getSession(); | |
| const token = session ? session.access_token : 'sandbox'; | |
| if (session?.user?.id) { | |
| setCurrentUserId(session.user.id); | |
| uidKey = getEffectiveUid(session.user.id); | |
| } | |
| const headers = { 'Authorization': `Bearer ${token}` }; | |
| // 1. Fetch current due queue with 4-second timeout to prevent 30s+ offline hangs | |
| const abortCtrl = new AbortController(); | |
| const timerId = setTimeout(() => abortCtrl.abort(), 4000); | |
| let dueRes: Response; | |
| try { | |
| dueRes = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/reviews/due`, { | |
| headers, | |
| signal: abortCtrl.signal, | |
| }); | |
| } finally { | |
| clearTimeout(timerId); | |
| } | |
| if (!dueRes.ok) { | |
| throw new Error(`Failed to load review queue: HTTP ${dueRes.status}`); | |
| } | |
| let data: ReviewItem[] = await dueRes.json(); | |
| if (!Array.isArray(data)) { | |
| data = []; | |
| } | |
| // 2. If reviewing a problem from journey path (or override id) | |
| if (overrideProblemId) { | |
| const targetStr = String(overrideProblemId).trim().toLowerCase(); | |
| const existingIdx = data.findIndex((r) => { | |
| const prob = r.problems; | |
| if (r.problem_id && String(r.problem_id).trim().toLowerCase() === targetStr) return true; | |
| if (prob?.id && String(prob.id).trim().toLowerCase() === targetStr) return true; | |
| if (prob?.problem_number !== undefined && prob?.problem_number !== null && String(prob.problem_number) === targetStr) return true; | |
| if (prob?.name && prob.name.trim().toLowerCase() === targetStr) return true; | |
| return false; | |
| }); | |
| if (existingIdx > 0) { | |
| // If already in queue, prioritize it to the front as Card 1 | |
| const [targetReview] = data.splice(existingIdx, 1); | |
| data.unshift(targetReview); | |
| } else if (existingIdx === -1) { | |
| // If not in cards yet: fetch its review record or activate it into FSRS and add to cards | |
| let overrideReview: ReviewItem | null = null; | |
| const overrideRes = await fetch( | |
| `${import.meta.env.VITE_API_BASE_URL}/api/reviews/problems/id/${overrideProblemId}`, | |
| { headers } | |
| ); | |
| if (overrideRes.ok) { | |
| const overrideData = await overrideRes.json(); | |
| if (Array.isArray(overrideData) && overrideData.length > 0) { | |
| overrideReview = overrideData[0]; | |
| } | |
| } | |
| if (!overrideReview) { | |
| const isNumeric = /^\d+$/.test(overrideProblemId); | |
| const catalogProb = findCatalogProblem( | |
| isNumeric ? parseInt(overrideProblemId, 10) : undefined, | |
| overrideProblemId | |
| ); | |
| if (catalogProb) { | |
| try { | |
| const actRes = await activateCatalogProblem(catalogProb); | |
| if (actRes?.problem_id) { | |
| const retryRes = await fetch( | |
| `${import.meta.env.VITE_API_BASE_URL}/api/reviews/problems/id/${actRes.problem_id}`, | |
| { headers } | |
| ); | |
| if (retryRes.ok) { | |
| const retryData = await retryRes.json(); | |
| if (Array.isArray(retryData) && retryData.length > 0) { | |
| overrideReview = retryData[0]; | |
| } | |
| } | |
| } | |
| } catch (actErr) { | |
| console.error('Failed to auto-activate problem for override review:', actErr); | |
| } | |
| } | |
| } | |
| if (overrideReview) { | |
| data.unshift(overrideReview); | |
| } | |
| } | |
| } | |
| setReviews(data); | |
| setQueueError(null); | |
| try { | |
| localStorage.setItem(`algospaced_review_queue_${uidKey}`, JSON.stringify(data)); | |
| } catch { | |
| // Safe fallback | |
| } | |
| if (data && data.length > 0) { | |
| if (showLoading) { | |
| const activeReview = data[0]; | |
| const rawProblem = activeReview.problems; | |
| const probNum = rawProblem?.problem_number ?? | |
| (/^\d+$/.test(activeReview?.problem_id || '') ? parseInt(activeReview.problem_id, 10) : undefined); | |
| const catalogProb = findCatalogProblem( | |
| probNum, | |
| rawProblem?.id || activeReview?.problem_id, | |
| rawProblem?.name | |
| ); | |
| const starter = catalogProb?.starter_code || rawProblem?.starter_code || ''; | |
| setCode(starter); | |
| } | |
| } else { | |
| // Empty queue: discover next milestone from journey progress | |
| try { | |
| const progRes = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/journey-progress`, { headers }); | |
| if (progRes.ok) { | |
| const progData: number[] = await progRes.json(); | |
| setNextMilestone(getNextUnsolvedProblem(new Set(progData)) ?? null); | |
| } else { | |
| setNextMilestone(getNextUnsolvedProblem(new Set()) ?? null); | |
| } | |
| } catch { | |
| setNextMilestone(getNextUnsolvedProblem(new Set()) ?? null); | |
| } | |
| } | |
| } catch (err) { | |
| console.error('Error fetching review queue:', err); | |
| const errMsg = err instanceof Error ? err.message : 'Network error loading review queue.'; | |
| // Attempt to restore cached review items from localStorage | |
| let restoredFromCache = false; | |
| try { | |
| const cachedRaw = localStorage.getItem(`algospaced_review_queue_${uidKey}`); | |
| if (cachedRaw) { | |
| const cachedData: ReviewItem[] = JSON.parse(cachedRaw); | |
| if (Array.isArray(cachedData) && cachedData.length > 0) { | |
| setReviews(cachedData); | |
| restoredFromCache = true; | |
| setQueueError(null); | |
| if (showLoading) { | |
| const activeReview = cachedData[0]; | |
| const rawProblem = activeReview.problems; | |
| const probNum = rawProblem?.problem_number ?? | |
| (/^\d+$/.test(activeReview?.problem_id || '') ? parseInt(activeReview.problem_id, 10) : undefined); | |
| const catalogProb = findCatalogProblem( | |
| probNum, | |
| rawProblem?.id || activeReview?.problem_id, | |
| rawProblem?.name | |
| ); | |
| const starter = catalogProb?.starter_code || rawProblem?.starter_code || ''; | |
| setCode(starter); | |
| } | |
| } | |
| } | |
| } catch (cacheErr) { | |
| console.warn('Failed to parse cached review items:', cacheErr); | |
| } | |
| if (!restoredFromCache) { | |
| setQueueError(errMsg); | |
| } | |
| } finally { | |
| setLoading(false); | |
| } | |
| }, [overrideProblemId, currentUserId]); | |
| useEffect(() => { | |
| if (isTransitioningOverrideRef.current) { | |
| isTransitioningOverrideRef.current = false; | |
| return; | |
| } | |
| let isCancelled = false; | |
| // Invoke asynchronously to avoid cascading synchronous render in effect body | |
| const timer = setTimeout(() => { | |
| if (!isCancelled) { | |
| void fetchQueue(true); | |
| } | |
| }, 0); | |
| return () => { | |
| isCancelled = true; | |
| clearTimeout(timer); | |
| }; | |
| }, [fetchQueue, refreshTrigger]); | |
| // Confetti trigger when queue completes | |
| useEffect(() => { | |
| if (!loading && !queueError && reviews.length === 0 && !overrideProblemId && !confettiTriggeredRef.current) { | |
| confettiTriggeredRef.current = true; | |
| try { | |
| confetti({ | |
| particleCount: 90, | |
| spread: 70, | |
| origin: { y: 0.6 } | |
| }); | |
| } catch { | |
| // Safe fallback if canvas is not ready | |
| } | |
| } | |
| }, [loading, queueError, reviews.length, overrideProblemId]); | |
| const handleGrade = useCallback( | |
| async (rating: number) => { | |
| if (reviews.length === 0 || submitting) return; | |
| const activeReview = reviews[0]; | |
| if (!activeReview || !activeReview.id) return; | |
| setSubmitting(true); | |
| setSubmittingRating(rating); | |
| setGradeError(null); | |
| const savedReviewsSnapshot = [...reviews]; | |
| try { | |
| const { data: { session } } = await supabase.auth.getSession(); | |
| const token = session ? session.access_token : 'sandbox'; | |
| const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/reviews/complete`, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| 'Authorization': `Bearer ${token}` | |
| }, | |
| body: JSON.stringify({ | |
| review_id: activeReview.id, | |
| fsrs_state: activeReview.fsrs_state ?? 0, | |
| fsrs_step: activeReview.fsrs_step ?? 0, | |
| fsrs_stability: activeReview.fsrs_stability ?? 0.0, | |
| fsrs_difficulty: activeReview.fsrs_difficulty ?? 0.0, | |
| fsrs_elapsed_days: activeReview.fsrs_elapsed_days ?? 0, | |
| fsrs_scheduled_days: activeReview.fsrs_scheduled_days ?? 0, | |
| fsrs_reps: activeReview.fsrs_reps ?? 0, | |
| fsrs_lapses: activeReview.fsrs_lapses ?? 0, | |
| last_reviewed: activeReview.last_reviewed, | |
| rating | |
| }) | |
| }); | |
| if (res.ok) { | |
| // Award player gold based on rating: +5g Again (1), +15g Hard (2), +25g Good (3), +35g Easy (4) | |
| const goldAward = rating === 4 ? 35 : rating === 3 ? 25 : rating === 2 ? 15 : 5; | |
| useEconomyStore.getState().awardGold(goldAward, `Completed review rating ${rating}`); | |
| // Trigger Princess Companion reaction & tower floor advance | |
| const probName = activeReview?.problems?.name || ''; | |
| const probPattern = activeReview?.problems?.pattern || ''; | |
| let companionRating: 'Correct' | 'Mixed' | 'Incorrect' = 'Correct'; | |
| if (rating === 1) companionRating = 'Incorrect'; | |
| else if (rating === 2) companionRating = 'Mixed'; | |
| else companionRating = 'Correct'; | |
| companionStore.addReviewEvent(companionRating, probName, probPattern).catch(() => {}); | |
| // Auto-commit solution to user's GitHub repository if configured | |
| const ghConfig = getGitHubConfig(); | |
| const solutionToPush = code.trim() || activeReview?.problems?.reference_code || ''; | |
| if (ghConfig.token && ghConfig.repoName && ghConfig.autoCommit && solutionToPush) { | |
| pushSolutionToGitHub({ | |
| token: ghConfig.token, | |
| repo: ghConfig.repoName, | |
| branch: ghConfig.branch, | |
| problem_number: activeReview?.problems?.problem_number, | |
| problem_name: probName || 'Algorithm Problem', | |
| pattern: probPattern || 'Algorithms', | |
| difficulty: activeReview?.problems?.difficulty || 'Medium', | |
| optimal_time: activeReview?.problems?.optimal_time || 'O(N)', | |
| optimal_space: activeReview?.problems?.optimal_space || 'O(1)', | |
| description: activeReview?.problems?.description || '', | |
| code: solutionToPush, | |
| }).catch((err) => { | |
| console.warn('GitHub background auto-commit failed:', err); | |
| }); | |
| } | |
| if (overrideProblemId && onClearOverrideRef.current) { | |
| isTransitioningOverrideRef.current = true; | |
| onClearOverrideRef.current(); | |
| } | |
| // Optimistically remove the completed card for instant, snappy UI | |
| setReviews((prev) => { | |
| const nextReviews = prev.slice(1); | |
| try { | |
| const effectiveUid = getEffectiveUid(currentUserId); | |
| localStorage.setItem(`algospaced_review_queue_${effectiveUid}`, JSON.stringify(nextReviews)); | |
| } catch { | |
| // Safe fallback | |
| } | |
| if (nextReviews.length > 0) { | |
| const nextActive = nextReviews[0]; | |
| const rawProb = nextActive.problems; | |
| const probNum = rawProb?.problem_number ?? | |
| (/^\d+$/.test(nextActive?.problem_id || '') ? parseInt(nextActive.problem_id, 10) : undefined); | |
| const catalogProb = findCatalogProblem( | |
| probNum, | |
| rawProb?.id || nextActive?.problem_id, | |
| rawProb?.name | |
| ); | |
| const nextStarter = catalogProb?.starter_code || rawProb?.starter_code || ''; | |
| setCode(nextStarter); | |
| } else { | |
| setCode(''); | |
| } | |
| return nextReviews; | |
| }); | |
| setQueueError(null); | |
| void fetchQueue(false); | |
| } else { | |
| const errorData = await res.json().catch(() => ({})); | |
| setGradeError(errorData.detail || `Server returned error (${res.status}). Please try again.`); | |
| setReviews(savedReviewsSnapshot); | |
| } | |
| } catch (err: unknown) { | |
| console.error('Error logging review completion:', err); | |
| const msg = err instanceof Error ? err.message : 'Network connection failed while logging review.'; | |
| setGradeError(msg); | |
| setReviews(savedReviewsSnapshot); | |
| } finally { | |
| setSubmitting(false); | |
| setSubmittingRating(null); | |
| } | |
| }, | |
| [reviews, submitting, overrideProblemId, fetchQueue, code, currentUserId] | |
| ); | |
| const handleActivateNextMilestone = useCallback(async () => { | |
| if (!nextMilestone || activatingMilestone) return; | |
| setActivatingMilestone(true); | |
| try { | |
| await activateCatalogProblem(nextMilestone); | |
| await fetchQueue(); | |
| } catch (err: unknown) { | |
| console.error('Failed to activate next milestone:', err); | |
| } finally { | |
| setActivatingMilestone(false); | |
| } | |
| }, [nextMilestone, activatingMilestone, fetchQueue]); | |
| const handleResetStarterCode = useCallback(() => { | |
| const activeReview = reviews[0]; | |
| const rawProblem = activeReview?.problems; | |
| const probNum = rawProblem?.problem_number ?? | |
| (/^\d+$/.test(activeReview?.problem_id || '') ? parseInt(activeReview.problem_id, 10) : undefined); | |
| const catalogProb = findCatalogProblem( | |
| probNum, | |
| rawProblem?.id || activeReview?.problem_id, | |
| rawProblem?.name | |
| ); | |
| const starter = catalogProb?.starter_code || rawProblem?.starter_code || ''; | |
| setCode(starter); | |
| }, [reviews]); | |
| const handleSelectCard = useCallback( | |
| (index: number) => { | |
| if (index <= 0 || index >= reviews.length || submitting) return; | |
| if (overrideProblemId && onClearOverrideRef.current) { | |
| isTransitioningOverrideRef.current = true; | |
| onClearOverrideRef.current(); | |
| } | |
| const target = reviews[index]; | |
| if (!target) return; | |
| const rawProb = target.problems; | |
| const probNum = | |
| rawProb?.problem_number ?? | |
| (/^\d+$/.test(target?.problem_id || '') ? parseInt(target.problem_id, 10) : undefined); | |
| const catalogProb = findCatalogProblem( | |
| probNum, | |
| rawProb?.id || target?.problem_id, | |
| rawProb?.name | |
| ); | |
| const starter = catalogProb?.starter_code || rawProb?.starter_code || ''; | |
| setCode(starter); | |
| setReviews((prev) => { | |
| const targetIdx = prev.findIndex((r) => (r.id && r.id === target.id) || r === target); | |
| if (targetIdx <= 0) return prev; | |
| const item = prev[targetIdx]; | |
| return [item, ...prev.slice(0, targetIdx), ...prev.slice(targetIdx + 1)]; | |
| }); | |
| }, | |
| [reviews, submitting, overrideProblemId] | |
| ); | |
| return { | |
| reviews, | |
| setReviews, | |
| loading, | |
| queueError, | |
| submitting, | |
| submittingRating, | |
| gradeError, | |
| setGradeError, | |
| code, | |
| setCode, | |
| nextMilestone, | |
| activatingMilestone, | |
| currentUserId, | |
| fetchQueue, | |
| handleGrade, | |
| handleSelectCard, | |
| handleActivateNextMilestone, | |
| handleResetStarterCode | |
| }; | |
| } | |