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.
This commit is contained in:
81
hooks/useCourse.ts
Normal file
81
hooks/useCourse.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
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 };
|
||||
};
|
||||
18
hooks/useMediaQuery.ts
Normal file
18
hooks/useMediaQuery.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export const MOBILE_QUERY = '(max-width: 900px)';
|
||||
|
||||
export const useMediaQuery = (query: string) => {
|
||||
const [matches, setMatches] = useState(() => typeof window !== 'undefined' && window.matchMedia(query).matches);
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(query);
|
||||
const update = () => setMatches(media.matches);
|
||||
update();
|
||||
media.addEventListener('change', update);
|
||||
return () => media.removeEventListener('change', update);
|
||||
}, [query]);
|
||||
return matches;
|
||||
};
|
||||
|
||||
/** Mobile (≤900px) has its own navigation and screens, not the desktop squeezed. */
|
||||
export const useIsMobile = () => useMediaQuery(MOBILE_QUERY);
|
||||
63
hooks/useSavedCourses.ts
Normal file
63
hooks/useSavedCourses.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { savedCourseApi } from '../services/api';
|
||||
|
||||
const legacyKeyFor = (userId: string) => `ca-saved-courses:${userId}`;
|
||||
|
||||
const readLegacy = (userId?: string) => {
|
||||
if (!userId) return [] as string[];
|
||||
try {
|
||||
const value = JSON.parse(localStorage.getItem(legacyKeyFor(userId)) || '[]');
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === 'string' && /^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(item))
|
||||
: [];
|
||||
} catch { return [] as string[]; }
|
||||
};
|
||||
|
||||
/** Saved courses follow the signed-in account and are stored by the API. */
|
||||
export const useSavedCourses = () => {
|
||||
const { user } = useAuth();
|
||||
const [ids, setIds] = useState<string[]>([]);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setIds([]);
|
||||
setLoaded(false);
|
||||
if (!user) { setLoaded(true); return; }
|
||||
|
||||
const load = async () => {
|
||||
const legacy = readLegacy(user.id);
|
||||
try {
|
||||
if (legacy.length) {
|
||||
// Move saves created before the API existed, then keep only the server copy.
|
||||
const results = await Promise.allSettled(legacy.map((courseId) => savedCourseApi.save(courseId)));
|
||||
if (results.every((result) => result.status === 'fulfilled')) {
|
||||
localStorage.removeItem(legacyKeyFor(user.id));
|
||||
}
|
||||
}
|
||||
const response = await savedCourseApi.list();
|
||||
if (!cancelled) setIds(response.data.map((item) => item.courseId));
|
||||
} catch {
|
||||
if (!cancelled) setIds(legacy);
|
||||
} finally {
|
||||
if (!cancelled) setLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
void load();
|
||||
return () => { cancelled = true; };
|
||||
}, [user?.id]);
|
||||
|
||||
const toggle = useCallback((courseId: string) => {
|
||||
if (!user) return;
|
||||
const previous = ids;
|
||||
const wasSaved = previous.includes(courseId);
|
||||
const next = wasSaved ? previous.filter((id) => id !== courseId) : [...previous, courseId];
|
||||
setIds(next);
|
||||
const request = wasSaved ? savedCourseApi.remove(courseId) : savedCourseApi.save(courseId);
|
||||
request.catch(() => setIds(previous));
|
||||
}, [ids, user]);
|
||||
|
||||
return { ids, loaded, toggle, isSaved: (courseId: string) => ids.includes(courseId) };
|
||||
};
|
||||
Reference in New Issue
Block a user