diff --git a/App.tsx b/App.tsx index 62bbe73..aeebc41 100644 --- a/App.tsx +++ b/App.tsx @@ -1,13 +1,12 @@ -import React, { useState } from 'react'; -import { HashRouter as Router, Routes, Route, Navigate } from 'react-router-dom'; -import { Navbar } from './components/Navbar'; -import { Hero } from './components/Hero'; -import { CourseGrid } from './components/CourseGrid'; +import React from 'react'; +import { BrowserRouter as Router, Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom'; import { ManageCourses } from './pages/ManageCourses'; import { MaterialsPage } from './pages/MaterialsPage'; -import { CoursePlayerModal } from './components/CoursePlayerModal'; import { AuthProvider, useAuth } from './context/AuthContext'; import { ToastProvider } from './context/ToastContext'; +import { ThemeProvider } from './context/ThemeContext'; +import { CatalogProvider } from './context/CatalogContext'; +import { AppShell } from './components/shell/AppShell'; import { Course, UserRole } from './types'; import { SuperAdmin } from './pages/SuperAdmin'; import { AccessTokenPage } from './pages/AccessTokenPage'; @@ -16,87 +15,63 @@ import { ProfilePage } from './pages/ProfilePage'; import { InstructorProfile } from './pages/InstructorProfile'; import { TrailDetail } from './pages/TrailDetail'; import { TrailPage } from './pages/TrailPage'; +import { AuthPage, homeFor } from './pages/AuthPage'; +import { paths } from './lib/routes'; +import { ExplorePage } from './pages/ExplorePage'; +import { SearchPage } from './pages/SearchPage'; +import { TrailsPage } from './pages/TrailsPage'; +import { ProfessorsPage } from './pages/ProfessorsPage'; +import { CommunityPage } from './pages/CommunityPage'; +import { DownloadsPage } from './pages/DownloadsPage'; +import { YouPage } from './pages/YouPage'; +import { ContinueCourse, CoursePage } from './pages/CoursePage'; +import { LessonPage } from './pages/LessonPage'; + +/** Keeps old /#/... links (invites, password resets, bookmarks) working after moving off HashRouter. */ +const LegacyHashRedirect: React.FC = () => { + const location = useLocation(); + const navigate = useNavigate(); + + React.useEffect(() => { + if (location.hash.startsWith('#/')) navigate(location.hash.slice(1), { replace: true }); + }, [location.hash, navigate]); + + return null; +}; -// Protected Route Component const ProtectedRoute: React.FC<{ children: React.ReactNode; allowedRoles?: UserRole[] }> = ({ children, allowedRoles }) => { const { user, isLoading } = useAuth(); if (isLoading) return null; - - if (!user) { - return ; - } - - if (allowedRoles && !allowedRoles.includes(user.role)) { - return ; - } + if (!user) return ; + if (allowedRoles && !allowedRoles.includes(user.role)) return ; return <>{children}; }; -// Home component -interface HomeProps { - onPlay: (course: Course) => void; -} - -const Home: React.FC = ({ onPlay }) => { - return ( -
- - -
- ); -}; - function AppContent() { - const [selectedCourse, setSelectedCourse] = useState(null); + const navigate = useNavigate(); + const setSelectedCourse = (course: Course) => navigate(paths.course(course.id)); return ( -
- {/* Navbar with Direct Materials Hub Trigger */} - - + - - } - /> - - {/* Full Dedicated Materials & Downloads Page */} - - - - } - /> - - {/* Professor Route - Protected */} - - - - } - /> - - - - - } - /> - } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> +
} /> } /> } /> } /> @@ -104,42 +79,25 @@ function AppContent() { } /> } /> } /> - - {/* Catch all redirect */} } />
- - {/* Global Player Modal */} - setSelectedCourse(null)} - /> - - {/* Footer */} -
-
-
- Compor HUB - | - Portal de Cursos & Central de Downloads -
-
- © {new Date().getFullYear()} Compor HUB. Todos os direitos reservados. -
-
-
-
+ ); } function App() { return ( - - - - - + + + + + + + + + + ); } diff --git a/BACKEND.md b/BACKEND.md index 4c75144..ea3b3c3 100644 --- a/BACKEND.md +++ b/BACKEND.md @@ -14,10 +14,16 @@ The API health endpoint is available at `http://localhost:3001/api/v1/health` an ## Current API -- `GET /api/v1/courses` returns published courses. +- `GET /api/v1/courses` returns published courses and, for authenticated learners, their completion percentage and last activity. - `GET /api/v1/courses/:courseId` returns one published course. +- `POST /api/v1/courses/:courseId/view` records a course view for the “most watched” shelves. - `GET /api/v1/courses/me/learning` returns the authenticated learner's started courses, ordered by their last activity, with completion percentage. - `GET /api/v1/courses/:courseId/progress` and `PUT /api/v1/lessons/:lessonId/progress` persist completion and watch position. +- `GET /api/v1/community/comments` returns the public, paginated community feed. +- `GET/PUT/DELETE /api/v1/saved-courses` keeps the authenticated learner's saved-course list. +- `GET /api/v1/downloads` and `POST /api/v1/downloads/:assetId` keep the authenticated learner's download history. +- `GET /api/v1/profiles/instructors` lists public instructor profiles. +- `GET /api/v1/search?q=&area=` searches courses, paths and public instructors. - `GET /api/v1/admin/audit-log` exposes the last 50 administrative actions to superadmins. ## Accounts and instructor access @@ -34,7 +40,7 @@ To create the first local administrator, set `SUPERADMIN_EMAIL`, `SUPERADMIN_PAS For local demos, `npm run db:seed-demo-content` imports the original frontend catalogue into PostgreSQL. It requires the bootstrap administrator to exist and skips courses already present. -Anonymous visitors can browse course and lesson information, but media and download links are removed from their response. A signed-in account is required to play lessons, download materials, track progress, or participate in discussion. +Anonymous visitors can browse course, path, instructor and community information, but media and download links are removed from their response. A signed-in account is required to play lessons, download materials, track progress, or participate in discussion. ## Provider boundaries diff --git a/components/CourseCard.tsx b/components/CourseCard.tsx index 421151f..1b99979 100644 --- a/components/CourseCard.tsx +++ b/components/CourseCard.tsx @@ -1,5 +1,10 @@ import React from 'react'; -import { PlayCircle, Download, FileText, CheckCircle2 } from 'lucide-react'; +import { + PlayCircleIcon as PlayCircle, + DownloadSimpleIcon as Download, + FileTextIcon as FileText, + CheckCircleIcon as CheckCircle2 +} from '@phosphor-icons/react'; import { Course, SectionVariant } from '../types'; import { CourseCoverImage } from './CourseCoverImage'; import { useNavigate } from 'react-router-dom'; diff --git a/components/CourseGrid.tsx b/components/CourseGrid.tsx deleted file mode 100644 index e4114c5..0000000 --- a/components/CourseGrid.tsx +++ /dev/null @@ -1,243 +0,0 @@ -import React, { useState, useEffect, useRef, useCallback } from 'react'; -import { CourseRow } from './CourseRow'; -import { Section, Course } from '../types'; -import { getCourses, getLearningPaths, PublicLearningPath } from '../services/db'; -import { useAuth } from '../context/AuthContext'; -import { Loader2, ChevronLeft, ChevronRight } from 'lucide-react'; -import { LearningPathRow } from './LearningPathRow'; - -interface CourseGridProps { - onCourseSelect?: (course: Course) => void; - selectedCategoryFilter?: string; -} - -export const CourseGrid: React.FC = ({ - onCourseSelect, - selectedCategoryFilter -}) => { - const [courses, setCourses] = useState([]); - const [paths, setPaths] = useState([]); - const [loading, setLoading] = useState(true); - const [activeCategory, setActiveCategory] = useState('all'); - const { user } = useAuth(); - - // Slider State & Refs for Categories - const categoryScrollRef = useRef(null); - const isMouseDownRef = useRef(false); - const startXRef = useRef(0); - const scrollLeftRef = useRef(0); - const draggedDistanceRef = useRef(0); - const [isDraggingCategory, setIsDraggingCategory] = useState(false); - const [canScrollCatLeft, setCanScrollCatLeft] = useState(false); - const [canScrollCatRight, setCanScrollCatRight] = useState(false); - - const checkCategoryBoundaries = useCallback(() => { - if (!categoryScrollRef.current) return; - const { scrollLeft, scrollWidth, clientWidth } = categoryScrollRef.current; - setCanScrollCatLeft(scrollLeft > 10); - setCanScrollCatRight(scrollLeft + clientWidth < scrollWidth - 10); - }, []); - - useEffect(() => { - const loadData = async () => { - try { - const [loadedCourses, loadedPaths] = await Promise.all([getCourses(), getLearningPaths()]); - setCourses(loadedCourses); - setPaths(loadedPaths); - } finally { - setLoading(false); - } - }; - - loadData(); - }, [user]); - - useEffect(() => { - checkCategoryBoundaries(); - window.addEventListener('resize', checkCategoryBoundaries); - return () => window.removeEventListener('resize', checkCategoryBoundaries); - }, [checkCategoryBoundaries, courses]); - - const handleCategoryScroll = (direction: 'left' | 'right') => { - if (!categoryScrollRef.current) return; - const scrollAmount = 300; - categoryScrollRef.current.scrollBy({ - left: direction === 'left' ? -scrollAmount : scrollAmount, - behavior: 'smooth' - }); - }; - - const handleCatMouseDown = (e: React.MouseEvent) => { - if (!categoryScrollRef.current) return; - isMouseDownRef.current = true; - startXRef.current = e.pageX - categoryScrollRef.current.offsetLeft; - scrollLeftRef.current = categoryScrollRef.current.scrollLeft; - draggedDistanceRef.current = 0; - setIsDraggingCategory(false); - }; - - const handleCatMouseMove = (e: React.MouseEvent) => { - if (!isMouseDownRef.current || !categoryScrollRef.current) return; - e.preventDefault(); - const x = e.pageX - categoryScrollRef.current.offsetLeft; - const walk = (x - startXRef.current) * 1.4; - draggedDistanceRef.current = Math.abs(walk); - - if (draggedDistanceRef.current > 5) { - setIsDraggingCategory(true); - categoryScrollRef.current.scrollLeft = scrollLeftRef.current - walk; - } - }; - - const handleCatMouseUp = () => { - isMouseDownRef.current = false; - setTimeout(() => { - setIsDraggingCategory(false); - draggedDistanceRef.current = 0; - }, 50); - }; - - const handleCategoryClick = (cat: string) => { - if (draggedDistanceRef.current < 8) { - setActiveCategory(cat); - } - }; - - const categories = Array.from(new Set(courses.map((course) => course.category))) - .sort((left, right) => left.localeCompare(right, 'pt-BR')); - - if (loading) { - return ( -
- -
- ); - } - - if (courses.length === 0) { - return ( -
-
-

Cursos em breve

-

Ainda não há cursos publicados. Cadastre o primeiro curso no Painel do Instrutor.

-
-
- ); - } - - // Filter courses if a specific category is active - const filteredCourses = activeCategory === 'all' - ? courses - : courses.filter(c => c.category === activeCategory); - - // Group into curated sections for Netflix/Apple TV style layout - const sections: Section[] = [ - { - title: activeCategory === 'all' ? 'Cursos em Destaque' : activeCategory, - variant: 'landscape', - courses: filteredCourses - }, - { - title: 'Com Materiais & Planilhas para Download', - variant: 'landscape', - courses: courses.filter(c => (c.attachments && c.attachments.length > 0) || c.lessons.some(l => l.attachments && l.attachments.length > 0)) - }, - ]; - - return ( -
- - {/* Category Pills Slider Container */} -
-
- - {/* Scroll Button Left */} - {canScrollCatLeft && ( - - )} - - {/* Left Gradient Fade */} - {canScrollCatLeft && ( -
- )} - - {/* Scrollable Category Track */} -
- - - {categories.map(cat => { - const count = courses.filter(c => c.category === cat).length; - return ( - - ); - })} -
- - {/* Right Gradient Fade */} - {canScrollCatRight && ( -
- )} - - {/* Scroll Button Right */} - {canScrollCatRight && ( - - )} - -
-
- - {/* Sections Rows */} - {sections.map((section, index) => ( - section.courses.length > 0 && ( - - ) - ))} - {activeCategory === 'all' && paths.length > 0 && } -
- ); -}; diff --git a/components/CoursePlayerModal.tsx b/components/CoursePlayerModal.tsx deleted file mode 100644 index 5c668cd..0000000 --- a/components/CoursePlayerModal.tsx +++ /dev/null @@ -1,682 +0,0 @@ -import React, { useState, useEffect, useRef } from 'react'; -import { - X, - Send, - User as UserIcon, - Lightbulb, - Paperclip, - Lock, - Unlock, - ListVideo, - Play, - Download, - Sparkles, - MessageSquare, - CheckCircle2, - Check, - Share2, - FileText -} from 'lucide-react'; -import { Course, Comment, Lesson, Attachment } from '../types'; -import { useAuth } from '../context/AuthContext'; -import { getComments, getLessonProgress, saveComment, saveLessonCompletion, saveLessonProgress, incrementViews } from '../services/db'; -import { LoginModal } from './LoginModal'; -import { MaterialCard } from './MaterialCard'; -import { courseApi, LessonPlayback } from '../services/api'; - -declare global { - interface Window { - playerjs?: { - Player: new (element: HTMLIFrameElement) => { - on: (event: string, listener: (data?: { seconds?: number; duration?: number }) => void) => void; - }; - }; - } -} - -let bunnyPlayerJsPromise: Promise | null = null; - -const loadBunnyPlayerJs = () => { - if (window.playerjs) return Promise.resolve(); - if (bunnyPlayerJsPromise) return bunnyPlayerJsPromise; - bunnyPlayerJsPromise = new Promise((resolve, reject) => { - const script = document.createElement('script'); - script.src = 'https://assets.mediadelivery.net/playerjs/player-0.1.0.min.js'; - script.async = true; - script.onload = () => resolve(); - script.onerror = () => reject(new Error('Bunny player events could not be loaded')); - document.head.appendChild(script); - }); - return bunnyPlayerJsPromise; -}; - -interface CoursePlayerModalProps { - course: Course | null; - onClose: () => void; -} - -export const CoursePlayerModal: React.FC = ({ course, onClose }) => { - const { user } = useAuth(); - const [comments, setComments] = useState([]); - const [newComment, setNewComment] = useState(''); - const [currentLesson, setCurrentLesson] = useState(null); - const [completedLessonIds, setCompletedLessonIds] = useState([]); - const [watchedSecondsByLesson, setWatchedSecondsByLesson] = useState>({}); - const [showLoginPrompt, setShowLoginPrompt] = useState(false); - const [activeTab, setActiveTab] = useState<'playlist' | 'materials' | 'discussion'>('playlist'); - const [copiedLink, setCopiedLink] = useState(false); - const [playback, setPlayback] = useState(null); - const [playbackError, setPlaybackError] = useState(''); - - const videoRef = useRef(null); - const bunnyFrameRef = useRef(null); - const lastProgressSave = useRef>({}); - - // Load course data and this learner's saved state from PostgreSQL. - useEffect(() => { - if (course) { - incrementViews(course.id); - setCompletedLessonIds([]); - setWatchedSecondsByLesson({}); - lastProgressSave.current = {}; - if (user) { - getComments(course.id).then(setComments).catch(() => setComments([])); - getLessonProgress(course.id).then((progress) => { - const completed = progress.filter((item) => item.completedAt).map((item) => item.lessonId); - setCompletedLessonIds(completed); - setWatchedSecondsByLesson(Object.fromEntries(progress.map((item) => [item.lessonId, item.watchedSeconds]))); - lastProgressSave.current = Object.fromEntries(progress.map((item) => [item.lessonId, item.watchedSeconds])); - const nextIncomplete = course.lessons.find((lesson) => !completed.includes(lesson.id)); - if (nextIncomplete) setCurrentLesson(nextIncomplete); - }).catch(() => setCompletedLessonIds([])); - } else { - setComments([]); - } - - // Select first lesson by default - if (course.lessons && course.lessons.length > 0) { - setCurrentLesson(course.lessons[0]); - } - } - }, [course, user]); - - // The API verifies the session before returning a time-limited Bunny embed - // URL. A video provider key is never sent to the browser. - useEffect(() => { - if (!course || !user || !currentLesson) { - setPlayback(null); - setPlaybackError(''); - return; - } - let cancelled = false; - setPlayback(null); - setPlaybackError(''); - courseApi.playback(course.id, currentLesson.id) - .then((response) => { - if (!cancelled) setPlayback(response.data); - }) - .catch((error) => { - if (!cancelled) setPlaybackError(error instanceof Error ? error.message : 'Não foi possível carregar este vídeo.'); - }); - return () => { cancelled = true; }; - }, [course, user, currentLesson]); - - // Persist completed lessons and recalculate progress - const updateCompletedLessons = (newCompleted: string[]) => { - setCompletedLessonIds(newCompleted); - if (course) { - } - }; - - const toggleLessonCompleted = (lessonId: string) => { - if (!user) { - setShowLoginPrompt(true); - return; - } - if (completedLessonIds.includes(lessonId)) { - const updated = completedLessonIds.filter(id => id !== lessonId); - updateCompletedLessons(updated); - saveLessonCompletion(lessonId, false).catch(() => updateCompletedLessons(completedLessonIds)); - } else { - markLessonCompleted(lessonId); - } - }; - - const markLessonCompleted = (lessonId: string, watchedSeconds?: number) => { - if (!user || completedLessonIds.includes(lessonId)) return; - const previous = completedLessonIds; - updateCompletedLessons([...previous, lessonId]); - saveLessonCompletion(lessonId, true, watchedSeconds).catch(() => updateCompletedLessons(previous)); - }; - - // Video finished automatically -> mark lesson as completed - const handleVideoEnded = () => { - if (currentLesson && !completedLessonIds.includes(currentLesson.id)) { - markLessonCompleted(currentLesson.id, Math.round(videoRef.current?.duration || 0)); - } - - // Auto-advance to next lesson if available - if (course?.lessons && currentLesson) { - const currentIndex = course.lessons.findIndex(l => l.id === currentLesson.id); - if (currentIndex >= 0 && currentIndex < course.lessons.length - 1) { - const nextLesson = course.lessons[currentIndex + 1]; - if (user) { - setTimeout(() => { - setCurrentLesson(nextLesson); - }, 1000); - } - } - } - }; - - // Track video progress - const handleTimeUpdate = () => { - if (videoRef.current) { - const { currentTime, duration } = videoRef.current; - if (duration > 0) { - if (user && currentLesson && currentTime - (lastProgressSave.current[currentLesson.id] || 0) >= 30) { - const watchedSeconds = Math.floor(currentTime); - lastProgressSave.current[currentLesson.id] = watchedSeconds; - setWatchedSecondsByLesson((current) => ({ ...current, [currentLesson.id]: watchedSeconds })); - saveLessonProgress(currentLesson.id, watchedSeconds).catch(() => undefined); - } - const percent = Math.round((currentTime / duration) * 100); - // Automatically mark as complete when reaching 95%+ - if (percent >= 95 && currentLesson && !completedLessonIds.includes(currentLesson.id)) { - markLessonCompleted(currentLesson.id, Math.round(currentTime)); - } - } - } - }; - - // Bunny's iframe does not expose an HTMLVideoElement. Player.js receives - // Bunny's trusted playback events and sends the same progress updates used - // for external video providers. - useEffect(() => { - if (!playback || playback.kind !== 'embed' || !currentLesson || !user) return; - let disposed = false; - const lessonId = currentLesson.id; - void loadBunnyPlayerJs().then(() => { - if (disposed || !bunnyFrameRef.current || !window.playerjs) return; - const player = new window.playerjs.Player(bunnyFrameRef.current); - player.on('timeupdate', (data) => { - const watchedSeconds = Math.floor(data?.seconds || 0); - if (disposed || watchedSeconds <= 0 || watchedSeconds - (lastProgressSave.current[lessonId] || 0) < 30) return; - lastProgressSave.current[lessonId] = watchedSeconds; - setWatchedSecondsByLesson((current) => ({ ...current, [lessonId]: watchedSeconds })); - saveLessonProgress(lessonId, watchedSeconds).catch(() => undefined); - }); - player.on('ended', (data) => { - if (disposed) return; - markLessonCompleted(lessonId, Math.floor(data?.duration || data?.seconds || 0)); - }); - }).catch(() => undefined); - return () => { disposed = true; }; - }, [playback, currentLesson, user, completedLessonIds]); - - const restoreWatchPosition = () => { - if (!currentLesson || !videoRef.current) return; - const watchedSeconds = watchedSecondsByLesson[currentLesson.id] || 0; - if (watchedSeconds > 0 && watchedSeconds < videoRef.current.duration - 5) videoRef.current.currentTime = watchedSeconds; - }; - - const handleAddComment = async (e: React.FormEvent) => { - e.preventDefault(); - if (!newComment.trim() || !course) return; - - const comment = { - courseId: course.id, - lessonId: currentLesson?.id, - text: newComment, - }; - - try { - const savedComment = await saveComment(comment); - setComments([savedComment, ...comments]); - setNewComment(''); - } catch { - // The server remains the source of truth; leave the text intact for a retry. - } - }; - - const changeLesson = (lesson: Lesson) => { - setCurrentLesson(lesson); - }; - - const handleShare = () => { - navigator.clipboard.writeText(window.location.href); - setCopiedLink(true); - setTimeout(() => setCopiedLink(false), 2500); - }; - - // Collect all downloadable materials for this course (Global + All Lessons) - const allCourseAttachments: Array<{ attachment: Attachment; source: string }> = []; - - if (course?.attachments) { - course.attachments.forEach(att => { - allCourseAttachments.push({ attachment: att, source: 'Material Geral do Curso' }); - }); - } - - if (course?.lessons) { - course.lessons.forEach(l => { - if (l.attachments) { - l.attachments.forEach(att => { - allCourseAttachments.push({ attachment: att, source: l.title }); - }); - } - }); - } - - const currentLessonAttachments = currentLesson?.attachments || []; - - // Access Control Logic - const canWatch = currentLesson && Boolean(user); - - if (!course) return null; - - return ( -
- {/* Top Bar Floating Controls */} -
-
- - - {course.title} - -
- -
- - - -
-
- -
-
- - {/* Main Left Column: Video & Lesson Details */} -
- - {/* Video Player Section */} -
- {canWatch ? ( - playback ? ( - playback.kind === 'embed' && playback.embedUrl ? ( -