Files
compor-academy/pages/LessonPage.tsx
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

216 lines
13 KiB
TypeScript

import React, { useEffect, useRef, useState } from 'react';
import { Link, Navigate, useNavigate, useParams } from 'react-router-dom';
import { CaretRightIcon, CheckIcon, CircleNotchIcon, PlayIcon } from '@phosphor-icons/react';
import { Comment, Course, Lesson } from '../types';
import { getComments, incrementViews, saveComment, saveLessonProgress } from '../services/db';
import { useCourse, useLessonProgress } from '../hooks/useCourse';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import { LessonVideo } from '../components/course/LessonVideo';
import { MaterialRow, useMaterialAction } from '../components/course/Materials';
import { Avatar } from '../components/ui/Avatar';
import { lessonDuration } from '../lib/format';
import { paths } from '../lib/routes';
import { signUpState } from './CoursePage';
import { useIsMobile } from '../hooks/useMediaQuery';
import { attachmentIcon, MaterialButton } from '../components/course/Materials';
export type LessonTab = 'aulas' | 'materiais' | 'discussao';
/** Everything the lesson screen does, shared by the desktop and mobile layouts. */
export const useLessonScreen = (course: Course | undefined, lesson: Lesson | undefined) => {
const { user } = useAuth();
const { showToast } = useToast();
const navigate = useNavigate();
const progress = useLessonProgress(course);
const [comments, setComments] = useState<Comment[]>([]);
const [draft, setDraft] = useState('');
const [posting, setPosting] = useState(false);
const advanceTimer = useRef<number>();
const trackedView = useRef<string>('');
useEffect(() => {
if (!user || !course || !lesson) return;
const key = `${course.id}:${lesson.id}`;
if (trackedView.current === key) return;
trackedView.current = key;
void incrementViews(course.id);
}, [course?.id, lesson?.id, user?.id]);
useEffect(() => {
if (!course || !user) { setComments([]); return; }
getComments(course.id).then(setComments).catch(() => setComments([]));
}, [course?.id, user?.id]);
useEffect(() => () => window.clearTimeout(advanceTimer.current), []);
const index = course && lesson ? course.lessons.indexOf(lesson) : -1;
const nextLesson = course && index >= 0 ? course.lessons[index + 1] : undefined;
const onTime = (seconds: number, duration?: number) => {
if (!user || !lesson) return;
const lessonId = lesson.id;
const watchedSeconds = Math.floor(seconds);
if (watchedSeconds > 0 && watchedSeconds - (progress.lastSaved.current[lessonId] || 0) >= 30) {
progress.lastSaved.current[lessonId] = watchedSeconds;
progress.setWatched((current) => ({ ...current, [lessonId]: watchedSeconds }));
saveLessonProgress(lessonId, watchedSeconds).catch(() => undefined);
}
// Automatically mark as complete when reaching 95%+.
if (duration && duration > 0 && Math.round((seconds / duration) * 100) >= 95) progress.markCompleted(lessonId, Math.round(seconds));
};
const onEnded = (seconds: number, autoAdvance: boolean) => {
if (!lesson) return;
progress.markCompleted(lesson.id, seconds);
if (autoAdvance && nextLesson && course && user) {
advanceTimer.current = window.setTimeout(() => navigate(paths.lesson(course.id, nextLesson.id)), 1000);
}
};
const postComment = async (event?: React.FormEvent) => {
event?.preventDefault();
if (!draft.trim() || !course) return;
setPosting(true);
try {
const saved = await saveComment({ courseId: course.id, lessonId: lesson?.id, text: draft });
setComments((current) => [saved, ...current]);
setDraft('');
} catch {
// The server remains the source of truth; keep the text for a retry.
showToast('Não foi possível publicar agora. Tente de novo.', 'error');
} finally {
setPosting(false);
}
};
const materials = lesson?.attachments || [];
const courseLevel = course?.attachments || [];
return { progress, comments, draft, setDraft, posting, postComment, onTime, onEnded, index, nextLesson, materials, courseLevel };
};
export const CommentItem: React.FC<{ comment: Comment; lessonNumber?: number }> = ({ comment, lessonNumber }) => (
<div className="comment">
<Avatar name={comment.user} size="sm" />
<div>
<div className="h"><b>{comment.user}</b>{[lessonNumber ? `Aula ${lessonNumber}` : '', comment.date].filter(Boolean).join(' · ')}</div>
<p>{comment.text}</p>
{comment.reply && (
<div className="reply">
<div className="h"><b>Resposta</b><span className="tagp">Professor</span>{comment.replyDate ? ` ${comment.replyDate}` : ''}</div>
<p>{comment.reply}</p>
</div>
)}
</div>
</div>
);
export const LessonPage: React.FC = () => {
const { courseId, lessonId } = useParams<{ courseId: string; lessonId: string }>();
const { user, isLoading: authLoading } = useAuth();
const { course, isLoading, missing } = useCourse(courseId);
const lesson = course?.lessons.find((item) => item.id === lessonId);
const screen = useLessonScreen(course, lesson);
const action = useMaterialAction();
const [tab, setTab] = useState<LessonTab>('aulas');
const isMobile = useIsMobile();
if (authLoading || isLoading) return <main className="wrap page"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
if (!user) return <Navigate to={paths.signUp} state={signUpState} replace />;
if (missing || !course) return <Navigate to={paths.explore} replace />;
if (!lesson) return <Navigate to={paths.course(course.id)} replace />;
const { progress, comments, index, nextLesson } = screen;
const lessonNumber = (comment: Comment) => (comment.lessonId ? course.lessons.findIndex((item) => item.id === comment.lessonId) + 1 : 0);
const done = progress.completed.has(lesson.id);
const pct = course.lessons.length ? Math.round((progress.doneCount / course.lessons.length) * 100) : 0;
if (isMobile) return <main className="m-page has-cta enter">
<LessonVideo key={lesson.id} className="m-player" courseId={course.id} lesson={lesson} resumeAt={progress.watched[lesson.id] || 0} onTime={screen.onTime} onEnded={screen.onEnded} />
<div className="m-gut"><header className="m-title"><h1>{lesson.title}</h1><p className="num">Aula {index + 1} de {course.lessons.length}{course.instructor ? ` · ${course.instructor}` : ''}</p></header>
<div className="m-seg" role="tablist">{([['aulas', 'Aulas'], ['materiais', 'Materiais'], ['discussao', 'Discussão']] as const).map(([key, label]) => <button key={key} type="button" role="tab" aria-selected={tab === key} onClick={() => setTab(key)}>{label}</button>)}</div>
<div className="m-pane">
{tab === 'aulas' && <section className="m-group"><div className="m-list">{course.lessons.map((item, itemIndex) => <Link className="m-row" to={paths.lesson(course.id, item.id)} key={item.id} aria-current={item.id === lesson.id ? 'page' : undefined}><span className="m-n num">{progress.completed.has(item.id) ? <CheckIcon className="ph" /> : item.id === lesson.id ? <PlayIcon className="ph" weight="fill" /> : itemIndex + 1}</span><span className="m-rt"><b>{item.title}</b><small>{lessonDuration(item)}</small></span><CaretRightIcon className="m-chev" /></Link>)}</div></section>}
{tab === 'materiais' && <section className="m-group"><div className="m-list">{[...screen.materials, ...screen.courseLevel].map((attachment) => <div className="m-row" key={attachment.id}><span className="m-ic">{attachmentIcon(attachment.type)}</span><span className="m-rt"><b>{attachment.name}</b><small>{attachment.size}</small></span><MaterialButton attachment={attachment} action={action} label={false} className="m-icb" /></div>)}</div>{screen.materials.length + screen.courseLevel.length === 0 && <p className="m-empty">Esta aula não tem materiais.</p>}</section>}
{tab === 'discussao' && <><form className="m-compose" onSubmit={screen.postComment}><textarea rows={1} value={screen.draft} onChange={(event) => screen.setDraft(event.target.value)} placeholder="Escreva uma pergunta" aria-label="Escrever comentário" /><button className="btn m-sm" type="submit" disabled={!screen.draft.trim() || screen.posting}>Enviar</button></form><div className="m-thread">{comments.map((comment) => <CommentItem key={comment.id} comment={comment} />)}{!comments.length && <p className="m-empty">Nenhuma pergunta ainda.</p>}</div></>}
</div>
</div>
<div className="m-cta"><button type="button" className="btn sec m-half" onClick={() => progress.toggleCompleted(lesson.id)} aria-pressed={done}><CheckIcon className="ph" />{done ? 'Vista' : 'Marcar vista'}</button>{nextLesson ? <Link className="btn m-half" to={paths.lesson(course.id, nextLesson.id)}>Próxima aula</Link> : <Link className="btn m-half" to={paths.course(course.id)}>Concluir</Link>}</div>
</main>;
return (
<main className="wrap page enter">
<div className="crumb">
<Link to={paths.explore}>Explorar</Link><CaretRightIcon className="ph" weight="bold" />
<Link to={paths.course(course.id)}>{course.title}</Link><CaretRightIcon className="ph" weight="bold" />
<span>Aula {index + 1}</span>
</div>
<div className="split">
<div>
<LessonVideo key={lesson.id} courseId={course.id} lesson={lesson} resumeAt={progress.watched[lesson.id] || 0} onTime={screen.onTime} onEnded={screen.onEnded} />
<div className="ltitle">
<div>
<h1>{lesson.title}</h1>
<small className="num">Aula {index + 1} de {course.lessons.length}{course.instructor ? ` · ${course.instructor}` : ''}</small>
</div>
<div className="acts">
<button type="button" className="btn sec" onClick={() => progress.toggleCompleted(lesson.id)} aria-pressed={done}>
{done ? <><CheckIcon className="ph" weight="bold" /> Vista</> : 'Marcar como vista'}
</button>
{nextLesson && <Link className="btn" to={paths.lesson(course.id, nextLesson.id)}>Próxima aula</Link>}
</div>
</div>
<div className="tabs" role="tablist">
{([['aulas', 'Aulas', course.lessons.length], ['materiais', 'Materiais', screen.materials.length + screen.courseLevel.length], ['discussao', 'Discussão', comments.length]] as const).map(([key, label, count]) => (
<button key={key} type="button" role="tab" aria-selected={tab === key} onClick={() => setTab(key)}>{label}<span className="num">{count}</span></button>
))}
</div>
<div className="pane">
{tab === 'aulas' && (
<ol className="lessons">
{course.lessons.map((item, itemIndex) => (
<li key={item.id}>
<Link className="row" to={paths.lesson(course.id, item.id)} aria-current={item.id === lesson.id ? 'true' : undefined}>
<span className="i num">{progress.completed.has(item.id) ? <span className="done"><CheckIcon className="ph" weight="bold" /></span> : item.id === lesson.id ? <PlayIcon className="ph" weight="fill" /> : itemIndex + 1}</span>
<span className="t">{item.title}</span>
<span className="r num">{lessonDuration(item)}</span>
</Link>
</li>
))}
</ol>
)}
{tab === 'materiais' && (
screen.materials.length + screen.courseLevel.length === 0 ? <p className="empty">Esta aula não tem materiais.</p> : (
<>
{screen.materials.map((attachment) => <MaterialRow key={attachment.id} attachment={attachment} action={action} />)}
{screen.courseLevel.length > 0 && <>
{screen.materials.length > 0 && <h3 className="muted" style={{ fontSize: 13, fontWeight: 500, margin: '20px 0 4px' }}>Do curso</h3>}
{screen.courseLevel.map((attachment) => <MaterialRow key={attachment.id} attachment={attachment} action={action} />)}
</>}
</>
)
)}
{tab === 'discussao' && (
<>
<form className="composer" onSubmit={screen.postComment}>
<textarea rows={2} value={screen.draft} onChange={(event) => screen.setDraft(event.target.value)} placeholder="Pergunte ou compartilhe um resultado" aria-label="Escrever comentário" />
<button className="btn" type="submit" disabled={!screen.draft.trim() || screen.posting}>Publicar</button>
</form>
{comments.length === 0 ? <p className="empty">Nenhuma pergunta ainda. Seja o primeiro a perguntar.</p> : comments.map((comment) => <CommentItem key={comment.id} comment={comment} lessonNumber={comment.lessonId && comment.lessonId !== lesson.id ? lessonNumber(comment) : undefined} />)}
</>
)}
</div>
</div>
<aside className="side">
<Link className="box" to={paths.course(course.id)}>
<h3>{course.title}</h3>
<span className="prog" style={{ display: 'block', margin: '0 0 8px' }}><i style={{ width: `${pct}%` }} /></span>
<p className="small num" style={{ fontSize: 13 }}>{progress.doneCount} de {course.lessons.length} aulas concluídas</p>
</Link>
{lesson.description && <div className="box"><h3>Sobre esta aula</h3><p className="small" style={{ whiteSpace: 'pre-line' }}>{lesson.description}</p></div>}
</aside>
</div>
</main>
);
};