Files
compor-academy/hooks/useCourse.ts
Cauê Faleiros 21085e887d
All checks were successful
CI / Validate frontend and API (push) Successful in 2m22s
CI / Build and publish Docker images (push) Successful in 1m6s
feat: finalize academy redesign and production readiness
Align admin, community, search, library, learning and course management with the mockup. Add saved courses, download history, public community feed, instructor directory, backend search, course views, admin content tools and community moderation. Harden API and Nginx for production.
2026-11-05 15:06:53 -03:00

82 lines
3.8 KiB
TypeScript

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Course, Lesson } from '../types';
import { getCourseById, getLessonProgress, saveLessonCompletion } from '../services/db';
import { useCatalog } from '../context/CatalogContext';
import { useAuth } from '../context/AuthContext';
/** A course from the shared catalogue, or fetched on its own when it is not listed there. */
export const useCourse = (courseId?: string) => {
const { courseById, isLoading: catalogLoading } = useCatalog();
const listed = courseId ? courseById(courseId) : undefined;
const [fetched, setFetched] = useState<Course | null | undefined>(undefined);
useEffect(() => {
if (!courseId || listed || catalogLoading) return;
let cancelled = false;
getCourseById(courseId).then((course) => { if (!cancelled) setFetched(course); });
return () => { cancelled = true; };
}, [catalogLoading, courseId, listed]);
const course = listed || fetched || undefined;
const isLoading = !course && (catalogLoading || fetched === undefined);
return { course, isLoading, missing: !course && !isLoading };
};
/** The learner's saved lesson progress for a course, with optimistic completion updates. */
export const useLessonProgress = (course?: Course) => {
const { user } = useAuth();
const { reload: reloadCatalog } = useCatalog();
const [completedIds, setCompletedIds] = useState<string[]>([]);
const [watched, setWatched] = useState<Record<string, number>>({});
// Which course the progress belongs to, so a stale value is never read as loaded.
const [loadedFor, setLoadedFor] = useState<string | null>(null);
const lastSaved = useRef<Record<string, number>>({});
const completedRef = useRef<string[]>([]);
completedRef.current = completedIds;
useEffect(() => {
setCompletedIds([]);
setWatched({});
lastSaved.current = {};
if (!course || !user) { setLoadedFor(course?.id ?? ''); return; }
let cancelled = false;
getLessonProgress(course.id).then((progress) => {
if (cancelled) return;
setCompletedIds(progress.filter((item) => item.completedAt).map((item) => item.lessonId));
const seconds = Object.fromEntries(progress.map((item) => [item.lessonId, item.watchedSeconds]));
setWatched(seconds);
lastSaved.current = { ...seconds };
}).catch(() => setCompletedIds([])).finally(() => { if (!cancelled) setLoadedFor(course.id); });
return () => { cancelled = true; };
}, [course?.id, user?.id]);
const markCompleted = useCallback((lessonId: string, watchedSeconds?: number) => {
if (!user || completedRef.current.includes(lessonId)) return;
const previous = completedRef.current;
setCompletedIds([...previous, lessonId]);
saveLessonCompletion(lessonId, true, watchedSeconds)
.then(() => reloadCatalog())
.catch(() => setCompletedIds(previous));
}, [reloadCatalog, user]);
const toggleCompleted = useCallback((lessonId: string) => {
if (!user) return;
if (completedRef.current.includes(lessonId)) {
const previous = completedRef.current;
setCompletedIds(previous.filter((id) => id !== lessonId));
saveLessonCompletion(lessonId, false)
.then(() => reloadCatalog())
.catch(() => setCompletedIds(previous));
} else {
markCompleted(lessonId);
}
}, [markCompleted, reloadCatalog, user]);
const completed = useMemo(() => new Set(completedIds), [completedIds]);
const next: Lesson | undefined = course?.lessons.find((lesson) => !completed.has(lesson.id)) || course?.lessons[0];
const nextIndex = next && course ? course.lessons.indexOf(next) : 0;
const loaded = loadedFor === (course?.id ?? '');
return { completed, watched, setWatched, lastSaved, loaded, markCompleted, toggleCompleted, next, nextIndex, doneCount: completed.size };
};