Files
compor-academy/pages/LessonPage.tsx
Cauê Faleiros 50905eefd7
All checks were successful
CI / Validate frontend and API (push) Successful in 3m5s
CI / Build and publish Docker images (push) Successful in 1m42s
feat: add 2FA, secure cookies and publishing tools
2026-11-06 10:29:37 -03:00

242 lines
15 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, getLessonNote, incrementViews, saveComment, saveLessonNote, 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 { MaterialButton, MaterialRow, attachmentIcon, 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';
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 [note, setNote] = useState('');
const [noteSaving, setNoteSaving] = useState(false);
const advanceTimer = useRef<number>();
const trackedView = useRef<string>('');
useEffect(() => {
if (!user || !lesson) { setNote(''); return; }
let cancelled = false;
getLessonNote(lesson.id)
.then((data) => { if (!cancelled) setNote(data.body); })
.catch(() => { if (!cancelled) setNote(''); });
return () => { cancelled = true; };
}, [lesson?.id, user?.id]);
const saveNote = async () => {
if (!lesson) return;
setNoteSaving(true);
try {
const saved = await saveLessonNote(lesson.id, note);
setNote(saved.body);
showToast('Anotação salva.', 'success');
} catch {
showToast('Não foi possível salvar a anotação.', 'error');
} finally {
setNoteSaving(false);
}
};
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, note, setNote, noteSaving, saveNote };
};
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>
<section className="m-group"><h2>Anotações</h2><div className="m-list"><label className="m-field col"><span>Suas anotações desta aula</span><textarea rows={4} value={screen.note} onChange={(event) => screen.setNote(event.target.value)} placeholder="Escreva aqui…" /></label></div><button className="link" type="button" style={{ marginTop: 10 }} onClick={() => void screen.saveNote()} disabled={screen.noteSaving}>{screen.noteSaving ? 'Salvando…' : 'Salvar anotação'}</button></section>
</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>}
<div className="box"><h3>Anotações</h3><div className="field"><textarea rows={4} value={screen.note} onChange={(event) => screen.setNote(event.target.value)} placeholder="Suas anotações desta aula…" aria-label="Anotações da aula" /></div><button className="btn sec" type="button" onClick={() => void screen.saveNote()} disabled={screen.noteSaving}>{screen.noteSaving ? 'Salvando…' : 'Salvar anotação'}</button></div>
</aside>
</div>
</main>
);
};