feat: finalize academy redesign and production readiness
All checks were successful
CI / Validate frontend and API (push) Successful in 2m22s
CI / Build and publish Docker images (push) Successful in 1m6s

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:
Cauê Faleiros
2026-11-05 15:06:53 -03:00
parent 95a4bd4ac7
commit 21085e887d
99 changed files with 10749 additions and 3935 deletions

View File

@@ -23,5 +23,5 @@ export const AccessTokenPage: React.FC<{ mode: 'invite' | 'reset' }> = ({ mode }
} catch { setError('Este link é inválido, expirou ou não pôde ser usado.'); }
finally { setSaving(false); }
};
return <main className="min-h-screen pt-32 px-6 flex justify-center"><form noValidate onSubmit={submit} className="w-full max-w-md rounded-2xl border border-white/10 bg-zinc-950 p-7 space-y-4"><h1 className="text-2xl font-bold">{mode === 'invite' ? 'Criar seu acesso' : 'Redefinir senha'}</h1>{mode === 'invite' && <input value={name} onChange={(event) => setName(event.target.value)} placeholder="Seu nome" className="w-full rounded-xl bg-zinc-900 p-3" />}<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} placeholder="Nova senha (mínimo 8 caracteres)" className="w-full rounded-xl bg-zinc-900 p-3" />{error && <p className="text-sm text-red-400">{error}</p>}<button disabled={!token || saving} className="w-full rounded-xl bg-orange-500 p-3 font-semibold">{saving ? 'Salvando...' : mode === 'invite' ? 'Criar conta' : 'Redefinir senha'}</button></form></main>;
return <main className="wrap page enter"><div className="auth"><h1>{mode === 'invite' ? 'Criar seu acesso' : 'Redefinir senha'}</h1><p>{mode === 'invite' ? 'Defina seu nome e uma senha para começar.' : 'Escolha uma nova senha para sua conta.'}</p><form noValidate onSubmit={submit}>{mode === 'invite' && <div className="field"><label htmlFor="access-name">Nome</label><input id="access-name" value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" required /></div>}<div className="field"><label htmlFor="access-password">Nova senha</label><input id="access-password" type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete="new-password" required /><small>Pelo menos 8 caracteres.</small></div>{error && <p className="formmsg bad" role="alert">{error}</p>}<button type="submit" disabled={!token || saving} className="btn">{saving ? 'Salvando…' : mode === 'invite' ? 'Criar conta' : 'Redefinir senha'}</button></form></div></main>;
};

82
pages/AuthPage.tsx Normal file
View File

@@ -0,0 +1,82 @@
import React, { useState } from 'react';
import { Link, Navigate, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { UserRole } from '../types';
import { paths } from '../lib/routes';
export const homeFor = (role: UserRole) => (role === 'superadmin' ? paths.admin : role === 'professor' ? paths.manage : paths.explore);
interface AuthPageProps {
mode: 'signin' | 'signup';
}
export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
const isRegistering = mode === 'signup';
const { user, login, register } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const lead = (location.state as { message?: string } | null)?.message;
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [error, setError] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
if (user && !isSubmitting) return <Navigate to={homeFor(user.role)} replace />;
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
setError('');
if (!email.trim() || !/^\S+@\S+\.\S+$/.test(email)) {
setError('Informe um e-mail válido.');
return;
}
if (isRegistering && name.trim().length < 2) {
setError('Informe seu nome.');
return;
}
if (password.length < 8) {
setError('A senha deve ter pelo menos 8 caracteres.');
return;
}
setIsSubmitting(true);
const signedInUser = isRegistering ? await register(name, email, password) : await login(email, password);
if (!signedInUser) {
setIsSubmitting(false);
setError(isRegistering
? 'Não foi possível criar sua conta. Use um e-mail válido e uma senha com pelo menos 8 caracteres.'
: 'Credenciais inválidas. Verifique seu e-mail e senha.');
return;
}
navigate(homeFor(signedInUser.role), { replace: true });
};
return (
<main className="wrap page auth-page enter">
<div className="auth">
<h1>{isRegistering ? 'Criar conta' : 'Entrar'}</h1>
<p>{lead || (isRegistering ? 'Gratuita. Dá acesso a todos os cursos e materiais.' : 'Use o e-mail da sua conta Compor.')}</p>
<form noValidate onSubmit={handleSubmit}>
{isRegistering && (
<div className="field"><label htmlFor="auth-name">Nome</label><input id="auth-name" value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" required /></div>
)}
<div className="field"><label htmlFor="auth-email">E-mail</label><input id="auth-email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} autoComplete="email" autoCapitalize="none" required /></div>
<div className="field">
<label htmlFor="auth-password">Senha</label>
<input id="auth-password" type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete={isRegistering ? 'new-password' : 'current-password'} required />
{isRegistering && <small>Pelo menos 8 caracteres.</small>}
</div>
{error && <p className="formmsg bad" role="alert">{error}</p>}
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Aguarde…' : isRegistering ? 'Criar conta' : 'Entrar'}</button>
</form>
<p className="alt">
{isRegistering
? <>Já tem conta? <Link className="link" to={paths.signIn}>Entrar</Link></>
: <>Não tem conta? <Link className="link" to={paths.signUp}>Criar conta</Link></>}
</p>
</div>
</main>
);
};

61
pages/CommunityPage.tsx Normal file
View File

@@ -0,0 +1,61 @@
import React, { useEffect, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { CaretRightIcon, PlusIcon } from '@phosphor-icons/react';
import { Comment, Course } from '../types';
import { getCommunityComments } from '../services/db';
import { useCatalog } from '../context/CatalogContext';
import { useAuth } from '../context/AuthContext';
import { Avatar } from '../components/ui/Avatar';
import { ChatMockIcon, PlusMockIcon, TeacherMockIcon } from '../components/ui/MockupIcons';
import { paths } from '../lib/routes';
import { useIsMobile } from '../hooks/useMediaQuery';
type Thread = { comment: Comment; course: Course };
const lessonNumberFor = (comment: Comment, course: Course) => {
if (!comment.lessonId) return 0;
return course.lessons.findIndex((lesson) => lesson.id === comment.lessonId) + 1;
};
export const CommunityPage: React.FC = () => {
const { courses, professors } = useCatalog();
const { user } = useAuth();
const location = useLocation();
const isMobile = useIsMobile();
const [threads, setThreads] = useState<Thread[]>([]);
const [view, setView] = useState<'discussoes' | 'professores'>(() => new URLSearchParams(location.search).get('tab') === 'professores' ? 'professores' : 'discussoes');
const [filter, setFilter] = useState<'todas' | 'abertas' | 'professor'>('todas');
useEffect(() => {
const courseById = new Map(courses.map((course) => [course.id, course]));
let cancelled = false;
getCommunityComments(100).then((comments) => {
if (cancelled) return;
setThreads(comments.flatMap((comment) => {
const course = courseById.get(comment.courseId);
return course ? [{ comment, course }] : [];
}));
}).catch(() => { if (!cancelled) setThreads([]); });
return () => { cancelled = true; };
}, [courses]);
useEffect(() => { if (new URLSearchParams(location.search).get('tab') === 'professores') setView('professores'); }, [location.search]);
const visible = threads.filter(({ comment }) => filter === 'todas' || (filter === 'abertas' ? !comment.reply : Boolean(comment.reply)));
if (isMobile) return <main className="m-page m-gut enter"><header className="m-large"><h1>Comunidade</h1>{user && view === 'discussoes' && <Link className="m-icb" to={courses[0] ? paths.course(courses[0].id) : paths.explore} aria-label="Nova pergunta"><PlusIcon className="ph" /></Link>}</header>
<div className="m-seg" role="tablist"><button type="button" role="tab" aria-selected={view === 'discussoes'} onClick={() => setView('discussoes')}>Discussões</button><button type="button" role="tab" aria-selected={view === 'professores'} onClick={() => setView('professores')}>Professores</button></div>
{view === 'professores' ? <section className="m-group"><div className="m-list">{professors.map((professor) => <Link className="m-row" key={professor.id} to={paths.professor(professor.id)}><Avatar name={professor.name} src={professor.avatarImageUrl} size="sm" /><span className="m-rt"><b>{professor.name}</b><small>{professor.headline ? `${professor.headline} · ` : ''}{professor.courses.length} {professor.courses.length === 1 ? 'curso' : 'cursos'}</small></span><CaretRightIcon className="m-chev" /></Link>)}</div></section> : <><div className="m-chips" role="group" aria-label="Filtrar discussões">{[['todas', 'Todas'], ['abertas', 'Sem resposta'], ['professor', 'Com professor']].map(([key, label]) => <button key={key} type="button" aria-pressed={filter === key} onClick={() => setFilter(key as typeof filter)}>{label}</button>)}</div><section className="m-group"><div className="m-list multi">{visible.map(({ comment, course }) => <Link className="m-row" key={comment.id} to={comment.lessonId ? paths.lesson(course.id, comment.lessonId) : paths.course(course.id)}><Avatar name={comment.user} size="sm" /><span className="m-rt"><b>{comment.text}</b><small>{comment.user} · {course.title} · {comment.date}</small></span>{comment.reply && <span className="m-chev" aria-label="Professor respondeu"><TeacherMockIcon className="ph" /></span>}</Link>)}</div>{!visible.length && <p className="m-empty">Nenhuma discussão por aqui ainda.</p>}</section></>}
</main>;
return <main className="wrap page enter">
<header className="ptitle"><div><h1>Discussões</h1><p>Perguntas e resultados dos alunos, organizados por aula.</p></div>{user ? <Link className="btn" to={courses[0] ? paths.course(courses[0].id) : paths.explore}><PlusMockIcon className="ph" /> Nova pergunta</Link> : <Link className="btn sec" to={paths.signIn}>Entrar para participar</Link>}</header>
<div className="seg" role="group" aria-label="Filtrar discussões" style={{ marginBottom: 20 }}>
{([['todas', 'Todas'], ['abertas', 'Sem resposta'], ['professor', 'Respondidas por professor']] as const).map(([key, label]) => <button key={key} type="button" aria-pressed={filter === key} onClick={() => setFilter(key)}>{label}</button>)}
</div>
<div className="list">{visible.map(({ comment, course }) => {
const lessonNumber = lessonNumberFor(comment, course);
return <Link className="row discussion-row" key={comment.id} to={comment.lessonId ? paths.lesson(course.id, comment.lessonId) : paths.course(course.id)}>
<Avatar name={comment.user} size="sm" />
<span className="t">{comment.text}<small>{[comment.user, `${course.title}${lessonNumber ? `, aula ${lessonNumber}` : ''}`, comment.date].join(' · ')}</small></span>
<span className="r">{comment.reply && <span className="ic-prof" title="Professor respondeu" aria-label="Professor respondeu"><TeacherMockIcon className="ph" /></span>}<span className="ic-cnt" aria-label={`${comment.reply ? 1 : 0} respostas`}><ChatMockIcon className="ph" /> {comment.reply ? 1 : 0}</span></span>
</Link>;
})}</div>
{!visible.length && <p className="empty">Nenhuma discussão por aqui ainda.</p>}
</main>;
};

161
pages/CoursePage.tsx Normal file
View File

@@ -0,0 +1,161 @@
import React from 'react';
import { Link, Navigate, useParams } from 'react-router-dom';
import { BookmarkSimpleIcon, CaretRightIcon, CheckIcon, CircleNotchIcon, PlayIcon } from '@phosphor-icons/react';
import { Attachment, Course } from '../types';
import { useCourse, useLessonProgress } from '../hooks/useCourse';
import { useAuth } from '../context/AuthContext';
import { useCatalog } from '../context/CatalogContext';
import { ArtImage, Cover, courseFraming, useCoverImage } from '../components/catalog/Artwork';
import { MaterialRow, useMaterialAction } from '../components/course/Materials';
import { Avatar } from '../components/ui/Avatar';
import { courseMeta, lessonDuration, plural } from '../lib/format';
import { paths } from '../lib/routes';
import { useSavedCourses } from '../hooks/useSavedCourses';
import { useIsMobile } from '../hooks/useMediaQuery';
import { MaterialButton, attachmentIcon } from '../components/course/Materials';
import { useState } from 'react';
export type CourseMaterial = { attachment: Attachment; detail: string; lessonIndex?: number };
export const courseMaterials = (course: Course): CourseMaterial[] => [
...(course.attachments || []).map((attachment) => ({ attachment, detail: 'Material do curso' })),
...course.lessons.flatMap((lesson, index) => (lesson.attachments || []).map((attachment) => ({ attachment, detail: `Aula ${index + 1}`, lessonIndex: index }))),
];
export const signUpState = { message: 'Crie uma conta gratuita para assistir a esta aula.' };
const PlayerPreview: React.FC<{ course: Course; to: string }> = ({ course, to }) => {
const image = useCoverImage(course.thumbnail);
const first = course.lessons[0];
return (
<Link className="player" to={to} state={to === paths.signUp ? signUpState : undefined} aria-label={first ? `Assistir aula 1: ${first.title}` : 'Assistir'}>
{image.show && <ArtImage source={course.thumbnail} framing={courseFraming(course)} onMissing={image.onMissing} />}
<div className="pl"><span className="playbtn"><PlayIcon className="ph" weight="fill" /></span></div>
{first && <div className="ctl num"><span>Aula 1 · {first.title}</span><span style={{ flex: 1 }} /><span>{lessonDuration(first)}</span></div>}
</Link>
);
};
export const CoursePage: React.FC = () => {
const { courseId } = useParams<{ courseId: string }>();
const { course, isLoading, missing } = useCourse(courseId);
const { user } = useAuth();
const { paths: trails } = useCatalog();
const progress = useLessonProgress(course);
const action = useMaterialAction();
const saved = useSavedCourses();
const isMobile = useIsMobile();
const [mobileTab, setMobileTab] = useState<'aulas' | 'materiais' | 'sobre'>('aulas');
if (isLoading) return <main className="wrap page"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
if (missing || !course) return <main className="wrap page"><p className="empty">Este curso não está disponível.</p></main>;
const trail = trails.find((item) => item.courses.some((entry) => entry.id === course.id));
const materials = courseMaterials(course);
const next = progress.next;
const watchTo = (lessonId?: string) => (user && lessonId ? paths.lesson(course.id, lessonId) : paths.signUp);
const started = progress.doneCount > 0;
if (isMobile) return <main className="m-page has-cta enter">
<div className="m-gut">
<Cover course={course} progress={user ? Math.round(progress.doneCount / Math.max(course.lessons.length, 1) * 100) : undefined} className="m-cover" />
<header className="m-title"><h1>{course.title}</h1><p className="num">{[course.instructor, courseMeta(course)].filter(Boolean).join(' · ')}</p></header>
{user && progress.doneCount > 0 && <div className="m-progress"><span className="prog"><i style={{ width: `${Math.round(progress.doneCount / Math.max(course.lessons.length, 1) * 100)}%` }} /></span><span>{progress.doneCount} de {course.lessons.length} aulas</span></div>}
<div className="m-seg" role="tablist">{([['aulas', 'Aulas'], ['materiais', 'Materiais'], ['sobre', 'Sobre']] as const).map(([key, label]) => <button type="button" role="tab" key={key} aria-selected={mobileTab === key} onClick={() => setMobileTab(key)}>{label}</button>)}</div>
<div className="m-pane">
{mobileTab === 'aulas' && <section className="m-group"><div className="m-list">{course.lessons.map((lesson, index) => <Link className="m-row" key={lesson.id} to={watchTo(lesson.id)} state={user ? undefined : signUpState}><span className="m-n num">{progress.completed.has(lesson.id) ? <CheckIcon className="ph" /> : index + 1}</span><span className="m-rt"><b>{lesson.title}</b><small>{lessonDuration(lesson)}</small></span><CaretRightIcon className="m-chev" /></Link>)}</div></section>}
{mobileTab === 'materiais' && <section className="m-group"><div className="m-list">{materials.map((item) => <div className="m-row" key={item.attachment.id}><span className="m-ic">{attachmentIcon(item.attachment.type)}</span><span className="m-rt"><b>{item.attachment.name}</b><small>{item.detail} · {item.attachment.size}</small></span><MaterialButton attachment={item.attachment} action={action} label={false} className="m-icb" /></div>)}</div>{!materials.length && <p className="m-empty">Este curso não tem materiais para baixar.</p>}</section>}
{mobileTab === 'sobre' && <><p className="m-body">{course.description}</p>{course.instructorId && <section className="m-group"><h2>Professor</h2><div className="m-list"><Link className="m-row" to={paths.professor(course.instructorId)}><Avatar name={course.instructor || 'Professor'} size="sm" /><span className="m-rt"><b>{course.instructor}</b></span><CaretRightIcon className="m-chev" /></Link></div></section>}{trail && <section className="m-group"><h2>Trilha</h2><div className="m-list"><Link className="m-row" to={paths.trail(trail.id)}><span className="m-rt"><b>{trail.title}</b></span><CaretRightIcon className="m-chev" /></Link></div></section>}</>}
</div>
</div>
<div className="m-cta">{user && <button type="button" className="btn sec m-half save-icon" onClick={() => saved.toggle(course.id)} aria-label={saved.isSaved(course.id) ? 'Remover dos salvos' : 'Salvar curso'} aria-pressed={saved.isSaved(course.id)}><BookmarkSimpleIcon className="ph" weight={saved.isSaved(course.id) ? 'fill' : 'regular'} /></button>}<Link className="btn m-big" to={user && next ? paths.lesson(course.id, next.id) : paths.signUp} state={user ? undefined : signUpState}>{user && started ? `Continuar aula ${progress.nextIndex + 1}` : user ? 'Assistir' : 'Criar conta para assistir'}</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.search}?area=${encodeURIComponent(course.category)}`}>{course.category}</Link><CaretRightIcon className="ph" weight="bold" />
<span>{course.title}</span>
</div>
<section className="chead">
<div>
<h1>{course.title}</h1>
{course.description && <p className="d">{course.description}</p>}
<p className="meta num">{[course.instructor, courseMeta(course)].filter(Boolean).join(' · ')}</p>
<div className="acts">
{user ? (
next && <Link className="btn lg" to={paths.lesson(course.id, next.id)}><PlayIcon className="ph" weight="fill" /> {started ? `Continuar aula ${progress.nextIndex + 1}` : 'Assistir'}</Link>
) : (
<>
<Link className="btn lg" to={paths.signUp} state={signUpState}>Criar conta para assistir</Link>
<Link className="btn lg sec" to={paths.signIn}>Entrar</Link>
</>
)}
{user && <button className="btn lg sec" type="button" onClick={() => saved.toggle(course.id)} aria-pressed={saved.isSaved(course.id)}><BookmarkSimpleIcon className="ph" weight={saved.isSaved(course.id) ? 'fill' : 'regular'} /> {saved.isSaved(course.id) ? 'Salvo' : 'Salvar'}</button>}
</div>
</div>
{course.lessons.length > 0 ? <PlayerPreview course={course} to={watchTo(course.lessons[0]?.id)} /> : <Cover course={course} variant="big" />}
</section>
<div className="split">
<div>
<section className="shelf" style={{ marginTop: 0 }}>
<header><h2>Aulas</h2><span className="count num">{courseMeta(course)}</span></header>
{course.lessons.length === 0 ? <p className="empty">As aulas deste curso ainda estão sendo preparadas.</p> : (
<ol className="list">
{course.lessons.map((lesson, index) => (
<li key={lesson.id}>
<Link className="row" to={watchTo(lesson.id)} state={user ? undefined : signUpState}>
<span className="i num">{progress.completed.has(lesson.id) ? <span className="done" aria-label="Concluída"><CheckIcon className="ph" weight="bold" /></span> : index + 1}</span>
<span className="t">{lesson.title}</span>
<span className="r num">{lessonDuration(lesson)}</span>
</Link>
</li>
))}
</ol>
)}
</section>
</div>
<aside className="side">
{course.instructorId && (
<Link className="box person" to={paths.professor(course.instructorId)} style={{ display: 'flex' }}>
<Avatar name={course.instructor || 'Professor'} />
<span>{course.instructor}<small>Professor</small></span>
</Link>
)}
{trail && (
<Link className="box" to={paths.trail(trail.id)}>
<h3 style={{ marginBottom: 4 }}>Faz parte da trilha</h3>
<span className="link">{trail.title} <CaretRightIcon className="ph" weight="bold" /></span>
</Link>
)}
<div className="box">
<h3>Materiais</h3>
{materials.length ? materials.map((item) => <MaterialRow key={item.attachment.id} attachment={item.attachment} detail={item.detail} action={action} compact />) : <p className="small">Este curso não tem materiais para baixar.</p>}
</div>
{user && course.lessons.length > 0 && (
<div className="box">
<h3>Seu progresso</h3>
<span className="prog" style={{ display: 'block', margin: '0 0 10px' }}><i style={{ width: `${Math.round((progress.doneCount / course.lessons.length) * 100)}%` }} /></span>
<p className="small num">{progress.doneCount} de {plural(course.lessons.length, 'aula', 'aulas')}</p>
</div>
)}
</aside>
</div>
</main>
);
};
/** Opens the learner's next unfinished lesson. */
export const ContinueCourse: React.FC = () => {
const { courseId } = useParams<{ courseId: string }>();
const { course, isLoading, missing } = useCourse(courseId);
const { user, isLoading: authLoading } = useAuth();
const progress = useLessonProgress(course);
if (authLoading || isLoading || (course && !progress.loaded)) return <main className="wrap page"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
if (missing || !course) return <Navigate to={paths.explore} replace />;
if (!user) return <Navigate to={paths.signUp} state={signUpState} replace />;
if (!progress.next) return <Navigate to={paths.course(course.id)} replace />;
return <Navigate to={paths.lesson(course.id, progress.next.id)} replace />;
};

51
pages/DownloadsPage.tsx Normal file
View File

@@ -0,0 +1,51 @@
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { CircleNotchIcon } from '@phosphor-icons/react';
import { useAuth } from '../context/AuthContext';
import { attachmentIcon, attachmentLabel, useMaterialAction } from '../components/course/Materials';
import { DownloadHistoryEntry, getDownloadHistory } from '../services/db';
import { DownloadMockIcon } from '../components/ui/MockupIcons';
import { useIsMobile } from '../hooks/useMediaQuery';
import { paths } from '../lib/routes';
const months = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'];
const downloadedLabel = (value: string) => {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '';
const today = new Date();
const day = new Date(date.getFullYear(), date.getMonth(), date.getDate());
const current = new Date(today.getFullYear(), today.getMonth(), today.getDate());
const days = Math.round((current.getTime() - day.getTime()) / 86_400_000);
if (days <= 0) return 'hoje';
if (days === 1) return 'ontem';
return `${date.getDate()} ${months[date.getMonth()]}`;
};
export const DownloadsPage: React.FC = () => {
const { user } = useAuth();
const action = useMaterialAction();
const isMobile = useIsMobile();
const [entries, setEntries] = useState<DownloadHistoryEntry[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
if (!user) { setEntries([]); setLoading(false); return; }
setLoading(true);
getDownloadHistory()
.then((history) => { if (!cancelled) setEntries(history); })
.catch(() => { if (!cancelled) setEntries([]); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [user?.id]);
if (isMobile) return <main className="m-page m-gut enter">
<header className="m-large"><h1>Meus downloads</h1></header>
{loading ? <p className="m-empty">Carregando…</p> : entries.length ? <section className="m-group"><div className="m-list">{entries.map(({ attachment, courseTitle, downloadedAt }) => <div className="m-row" key={attachment.id}><span className="m-ic">{attachmentIcon(attachment.type)}</span><span className="m-rt"><b>{attachment.name}</b><small>{courseTitle} · baixado {downloadedLabel(downloadedAt)}</small></span><button className="m-icb" type="button" onClick={() => void action.open(attachment)} aria-label={`Baixar ${attachment.name} novamente`} disabled={action.busyId === attachment.id}><DownloadMockIcon className="ph" /></button></div>)}</div></section> : <p className="m-empty">Seus downloads aparecerão aqui.</p>}
</main>;
return <main className="wrap page enter">
<header className="ptitle"><div><h1>Meus downloads</h1><p>Arquivos que você já baixou das aulas.</p></div><Link className="btn sec" to={paths.library}>Ver biblioteca</Link></header>
{loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : entries.length ? <div className="list">{entries.map(({ attachment, courseTitle, lessonNumber, downloadedAt }) => <div className="file" key={attachment.id} style={{ padding: '14px 4px' }}><span className="ic">{attachmentIcon(attachment.type)}</span><span>{attachment.name}<small className="num">{[courseTitle, lessonNumber ? `aula ${lessonNumber}` : '', attachmentLabel(attachment.type), attachment.size, `baixado ${downloadedLabel(downloadedAt)}`].filter(Boolean).join(' · ')}</small></span><button type="button" className="btn sec" onClick={() => void action.open(attachment)} disabled={action.busyId === attachment.id}><DownloadMockIcon className="ph" /> {attachment.type === 'link' ? 'Abrir de novo' : 'Baixar de novo'}</button></div>)}</div> : <div className="empty"><DownloadMockIcon className="ph" style={{ fontSize: 24, marginBottom: 8 }} /><p>Seus downloads aparecerão aqui.</p><Link className="link" to={paths.library}>Explorar a biblioteca</Link></div>}
</main>;
};

48
pages/ExplorePage.tsx Normal file
View File

@@ -0,0 +1,48 @@
import React from 'react';
import { CircleNotchIcon } from '@phosphor-icons/react';
import { Hero } from '../components/catalog/Hero';
import { Shelf } from '../components/catalog/Shelf';
import { ContinueCard, CourseCard, TrailPoster } from '../components/catalog/Artwork';
import { useCatalog } from '../context/CatalogContext';
import { useAuth } from '../context/AuthContext';
import { paths } from '../lib/routes';
import { useIsMobile } from '../hooks/useMediaQuery';
export const ExplorePage: React.FC = () => {
const { courses, paths: trails, areas, isLoading, failed } = useCatalog();
const { user } = useAuth();
const isMobile = useIsMobile();
const going = user ? courses.filter((course) => (course.progress || 0) > 0 && (course.progress || 0) < 100) : [];
const mostWatched = courses.length > 0 && (
<Shelf title="Mais assistidos" to={paths.search}>
{[...courses].sort((a, b) => (b.views || 0) - (a.views || 0)).slice(0, 10).map((course) => <CourseCard key={course.id} course={course} />)}
</Shelf>
);
const trailsShelf = trails.length > 0 && (
<Shelf title="Trilhas" to={paths.trails} kind="tall">
{trails.map((trail) => <TrailPoster key={trail.id} path={trail} />)}
</Shelf>
);
return (
<>
<Hero />
<main className="wrap page has-hero enter">
{isLoading && <div className="loading"><CircleNotchIcon className="ph spin" /></div>}
{!isLoading && failed && <p className="empty">Não foi possível carregar os cursos. Tente novamente em instantes.</p>}
{!isLoading && !failed && courses.length === 0 && <p className="empty">Ainda não há cursos publicados.</p>}
{going.length > 0 && (
<Shelf title="Continue assistindo" to={paths.learning} kind="wide">
{going.map((course) => <ContinueCard key={course.id} course={course} />)}
</Shelf>
)}
{isMobile ? <>{trailsShelf}{mostWatched}</> : <>{mostWatched}{trailsShelf}</>}
{areas.map((area) => (
<Shelf key={area} title={area} to={`${paths.search}?area=${encodeURIComponent(area)}`}>
{courses.filter((course) => course.category === area).map((course) => <CourseCard key={course.id} course={course} />)}
</Shelf>
))}
</main>
</>
);
};

View File

@@ -1,34 +1,38 @@
import React, { useEffect, useState } from 'react';
import { ExternalLink, Globe2, Instagram, Linkedin, Loader2, UserRound, Youtube } from 'lucide-react';
import { useParams } from 'react-router-dom';
import { Link, useParams } from 'react-router-dom';
import { ArrowSquareOutIcon, CaretRightIcon, CircleNotchIcon, GlobeIcon, InstagramLogoIcon, LinkedinLogoIcon, YoutubeLogoIcon } from '@phosphor-icons/react';
import { Course } from '../types';
import { getPublicProfile, InstructorProfileData } from '../services/db';
import { CourseCoverImage } from '../components/CourseCoverImage';
import { CourseCard } from '../components/CourseCard';
import { CourseCard, Thumb } from '../components/catalog/Artwork';
import { Avatar } from '../components/ui/Avatar';
import { paths } from '../lib/routes';
import { useIsMobile } from '../hooks/useMediaQuery';
const networks = [
{ key: 'websiteUrl', label: 'Site', icon: Globe2 },
{ key: 'linkedinUrl', label: 'LinkedIn', icon: Linkedin },
{ key: 'instagramUrl', label: 'Instagram', icon: Instagram },
{ key: 'youtubeUrl', label: 'YouTube', icon: Youtube },
{ key: 'websiteUrl', label: 'Site', icon: GlobeIcon },
{ key: 'linkedinUrl', label: 'LinkedIn', icon: LinkedinLogoIcon },
{ key: 'instagramUrl', label: 'Instagram', icon: InstagramLogoIcon },
{ key: 'youtubeUrl', label: 'YouTube', icon: YoutubeLogoIcon },
] as const;
export const InstructorProfile: React.FC<{ onPlay: (course: Course) => void }> = ({ onPlay }) => {
export const InstructorProfile: React.FC<{ onPlay: (course: Course) => void }> = () => {
const { instructorId, profileId } = useParams<{ instructorId?: string; profileId?: string }>();
const publicProfileId = instructorId || profileId;
const id = instructorId || profileId;
const isMobile = useIsMobile();
const [profile, setProfile] = useState<InstructorProfileData | null>(null);
const [state, setState] = useState<'loading' | 'ready' | 'missing'>('loading');
useEffect(() => {
if (!publicProfileId) return;
setState('loading');
getPublicProfile(publicProfileId).then((data) => { setProfile(data); setState('ready'); }).catch(() => setState('missing'));
}, [publicProfileId]);
if (state === 'loading') return <main className="min-h-[65vh] pt-32 flex items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-orange-400" /></main>;
if (state === 'missing' || !profile) return <main className="mx-auto flex min-h-[65vh] max-w-5xl items-center px-6 pt-24"><div><p className="text-sm font-semibold uppercase tracking-widest text-orange-400">Perfil indisponível</p><h1 className="mt-3 text-3xl font-bold">Este perfil não está público.</h1></div></main>;
const [loading, setLoading] = useState(true);
useEffect(() => { if (!id) return; setLoading(true); getPublicProfile(id).then(setProfile).catch(() => setProfile(null)).finally(() => setLoading(false)); }, [id]);
if (loading) return <main className="wrap page"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
if (!profile) return <main className="wrap page"><p className="empty">Este perfil não está público.</p></main>;
const isInstructor = profile.role === 'instructor' || profile.role === 'admin';
return <main className="min-h-screen pb-20 pt-20"><section className="border-b border-white/10 bg-gradient-to-br from-orange-500/15 via-zinc-950 to-black"><div className="mx-auto grid max-w-6xl gap-7 px-6 py-12 sm:px-8 md:grid-cols-[auto_1fr] md:items-center md:py-16"><div className="h-32 w-32 overflow-hidden rounded-full border-4 border-zinc-900 bg-zinc-800 shadow-2xl shadow-black/50">{profile.avatarImageUrl ? <CourseCoverImage source={profile.avatarImageUrl} alt={`Foto de ${profile.name}`} className="h-full w-full object-cover" /> : <div className="flex h-full w-full items-center justify-center bg-orange-500/15"><UserRound className="h-14 w-14 text-orange-300" /></div>}</div><div><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-400">{isInstructor ? 'Instrutor' : 'Aluno'}</p><h1 className="mt-2 text-3xl font-bold tracking-tight text-white sm:text-5xl">{profile.name}</h1>{profile.headline && <p className="mt-3 text-lg text-gray-300">{profile.headline}</p>}<div className="mt-5 flex flex-wrap gap-2">{networks.map(({ key, label, icon: Icon }) => { const url = profile[key]; return url ? <a key={key} href={url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-2 rounded-xl border border-white/15 bg-white/5 px-3.5 py-2 text-sm font-semibold text-white transition hover:border-orange-500/40 hover:bg-orange-500/10"><Icon className="h-4 w-4 text-orange-400" />{label}<ExternalLink className="h-3 w-3 text-gray-500" /></a> : null; })}</div></div></div></section><div className={`mx-auto max-w-6xl gap-12 px-6 py-12 sm:px-8 ${isInstructor ? 'grid lg:grid-cols-[minmax(0,0.7fr)_minmax(0,1.3fr)]' : 'max-w-3xl'}`}><aside><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-400">Sobre</p><h2 className="mt-2 text-2xl font-bold text-white">Conheça {profile.name.split(' ')[0]}</h2><p className="mt-5 whitespace-pre-line text-sm leading-7 text-gray-300">{profile.bio || `${isInstructor ? 'Este instrutor' : 'Este aluno'} ainda não adicionou uma apresentação.`}</p></aside>{isInstructor && <section><div className="mb-6 flex items-end justify-between gap-4"><div><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-400">Conteúdo</p><h2 className="mt-2 text-2xl font-bold text-white">Cursos publicados</h2></div><span className="rounded-full bg-white/5 px-3 py-1.5 text-xs font-semibold text-gray-300">{profile.courses.length} {profile.courses.length === 1 ? 'curso' : 'cursos'}</span></div>{profile.courses.length ? <div className="grid gap-7 sm:grid-cols-2">{profile.courses.map((course) => <CourseCard key={course.id} course={course} variant="landscape" onClick={onPlay} />)}</div> : <div className="rounded-2xl border border-dashed border-white/15 p-8 text-center text-sm text-gray-500">Nenhum curso publicado ainda.</div>}</section>}</div></main>;
if (isMobile) return <main className="m-page m-gut enter"><header className="m-person"><Avatar name={profile.name} src={profile.avatarImageUrl || undefined} size="xl" /><h1>{profile.name}</h1>{profile.headline && <p>{profile.headline}</p>}{profile.bio && <p className="m-body">{profile.bio}</p>}</header>
{isInstructor && <section className="m-group"><h2>{profile.courses.length} {profile.courses.length === 1 ? 'curso' : 'cursos'}</h2><div className="m-list">{profile.courses.map((course) => <Link className="m-row" key={course.id} to={paths.course(course.id)}><Thumb course={course} /><span className="m-rt"><b>{course.title}</b><small>{course.lessons.length} aulas · {course.duration}</small></span><CaretRightIcon className="m-chev" /></Link>)}</div></section>}
</main>;
return <main className="wrap page enter"><div className="crumb"><Link to={paths.professors}>Professores</Link><CaretRightIcon className="ph" /><span>{profile.name}</span></div>
<header className="profile-head">{profile.avatarImageUrl ? <span className="av xl"><CourseCoverImage source={profile.avatarImageUrl} alt={`Foto de ${profile.name}`} /></span> : <Avatar name={profile.name} size="xl" />}<div><h1>{profile.name}</h1>{profile.headline && <p>{profile.headline}</p>}</div></header>
{profile.bio && <p className="profile-bio">{profile.bio}</p>}
<div className="profile-links">{networks.map(({ key, label, icon: Icon }) => { const url = profile[key]; return url ? <a className="btn sec" key={key} href={url} target="_blank" rel="noreferrer"><Icon className="ph" />{label}<ArrowSquareOutIcon className="ph" /></a> : null; })}</div>
{isInstructor && <section className="shelf"><header><h2>Cursos</h2><span className="count num">{profile.courses.length}</span></header>{profile.courses.length ? <div className="grid">{profile.courses.map((course) => <CourseCard key={course.id} course={course} />)}</div> : <p className="empty">Nenhum curso publicado ainda.</p>}</section>}
</main>;
};

215
pages/LessonPage.tsx Normal file
View File

@@ -0,0 +1,215 @@
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>
);
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,84 +1,45 @@
import React, { useEffect, useMemo, useState } from 'react';
import { ArrowLeft, BookOpen, Download, ExternalLink, Filter, FolderOpen, LayoutGrid, List, Loader2, Play, Search, X } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { Attachment, AttachmentType, Course } from '../types';
import { getCourses } from '../services/db';
import { downloadCourseAsset } from '../services/api';
import { getAttachmentBadge, getAttachmentIcon } from '../components/MaterialCard';
import { useToast } from '../context/ToastContext';
import React, { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { Attachment, Course } from '../types';
import { useCatalog } from '../context/CatalogContext';
import { useAuth } from '../context/AuthContext';
import { attachmentIcon, attachmentLabel, useMaterialAction } from '../components/course/Materials';
import { DownloadMockIcon, SearchMockIcon } from '../components/ui/MockupIcons';
import { useIsMobile } from '../hooks/useMediaQuery';
import { paths } from '../lib/routes';
interface MaterialsPageProps { onPlayCourse: (course: Course) => void; }
type Material = { id: string; attachment: Attachment; course: Course; lessonTitle?: string; };
type SortOption = 'recent' | 'name' | 'type';
type Material = { attachment: Attachment; course: Course; lessonTitle?: string; lessonNumber?: number };
const filterTypes: Array<{ value: 'all' | AttachmentType; label: string }> = [
{ value: 'all', label: 'Todos os formatos' }, { value: 'pdf', label: 'PDF' }, { value: 'spreadsheet', label: 'Planilha' }, { value: 'doc', label: 'Documento' }, { value: 'zip', label: 'Arquivo compactado' }, { value: 'image', label: 'Imagem' }, { value: 'link', label: 'Link' },
];
const formatDate = (date?: string) => date ? new Intl.DateTimeFormat('pt-BR', { dateStyle: 'medium' }).format(new Date(date)) : 'Data não informada';
const materialDate = (material: Material) => {
const value = material.attachment.createdAt ? new Date(material.attachment.createdAt).getTime() : 0;
return Number.isNaN(value) ? 0 : value;
};
export const MaterialsPage: React.FC<MaterialsPageProps> = ({ onPlayCourse }) => {
const navigate = useNavigate();
const { showDownloadToast, showToast } = useToast();
const [courses, setCourses] = useState<Course[]>([]);
const [isLoading, setIsLoading] = useState(true);
export const MaterialsPage: React.FC<{ onPlayCourse: (course: Course) => void }> = () => {
const { courses, isLoading } = useCatalog();
const { user } = useAuth();
const isMobile = useIsMobile();
const action = useMaterialAction();
const [query, setQuery] = useState('');
const [selectedTrail, setSelectedTrail] = useState('all');
const [selectedCourse, setSelectedCourse] = useState('all');
const [selectedType, setSelectedType] = useState<'all' | AttachmentType>('all');
const [sort, setSort] = useState<SortOption>('recent');
const [view, setView] = useState<'grid' | 'list'>('grid');
useEffect(() => {
window.scrollTo(0, 0);
getCourses().then(setCourses).catch(() => showToast('Não foi possível carregar os materiais.', 'error')).finally(() => setIsLoading(false));
}, [showToast]);
const materials = useMemo<Material[]>(() => courses.flatMap((course) => [
...(course.attachments || []).map((attachment) => ({ id: `course-${course.id}-${attachment.id}`, attachment, course })),
...course.lessons.flatMap((lesson) => (lesson.attachments || []).map((attachment) => ({ id: `lesson-${course.id}-${lesson.id}-${attachment.id}`, attachment, course, lessonTitle: lesson.title }))),
...(course.attachments || []).map((attachment) => ({ attachment, course })),
...course.lessons.flatMap((lesson, index) => (lesson.attachments || []).map((attachment) => ({ attachment, course, lessonTitle: lesson.title, lessonNumber: index + 1 }))),
]), [courses]);
const trails = useMemo<string[]>(() => Array.from(new Set<string>(courses.map((course) => course.category))).filter(Boolean).sort((a, b) => a.localeCompare(b, 'pt-BR')), [courses]);
const courseOptions = useMemo(() => courses.filter((course) => selectedTrail === 'all' || course.category === selectedTrail).sort((a, b) => a.title.localeCompare(b.title, 'pt-BR')), [courses, selectedTrail]);
const filteredMaterials = useMemo(() => materials.filter((material) => {
const normalized = query.trim().toLocaleLowerCase('pt-BR');
const searchMatches = !normalized || [material.attachment.name, material.attachment.description, material.course.title, material.course.category, material.lessonTitle].some((value) => value?.toLocaleLowerCase('pt-BR').includes(normalized));
return searchMatches && (selectedTrail === 'all' || material.course.category === selectedTrail) && (selectedCourse === 'all' || material.course.id === selectedCourse) && (selectedType === 'all' || material.attachment.type === selectedType);
}).sort((left, right) => {
if (sort === 'name') return left.attachment.name.localeCompare(right.attachment.name, 'pt-BR');
if (sort === 'type') return left.attachment.type.localeCompare(right.attachment.type, 'pt-BR') || left.attachment.name.localeCompare(right.attachment.name, 'pt-BR');
return materialDate(right) - materialDate(left) || left.attachment.name.localeCompare(right.attachment.name, 'pt-BR');
}), [materials, query, selectedTrail, selectedCourse, selectedType, sort]);
const hasFilters = Boolean(query) || selectedTrail !== 'all' || selectedCourse !== 'all' || selectedType !== 'all';
const clearFilters = () => { setQuery(''); setSelectedTrail('all'); setSelectedCourse('all'); setSelectedType('all'); };
const openMaterial = async (material: Material) => {
if (material.attachment.type === 'link') {
showToast(`Abrindo “${material.attachment.name}”.`, 'info');
return;
}
try {
await downloadCourseAsset(material.attachment.id, material.attachment.name);
showDownloadToast(material.attachment.name, material.attachment.size);
} catch (error) {
showToast(error instanceof Error ? error.message : 'Não foi possível baixar este material.', 'error');
}
};
const q = query.trim().toLocaleLowerCase('pt-BR');
const visible = materials.filter((material) => !q || [material.attachment.name, material.course.title, material.lessonTitle].some((value) => value?.toLocaleLowerCase('pt-BR').includes(q)));
const open = (material: Material) => { void action.open(material.attachment); };
return <main className="min-h-screen bg-black pb-20 pt-24 text-white"><div className="mx-auto max-w-7xl px-5 sm:px-8">
<header className="border-b border-white/10 pb-7"><button onClick={() => navigate('/')} className="mb-5 inline-flex items-center gap-1.5 text-sm text-gray-400 transition hover:text-orange-300"><ArrowLeft className="h-4 w-4" /> Início</button><div><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-400">Central de recursos</p><h1 className="mt-2 text-3xl font-bold tracking-tight sm:text-4xl">Biblioteca de materiais</h1><p className="mt-3 max-w-2xl text-sm leading-6 text-gray-400">Materiais disponibilizados pelos instrutores nos cursos e aulas da plataforma.</p></div></header>
if (isMobile) {
const courseIds = Array.from(new Set(visible.map((material) => material.course.id)));
return <main className="m-page m-gut enter">
<header className="m-large"><h1>Biblioteca</h1></header>
<p className="m-lead">Planilhas, guias e modelos das aulas.</p>
{courseIds.map((courseId) => {
const group = visible.filter((material) => material.course.id === courseId);
return <section className="m-group" key={courseId}><h2>{group[0].course.title}</h2><div className="m-list">{group.map((material) => <div className="m-row" key={`${material.course.id}-${material.lessonNumber || 0}-${material.attachment.id}`}><span className="m-ic">{attachmentIcon(material.attachment.type)}</span><span className="m-rt"><b>{material.attachment.name}</b><small>{[material.lessonNumber ? `Aula ${material.lessonNumber}` : '', attachmentLabel(material.attachment.type), material.attachment.size].filter(Boolean).join(' · ')}</small></span>{user ? <button className="m-icb" type="button" onClick={() => open(material)} aria-label={`Baixar ${material.attachment.name}`}><DownloadMockIcon className="ph" /></button> : null}</div>)}</div></section>;
})}
{!visible.length && !isLoading && <p className="m-empty">Nenhum material encontrado.</p>}
{!user && <div className="m-cta"><Link className="btn m-big" to={paths.signIn}>Entrar para baixar</Link></div>}
</main>;
}
<section className="mt-6 rounded-2xl border border-white/10 bg-zinc-950/80 p-4 sm:p-5"><div className="grid gap-3 lg:grid-cols-[minmax(0,1.5fr)_repeat(3,minmax(0,.7fr))]"><label className="relative block"><Search className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500" /><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Buscar por material, curso ou aula" className="w-full rounded-xl border border-white/10 bg-zinc-900 py-3 pl-10 pr-10 text-sm text-white outline-none transition focus:border-orange-500/70 focus:ring-2 focus:ring-orange-500/15" />{query && <button onClick={() => setQuery('')} className="absolute right-3 top-1/2 -translate-y-1/2 rounded p-1 text-gray-400 hover:text-white" aria-label="Limpar busca"><X className="h-4 w-4" /></button>}</label><FilterSelect value={selectedTrail} onChange={(value) => { setSelectedTrail(value); setSelectedCourse('all'); }} label="Trilha" options={[{ value: 'all', label: 'Todas as trilhas' }, ...trails.map((trail) => ({ value: trail, label: trail }))]} /><FilterSelect value={selectedCourse} onChange={setSelectedCourse} label="Curso" options={[{ value: 'all', label: 'Todos os cursos' }, ...courseOptions.map((course) => ({ value: course.id, label: course.title }))]} /><FilterSelect value={selectedType} onChange={(value) => setSelectedType(value as 'all' | AttachmentType)} label="Formato" options={filterTypes} /></div><div className="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-white/5 pt-4"><div className="flex items-center gap-2 text-xs text-gray-500"><Filter className="h-3.5 w-3.5 text-orange-400" /> {filteredMaterials.length} {filteredMaterials.length === 1 ? 'resultado' : 'resultados'}</div><div className="flex items-center gap-2">{hasFilters && <button onClick={clearFilters} className="rounded-lg px-3 py-2 text-xs font-semibold text-gray-300 transition hover:bg-white/10 hover:text-white">Limpar filtros</button>}<label className="sr-only" htmlFor="materials-sort">Ordenar por</label><select id="materials-sort" value={sort} onChange={(event) => setSort(event.target.value as SortOption)} className="rounded-lg border border-white/10 bg-zinc-900 px-3 py-2 text-xs font-semibold text-white outline-none"><option value="recent">Mais recentes</option><option value="name">Nome</option><option value="type">Formato</option></select><div className="flex rounded-lg border border-white/10 bg-zinc-900 p-1"><button onClick={() => setView('grid')} aria-label="Visualização em grade" className={`rounded p-1.5 ${view === 'grid' ? 'bg-orange-500 text-white' : 'text-gray-400 hover:text-white'}`}><LayoutGrid className="h-4 w-4" /></button><button onClick={() => setView('list')} aria-label="Visualização em lista" className={`rounded p-1.5 ${view === 'list' ? 'bg-orange-500 text-white' : 'text-gray-400 hover:text-white'}`}><List className="h-4 w-4" /></button></div></div></div></section>
<section className="mt-6">{isLoading ? <div className="flex min-h-72 items-center justify-center"><Loader2 className="h-7 w-7 animate-spin text-orange-400" /></div> : filteredMaterials.length === 0 ? <EmptyState hasMaterials={materials.length > 0} onClear={clearFilters} /> : view === 'grid' ? <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">{filteredMaterials.map((material) => <MaterialGridCard key={material.id} material={material} onOpen={openMaterial} onCourse={onPlayCourse} />)}</div> : <div className="overflow-hidden rounded-2xl border border-white/10 bg-zinc-950/80"><div className="hidden grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)_10rem_8rem] gap-4 border-b border-white/10 px-5 py-3 text-xs font-semibold uppercase tracking-wider text-gray-500 md:grid"><span>Material</span><span>Curso e aula</span><span>Adicionado em</span><span className="text-right">Ações</span></div>{filteredMaterials.map((material) => <MaterialListRow key={material.id} material={material} onOpen={openMaterial} onCourse={onPlayCourse} />)}</div>}</section>
</div></main>;
return <main className="wrap page enter">
<header className="ptitle"><div><h1>Materiais</h1><p>Planilhas, guias e modelos das aulas.</p></div><label className="search"><SearchMockIcon className="ph" /><input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Buscar materiais" aria-label="Buscar materiais" /></label></header>
{isLoading ? <p className="empty">Carregando materiais…</p> : visible.length ? <div className="tablewrap"><table className="t-mat"><thead><tr><th>Arquivo</th><th>Curso</th><th>Aula</th><th>Tamanho</th><th></th></tr></thead><tbody>{visible.map((material) => <tr key={`${material.course.id}-${material.lessonNumber || 0}-${material.attachment.id}`}><td><span className="file-name"><span className="ic">{attachmentIcon(material.attachment.type)}</span><span>{material.attachment.name}<small>{attachmentLabel(material.attachment.type)}</small></span></span></td><td><Link className="link" to={paths.course(material.course.id)}>{material.course.title}</Link></td><td className="num">{material.lessonNumber || '—'}</td><td className="num">{material.attachment.size || '—'}</td><td className="right">{user ? <button type="button" className="btn sec" onClick={() => open(material)} disabled={action.busyId === material.attachment.id}><DownloadMockIcon className="ph" /> {material.attachment.type === 'link' ? 'Abrir' : 'Baixar'}</button> : <Link className="btn sec" to={paths.signIn}>Entrar para baixar</Link>}</td></tr>)}</tbody></table></div> : <p className="empty">Nenhum material encontrado.</p>}
</main>;
};
const FilterSelect: React.FC<{ value: string; label: string; options: Array<{ value: string; label: string }>; onChange: (value: string) => void }> = ({ value, label, options, onChange }) => <label className="block"><span className="sr-only">{label}</span><select value={value} onChange={(event) => onChange(event.target.value)} className="w-full rounded-xl border border-white/10 bg-zinc-900 px-3 py-3 text-sm text-white outline-none transition focus:border-orange-500/70"><option value="" disabled>{label}</option>{options.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</select></label>;
const EmptyState: React.FC<{ hasMaterials: boolean; onClear: () => void }> = ({ hasMaterials, onClear }) => <div className="flex min-h-80 flex-col items-center justify-center rounded-2xl border border-dashed border-white/15 bg-zinc-950/50 px-6 text-center"><div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-orange-500/10"><FolderOpen className="h-7 w-7 text-orange-400" /></div><h2 className="mt-5 text-lg font-bold text-white">{hasMaterials ? 'Nenhum material corresponde aos filtros' : 'A biblioteca ainda não tem materiais'}</h2><p className="mt-2 max-w-md text-sm leading-6 text-gray-500">{hasMaterials ? 'Tente alterar a busca ou os filtros selecionados.' : 'Quando um instrutor adicionar materiais a um curso ou aula, eles aparecerão aqui.'}</p>{hasMaterials && <button onClick={onClear} className="mt-5 rounded-xl bg-orange-500 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-orange-600">Limpar filtros</button>}</div>;
const MaterialMeta: React.FC<{ material: Material }> = ({ material }) => <div className="min-w-0"><p className="truncate text-xs font-semibold text-orange-300">{material.course.category}</p><p className="mt-1 flex items-center gap-1.5 truncate text-xs text-gray-400"><BookOpen className="h-3.5 w-3.5 shrink-0" />{material.course.title}</p>{material.lessonTitle && <p className="mt-1 truncate text-xs text-gray-500">Aula: {material.lessonTitle}</p>}</div>;
const MaterialGridCard: React.FC<{ material: Material; onOpen: (material: Material) => void | Promise<void>; onCourse: (course: Course) => void }> = ({ material, onOpen, onCourse }) => { const { attachment } = material; const badge = getAttachmentBadge(attachment.type); const isLink = attachment.type === 'link'; return <article className="flex min-h-64 flex-col rounded-2xl border border-white/10 bg-zinc-950/80 p-5 transition hover:border-orange-500/35 hover:bg-zinc-900/80"><div className="flex items-start justify-between gap-4"><div className="rounded-xl bg-white/5 p-3">{getAttachmentIcon(attachment.type)}</div><span className={`rounded-full px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider ${badge.bg}`}>{badge.label}</span></div><div className="mt-5"><h2 className="line-clamp-2 text-base font-bold text-white">{attachment.name}</h2>{attachment.description && <p className="mt-2 line-clamp-2 text-sm leading-5 text-gray-400">{attachment.description}</p>}</div><div className="mt-5 border-t border-white/10 pt-4"><MaterialMeta material={material} /><div className="mt-4 flex items-center justify-between gap-3 text-xs text-gray-500"><span>{attachment.size || 'Tamanho não informado'}</span><span>{formatDate(attachment.createdAt)}</span></div></div><div className="mt-5 flex items-center gap-2"><button onClick={() => onCourse(material.course)} className="inline-flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-2 text-xs font-semibold text-gray-300 transition hover:bg-white/10 hover:text-white"><Play className="h-3.5 w-3.5 text-orange-400" /> Abrir curso</button>{isLink ? <a href={attachment.url} target="_blank" rel="noreferrer" onClick={() => void onOpen(material)} className="ml-auto inline-flex items-center gap-1.5 rounded-lg bg-orange-500 px-3 py-2 text-xs font-semibold text-white transition hover:bg-orange-600"><ExternalLink className="h-3.5 w-3.5" />Abrir</a> : <button type="button" onClick={() => void onOpen(material)} className="ml-auto inline-flex items-center gap-1.5 rounded-lg bg-orange-500 px-3 py-2 text-xs font-semibold text-white transition hover:bg-orange-600"><Download className="h-3.5 w-3.5" />Baixar</button>}</div></article>; };
const MaterialListRow: React.FC<{ material: Material; onOpen: (material: Material) => void | Promise<void>; onCourse: (course: Course) => void }> = ({ material, onOpen, onCourse }) => { const { attachment } = material; const isLink = attachment.type === 'link'; return <article className="grid gap-4 border-b border-white/5 px-5 py-4 last:border-0 md:grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)_10rem_8rem] md:items-center"><div className="flex min-w-0 items-center gap-3"><div className="shrink-0">{getAttachmentIcon(attachment.type)}</div><div className="min-w-0"><p className="truncate text-sm font-semibold text-white">{attachment.name}</p><p className="mt-1 text-xs text-gray-500">{attachment.size || 'Tamanho não informado'}</p></div></div><MaterialMeta material={material} /><p className="text-xs text-gray-500">{formatDate(attachment.createdAt)}</p><div className="flex items-center gap-2 md:justify-end"><button onClick={() => onCourse(material.course)} className="rounded-lg p-2 text-gray-400 transition hover:bg-white/10 hover:text-orange-300" title="Abrir curso"><Play className="h-4 w-4" /></button>{isLink ? <a href={attachment.url} target="_blank" rel="noreferrer" onClick={() => void onOpen(material)} className="inline-flex items-center gap-1.5 rounded-lg bg-orange-500 px-3 py-2 text-xs font-semibold text-white transition hover:bg-orange-600"><ExternalLink className="h-3.5 w-3.5" />Abrir</a> : <button type="button" onClick={() => void onOpen(material)} className="inline-flex items-center gap-1.5 rounded-lg bg-orange-500 px-3 py-2 text-xs font-semibold text-white transition hover:bg-orange-600"><Download className="h-3.5 w-3.5" />Baixar</button>}</div></article>; };

View File

@@ -1,40 +1,60 @@
import React, { useEffect, useState } from 'react';
import { BookOpenCheck, Loader2, PlayCircle } from 'lucide-react';
import { Link } from 'react-router-dom';
import { CircleNotchIcon } from '@phosphor-icons/react';
import { Course } from '../types';
import { getMyLearningCourses } from '../services/db';
import { CourseCoverImage } from '../components/CourseCoverImage';
import { CourseCard, Cover, Thumb } from '../components/catalog/Artwork';
import { PlayMockIcon } from '../components/ui/MockupIcons';
import { useSavedCourses } from '../hooks/useSavedCourses';
import { useCatalog } from '../context/CatalogContext';
import { useIsMobile } from '../hooks/useMediaQuery';
import { paths } from '../lib/routes';
export const MyLearning: React.FC<{ onPlay: (course: Course) => void }> = ({ onPlay }) => {
export const MyLearning: React.FC<{ onPlay: (course: Course) => void }> = () => {
const [courses, setCourses] = useState<Course[]>([]);
const [loading, setLoading] = useState(true);
const [tab, setTab] = useState<'andamento' | 'concluidos' | 'salvos'>('andamento');
const saved = useSavedCourses();
const isMobile = useIsMobile();
const { courses: catalogCourses } = useCatalog();
useEffect(() => { getMyLearningCourses().then(setCourses).catch(() => setCourses([])).finally(() => setLoading(false)); }, []);
const going = courses.filter((course) => (course.progress || 0) < 100);
const done = courses.filter((course) => (course.progress || 0) >= 100);
const savedCourses = catalogCourses.filter((course) => saved.isSaved(course.id));
const first = going[0];
const completedCount = first ? Math.round(((first.progress || 0) / 100) * first.lessons.length) : 0;
const nextLesson = first?.lessons[Math.min(completedCount, Math.max(first.lessons.length - 1, 0))];
useEffect(() => {
getMyLearningCourses().then(setCourses).catch(() => setCourses([])).finally(() => setLoading(false));
}, []);
if (loading) return <main className="wrap page enter"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
return (
<main className="min-h-screen max-w-[1440px] mx-auto pt-28 pb-20 px-6 md:px-12">
<div className="mb-10">
<div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-orange-400 mb-3"><BookOpenCheck className="w-4 h-4" /> Minha área</div>
<h1 className="text-3xl md:text-4xl font-bold text-white">Continue aprendendo</h1>
<p className="mt-2 text-gray-400">Retome suas aulas exatamente de onde parou.</p>
if (isMobile) {
const chosen = tab === 'andamento' ? going : tab === 'concluidos' ? done : savedCourses;
return <main className="m-page m-gut enter"><header className="m-large"><h1>Minha aprendizagem</h1></header>
<div className="m-seg" role="tablist">{[['andamento', 'Em andamento'], ['concluidos', 'Concluídos'], ['salvos', 'Salvos']].map(([key, label]) => <button type="button" role="tab" key={key} aria-selected={tab === key} onClick={() => setTab(key as typeof tab)}>{label}</button>)}</div>
{chosen.length ? <section className="m-group"><div className="m-list">{chosen.map((course) => {
const progress = course.progress || 0;
const lessonIndex = Math.min(Math.round((progress / 100) * course.lessons.length), Math.max(course.lessons.length - 1, 0));
const linkedLesson = course.lessons[lessonIndex];
const to = tab === 'andamento' && linkedLesson ? paths.lesson(course.id, linkedLesson.id) : paths.course(course.id);
const sub = tab === 'andamento' ? `Aula ${lessonIndex + 1} de ${course.lessons.length}` : tab === 'concluidos' ? 'Concluído' : `${course.lessons.length} aulas`;
return <Link className="m-row" key={course.id} to={to}><Thumb course={course} className="m-th" /><span className="m-rt"><b>{course.title}</b><small>{sub}</small></span>{tab === 'andamento' && <span className="m-mini"><span className="m-bar"><i style={{ width: `${progress}%` }} /></span></span>}</Link>;
})}</div></section> : <p className="m-empty">Nada por aqui ainda.</p>}
</main>;
}
return <main className="wrap page enter">
<div className="ptitle"><div><h1>Minha aprendizagem</h1></div></div>
{first && <Link className="box contbox" to={paths.continueCourse(first.id)}>
<Cover course={first} variant="mini" />
<div>
<h2>{nextLesson?.title || first.title}</h2>
<p className="num" style={{ fontSize: 14, color: 'var(--fg-2)', marginTop: 4 }}>Continuar de onde parou · {first.title}, aula {Math.min(completedCount + 1, first.lessons.length)} de {first.lessons.length}</p>
<div className="prog"><i style={{ width: `${Math.round(first.progress || 0)}%` }} /></div>
</div>
{loading ? <div className="h-64 flex justify-center items-center"><Loader2 className="w-8 h-8 animate-spin text-orange-400" /></div> : courses.length === 0 ? (
<div className="rounded-2xl border border-white/10 bg-zinc-950/80 py-16 px-6 text-center">
<BookOpenCheck className="w-10 h-10 text-orange-400 mx-auto mb-4" />
<h2 className="font-bold text-white text-lg">Você ainda não iniciou nenhum curso</h2>
<p className="mt-2 text-sm text-gray-400">Escolha uma aula na página de cursos para começar.</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
{courses.map((course) => (
<button key={course.id} onClick={() => onPlay(course)} className="group overflow-hidden rounded-2xl border border-white/10 bg-zinc-950/80 text-left hover:border-orange-500/50 transition-colors">
<div className="aspect-video relative overflow-hidden bg-zinc-900"><CourseCoverImage source={course.thumbnail} alt="" className="h-full w-full object-cover opacity-75 transition-opacity group-hover:opacity-100" style={{ transform: `scale(${course.coverImageZoom || 1})`, objectPosition: `${course.coverImagePositionX ?? 50}% ${course.coverImagePositionY ?? 50}%` }} /><div className="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent" /><span className="absolute left-4 bottom-4 inline-flex items-center gap-2 rounded-full bg-orange-500 px-3 py-2 text-xs font-bold text-white"><PlayCircle className="w-4 h-4" /> Continuar</span></div>
<div className="p-5"><p className="text-xs text-orange-400 font-semibold uppercase tracking-wider">{course.category}</p><h2 className="mt-2 font-bold text-white">{course.title}</h2><div className="mt-4 h-1.5 overflow-hidden rounded-full bg-white/10"><div className="h-full rounded-full bg-orange-500" style={{ width: `${course.progress || 0}%` }} /></div><p className="mt-2 text-xs text-gray-400">{course.progress || 0}% concluído</p></div>
</button>
))}
</div>
)}
</main>
);
<span className="btn"><PlayMockIcon className="ph" /> Continuar</span>
</Link>}
<section className="shelf"><header><h2>Em andamento</h2></header><div className="grid">{going.map((course) => <CourseCard key={course.id} course={course} />)}</div></section>
<section className="shelf"><header><h2>Concluídos</h2></header><div className="grid">{done.map((course) => <CourseCard key={course.id} course={course} />)}</div></section>
<section className="shelf"><header><h2>Salvos</h2></header><div className="grid">{savedCourses.map((course) => <CourseCard key={course.id} course={course} />)}</div></section>
</main>;
};

13
pages/ProfessorsPage.tsx Normal file
View File

@@ -0,0 +1,13 @@
import React from 'react';
import { Link, Navigate } from 'react-router-dom';
import { Avatar } from '../components/ui/Avatar';
import { useCatalog } from '../context/CatalogContext';
import { paths } from '../lib/routes';
import { useIsMobile } from '../hooks/useMediaQuery';
export const ProfessorsPage: React.FC = () => {
const { professors } = useCatalog();
const isMobile = useIsMobile();
if (isMobile) return <Navigate to="/comunidade?tab=professores" replace />;
return <main className="wrap page enter"><header className="ptitle"><div><h1>Professores</h1><p>Quem ensina na Compor.</p></div></header><div className="pcards">{professors.map((professor) => <Link className="pcard" key={professor.id} to={paths.professor(professor.id)}><Avatar name={professor.name} src={professor.avatarImageUrl} size="xl" /><b>{professor.name}</b>{professor.headline && <small>{professor.headline}</small>}<small className="num">{professor.courses.length} {professor.courses.length === 1 ? 'curso' : 'cursos'}</small></Link>)}</div></main>;
};

View File

@@ -1,135 +1,58 @@
import React, { useEffect, useRef, useState } from 'react';
import { Camera, ExternalLink, Globe2, Instagram, Linkedin, Loader2, Save, UserRound, Youtube } from 'lucide-react';
import { Link } from 'react-router-dom';
import { ArrowSquareOutIcon, CameraIcon, CircleNotchIcon, GlobeIcon, InstagramLogoIcon, LinkedinLogoIcon, YoutubeLogoIcon } from '@phosphor-icons/react';
import { useAuth } from '../context/AuthContext';
import { Profile, ProfileInput, instructorApi, profileApi } from '../services/api';
import { CourseCoverImage } from '../components/CourseCoverImage';
import { Switch } from '../components/ui/Switch';
import { useToast } from '../context/ToastContext';
import { useNavigate } from 'react-router-dom';
import { paths } from '../lib/routes';
const emptyProfile = (user: { id: string; email: string; name: string; role: string }): Profile => ({
id: user.id,
email: user.email,
name: user.name,
id: user.id, email: user.email, name: user.name,
role: user.role === 'superadmin' ? 'admin' : user.role === 'professor' ? 'instructor' : 'student',
avatarImageUrl: null,
headline: '',
bio: '',
websiteUrl: null,
linkedinUrl: null,
instagramUrl: null,
youtubeUrl: null,
isPublic: true,
avatarImageUrl: null, headline: '', bio: '', websiteUrl: null, linkedinUrl: null, instagramUrl: null, youtubeUrl: null, isPublic: true,
});
const inputClass = 'w-full rounded-xl border border-white/10 bg-zinc-900 px-4 py-3 text-sm text-white outline-none transition focus:border-orange-500/70 focus:ring-2 focus:ring-orange-500/15';
export const ProfilePage: React.FC = () => {
const { user, updateCurrentUser } = useAuth();
const { showToast } = useToast();
const navigate = useNavigate();
const fileInput = useRef<HTMLInputElement>(null);
const [profile, setProfile] = useState<Profile | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [isUploading, setIsUploading] = useState(false);
useEffect(() => {
if (!user) return;
profileApi.me()
.then((response) => setProfile(response.data))
.catch(() => {
setProfile(emptyProfile(user));
showToast('Não foi possível carregar todos os dados do perfil.', 'error');
})
.finally(() => setIsLoading(false));
profileApi.me().then((response) => setProfile(response.data)).catch(() => { setProfile(emptyProfile(user)); showToast('Não foi possível carregar todos os dados do perfil.', 'error'); }).finally(() => setIsLoading(false));
}, [showToast, user]);
if (isLoading || !profile || !user) {
return <main className="min-h-[65vh] pt-32 flex items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-orange-400" /></main>;
}
if (isLoading || !profile || !user) return <main className="wrap page"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
const update = <K extends keyof Profile>(key: K, value: Profile[K]) => setProfile((current) => current ? { ...current, [key]: value } : current);
const uploadAvatar = async (file?: File) => {
if (!file) return;
if (!file.type.startsWith('image/')) {
showToast('Selecione uma imagem JPG, PNG ou WebP.', 'error');
return;
}
if (!file.type.startsWith('image/')) { showToast('Selecione uma imagem JPG, PNG ou WebP.', 'error'); return; }
setIsUploading(true);
try {
const response = await instructorApi.uploadCover(file);
update('avatarImageUrl', response.data.coverImageUrl);
showToast('Foto enviada. Salve o perfil para publicar a alteração.', 'success');
} catch {
showToast('Não foi possível enviar a foto.', 'error');
} finally {
setIsUploading(false);
}
try { const response = await instructorApi.uploadCover(file); update('avatarImageUrl', response.data.coverImageUrl); showToast('Foto enviada. Salve o perfil para publicar a alteração.', 'success'); }
catch { showToast('Não foi possível enviar a foto.', 'error'); }
finally { setIsUploading(false); }
};
const save = async (event: React.FormEvent) => {
event.preventDefault();
const input: ProfileInput = {
name: profile.name,
avatarImageUrl: profile.avatarImageUrl,
headline: profile.headline,
bio: profile.bio,
websiteUrl: profile.websiteUrl,
linkedinUrl: profile.linkedinUrl,
instagramUrl: profile.instagramUrl,
youtubeUrl: profile.youtubeUrl,
isPublic: profile.isPublic,
};
const input: ProfileInput = { name: profile.name, avatarImageUrl: profile.avatarImageUrl, headline: profile.headline, bio: profile.bio, websiteUrl: profile.websiteUrl, linkedinUrl: profile.linkedinUrl, instagramUrl: profile.instagramUrl, youtubeUrl: profile.youtubeUrl, isPublic: profile.isPublic };
setIsSaving(true);
try {
const response = await profileApi.update(input);
setProfile(response.data);
updateCurrentUser({ id: user.id, email: user.email, name: response.data.name, role: response.data.role });
showToast('Perfil salvo com sucesso.', 'success');
} catch {
showToast('Não foi possível salvar o perfil. Verifique os links informados.', 'error');
} finally {
setIsSaving(false);
}
try { const response = await profileApi.update(input); setProfile(response.data); updateCurrentUser({ id: user.id, email: user.email, name: response.data.name, role: response.data.role }); showToast('Perfil salvo com sucesso.', 'success'); }
catch { showToast('Não foi possível salvar o perfil. Verifique os links informados.', 'error'); }
finally { setIsSaving(false); }
};
return (
<main className="mx-auto min-h-screen w-full max-w-5xl px-5 pb-20 pt-28 sm:px-8">
<div className="mb-8 flex flex-col justify-between gap-5 sm:flex-row sm:items-end">
<div>
<p className="mb-2 text-xs font-bold uppercase tracking-[0.18em] text-orange-400">Sua conta</p>
<h1 className="text-3xl font-bold tracking-tight text-white sm:text-4xl">Meu perfil</h1>
<p className="mt-2 max-w-xl text-sm text-gray-400">Apresente quem você é, compartilhe seus links e escolha a visibilidade do seu perfil.</p>
</div>
{profile.isPublic && <button onClick={() => navigate(`/perfis/${user.id}`)} className="inline-flex items-center justify-center gap-2 rounded-xl border border-white/15 bg-white/5 px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/10"><ExternalLink className="h-4 w-4" /> Ver perfil público</button>}
</div>
<form onSubmit={save} className="overflow-hidden rounded-3xl border border-white/10 bg-zinc-950/80 shadow-2xl shadow-black/30">
<section className="border-b border-white/10 bg-gradient-to-r from-orange-500/15 via-zinc-950 to-zinc-950 p-6 sm:p-8">
<div className="flex flex-col gap-5 sm:flex-row sm:items-center">
<div className="relative h-28 w-28 shrink-0 overflow-hidden rounded-full border-4 border-zinc-950 bg-zinc-900 shadow-xl">
{profile.avatarImageUrl ? <CourseCoverImage source={profile.avatarImageUrl} alt={`Foto de ${profile.name}`} className="h-full w-full object-cover" /> : <div className="flex h-full w-full items-center justify-center bg-orange-500/15"><UserRound className="h-11 w-11 text-orange-300" /></div>}
<button type="button" disabled={isUploading} onClick={() => fileInput.current?.click()} className="absolute inset-x-0 bottom-0 flex h-9 items-center justify-center bg-black/70 text-xs font-semibold text-white transition hover:bg-black/90 disabled:opacity-60">{isUploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <><Camera className="mr-1.5 h-3.5 w-3.5" /> Alterar</>}</button>
</div>
<div><h2 className="text-xl font-bold text-white">{profile.name}</h2><p className="mt-1 text-sm text-gray-400">{user.email}</p><p className="mt-3 text-xs text-orange-200/80">A foto e a apresentação ficam visíveis quando seu perfil estiver público.</p></div>
</div>
<input ref={fileInput} type="file" accept="image/jpeg,image/png,image/webp" className="hidden" onChange={(event) => { void uploadAvatar(event.target.files?.[0]); event.currentTarget.value = ''; }} />
</section>
<div className="grid gap-8 p-6 sm:p-8 lg:grid-cols-[1fr_0.8fr]">
<section className="space-y-5">
<label className="block"><span className="mb-2 block text-sm font-semibold text-white">Nome</span><input value={profile.name} onChange={(event) => update('name', event.target.value)} className={inputClass} maxLength={120} required /></label>
<label className="block"><span className="mb-2 block text-sm font-semibold text-white">Título profissional</span><input value={profile.headline} onChange={(event) => update('headline', event.target.value)} placeholder="Ex.: Especialista em crescimento e mídia paga" className={inputClass} maxLength={180} /></label>
<label className="block"><span className="mb-2 block text-sm font-semibold text-white">Sobre você</span><textarea value={profile.bio} onChange={(event) => update('bio', event.target.value)} placeholder="Conte brevemente sobre você, seus interesses ou sua experiência." className={`${inputClass} min-h-40 resize-y`} maxLength={3000} /></label>
</section>
<section className="rounded-2xl border border-white/10 bg-black/30 p-5 sm:p-6"><div className="mb-5"><h2 className="font-bold text-white">Links e visibilidade</h2><p className="mt-1 text-xs leading-relaxed text-gray-500">Use links completos, começando com https://.</p></div><div className="space-y-4"><UrlField icon={<Globe2 />} label="Site" value={profile.websiteUrl} onChange={(value) => update('websiteUrl', value || null)} placeholder="https://seusite.com" /><UrlField icon={<Linkedin />} label="LinkedIn" value={profile.linkedinUrl} onChange={(value) => update('linkedinUrl', value || null)} placeholder="https://linkedin.com/in/seu-perfil" /><UrlField icon={<Instagram />} label="Instagram" value={profile.instagramUrl} onChange={(value) => update('instagramUrl', value || null)} placeholder="https://instagram.com/seu-perfil" /><UrlField icon={<Youtube />} label="YouTube" value={profile.youtubeUrl} onChange={(value) => update('youtubeUrl', value || null)} placeholder="https://youtube.com/@seu-canal" /></div><label className="mt-6 flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.03] p-4"><input type="checkbox" checked={profile.isPublic} onChange={(event) => update('isPublic', event.target.checked)} className="mt-0.5 h-4 w-4 accent-orange-500" /><span><span className="block text-sm font-semibold text-white">Perfil público</span><span className="mt-1 block text-xs leading-relaxed text-gray-500">Permite que outras pessoas vejam sua apresentação e seus links. Perfis de instrutores também exibem seus cursos publicados.</span></span></label></section>
</div>
<div className="flex justify-end border-t border-white/10 bg-black/20 p-5 sm:px-8"><button disabled={isSaving} className="inline-flex min-w-40 items-center justify-center gap-2 rounded-xl bg-orange-500 px-5 py-3 text-sm font-bold text-white shadow-lg shadow-orange-500/20 transition hover:bg-orange-600 disabled:opacity-60">{isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />} Salvar perfil</button></div>
</form>
</main>
);
return <main className="wrap page enter profile-page">
<header className="ptitle"><div><h1>Conta</h1><p>Seus dados, apresentação e links.</p></div>{profile.isPublic && <Link className="btn sec" to={`/perfis/${user.id}`}><ArrowSquareOutIcon className="ph" /> Ver perfil público</Link>}</header>
<form onSubmit={save} className="profile-form">
<div className="profile-avatar"><span className="av xl">{profile.avatarImageUrl ? <CourseCoverImage source={profile.avatarImageUrl} alt={`Foto de ${profile.name}`} /> : profile.name.slice(0, 2).toUpperCase()}</span><button type="button" className="link" disabled={isUploading} onClick={() => fileInput.current?.click()}><CameraIcon className="ph" /> Trocar foto</button><input ref={fileInput} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={(event) => { void uploadAvatar(event.target.files?.[0]); event.currentTarget.value = ''; }} /></div>
<div className="profile-fields"><section className="form"><h2>Dados pessoais</h2><div className="field"><label htmlFor="profile-name">Nome</label><input id="profile-name" value={profile.name} onChange={(event) => update('name', event.target.value)} maxLength={120} required /></div><div className="field"><label htmlFor="profile-email">E-mail</label><input id="profile-email" value={user.email} disabled /></div><div className="field"><label htmlFor="profile-headline">Título profissional</label><input id="profile-headline" value={profile.headline} onChange={(event) => update('headline', event.target.value)} maxLength={180} /></div><div className="field"><label htmlFor="profile-bio">Sobre você</label><textarea id="profile-bio" value={profile.bio} onChange={(event) => update('bio', event.target.value)} maxLength={3000} /></div></section>
<section className="form"><h2>Links e visibilidade</h2><p className="muted">Use links completos, começando com https://.</p><UrlField icon={<GlobeIcon />} label="Site" value={profile.websiteUrl} onChange={(value) => update('websiteUrl', value || null)} /><UrlField icon={<LinkedinLogoIcon />} label="LinkedIn" value={profile.linkedinUrl} onChange={(value) => update('linkedinUrl', value || null)} /><UrlField icon={<InstagramLogoIcon />} label="Instagram" value={profile.instagramUrl} onChange={(value) => update('instagramUrl', value || null)} /><UrlField icon={<YoutubeLogoIcon />} label="YouTube" value={profile.youtubeUrl} onChange={(value) => update('youtubeUrl', value || null)} /><div className="toggle"><span>Perfil público<small>Permite que outras pessoas vejam sua apresentação e seus cursos.</small></span><Switch checked={profile.isPublic} onChange={(checked) => update('isPublic', checked)} label="Perfil público" /></div></section></div>
<button className="btn lg profile-save" type="submit" disabled={isSaving}>{isSaving ? 'Salvando…' : 'Salvar'}</button>
</form>
</main>;
};
const UrlField: React.FC<{ icon: React.ReactNode; label: string; value: string | null; placeholder: string; onChange: (value: string) => void }> = ({ icon, label, value, placeholder, onChange }) => <label className="block"><span className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-gray-400"><span className="text-orange-400 [&>svg]:h-4 [&>svg]:w-4">{icon}</span>{label}</span><input type="url" value={value || ''} onChange={(event) => onChange(event.target.value)} placeholder={placeholder} className={inputClass} /></label>;
const UrlField: React.FC<{ icon: React.ReactNode; label: string; value: string | null; onChange: (value: string) => void }> = ({ icon, label, value, onChange }) => <div className="field"><label>{icon} {label}<input type="url" value={value || ''} onChange={(event) => onChange(event.target.value)} placeholder="https://" /></label></div>;

74
pages/SearchPage.tsx Normal file
View File

@@ -0,0 +1,74 @@
import React, { useEffect, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { CourseCard, Thumb, TrailPoster } from '../components/catalog/Artwork';
import { Avatar } from '../components/ui/Avatar';
import { SearchMockIcon } from '../components/ui/MockupIcons';
import { useCatalog } from '../context/CatalogContext';
import { searchCatalog, SearchResults } from '../services/db';
import { useIsMobile } from '../hooks/useMediaQuery';
import { paths } from '../lib/routes';
const emptyResults: SearchResults = { courses: [], paths: [], professors: [] };
export const SearchPage: React.FC = () => {
const { courseById, pathTone } = useCatalog();
const isMobile = useIsMobile();
const [params] = useSearchParams();
const [query, setQuery] = useState(params.get('q') || params.get('area') || '');
const [results, setResults] = useState<SearchResults>(emptyResults);
const [isLoading, setIsLoading] = useState(true);
const [failed, setFailed] = useState(false);
const normalized = query.trim().length > 0;
useEffect(() => {
let cancelled = false;
setIsLoading(true);
const timer = window.setTimeout(() => {
searchCatalog(query)
.then((response) => {
if (cancelled) return;
setResults(response);
setFailed(false);
})
.catch(() => {
if (cancelled) return;
setResults(emptyResults);
setFailed(true);
})
.finally(() => { if (!cancelled) setIsLoading(false); });
}, 250);
return () => { cancelled = true; window.clearTimeout(timer); };
}, [query]);
if (isMobile) return <main className="m-page m-gut enter">
<header className="m-large"><h1>Buscar</h1></header>
<label className="m-search"><SearchMockIcon className="ph" /><input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Cursos, trilhas e professores" aria-label="Buscar" autoComplete="off" /></label>
{isLoading ? <p className="m-empty">Carregando…</p> : failed ? <p className="m-empty">Não foi possível buscar agora. Tente novamente.</p> : <>
{results.courses.length > 0 && <section className="m-group"><h2>Cursos</h2><div className="m-list">{results.courses.map((course) => { const listed = courseById(course.id); const shown = listed ? { ...course, progress: listed.progress } : course; return <Link className="m-row" key={course.id} to={paths.course(course.id)}><Thumb course={shown} className="m-th" /><span className="m-rt"><b>{course.title}</b><small>{course.instructor} · {course.lessons.length} aulas</small></span></Link>; })}</div></section>}
{normalized && results.paths.length > 0 && <section className="m-group"><h2>Trilhas</h2><div className="m-list">{results.paths.map((trail) => <Link className="m-row" key={trail.id} to={paths.trail(trail.id)}><span className={`m-part xs tr-${pathTone(trail)}`} aria-hidden="true" /><span className="m-rt"><b>{trail.title}</b><small>{trail.courses.length} cursos</small></span></Link>)}</div></section>}
{normalized && results.professors.length > 0 && <section className="m-group"><h2>Professores</h2><div className="m-list">{results.professors.map((professor) => <Link className="m-row" key={professor.id} to={paths.professor(professor.id)}><Avatar name={professor.name} src={professor.avatarImageUrl} size="sm" /><span className="m-rt"><b>{professor.name}</b>{professor.headline && <small>{professor.headline}</small>}</span></Link>)}</div></section>}
{!results.courses.length && !results.paths.length && !results.professors.length && <p className="m-empty">Nada encontrado para “{query}”.<br />Tente “Meta Ads” ou “CRM”.</p>}
</>}
</main>;
return <main className="wrap page enter">
<div className="ptitle"><div><h1>Buscar</h1></div></div> <label className="search bigsearch"><SearchMockIcon className="ph" /><input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Cursos, trilhas e professores" aria-label="Buscar" autoComplete="off" /></label>
{isLoading ? <p className="empty" style={{ marginTop: 32 }}>Carregando…</p> : failed ? <p className="empty" style={{ marginTop: 32 }}>Não foi possível buscar agora. Tente novamente.</p> : <>
{normalized && results.professors.length > 0 && <section className="shelf">
<div className="rowhead"><h2>Professores</h2></div>
<div className="pcards">{results.professors.map((professor) => <Link className="pcard" to={paths.professor(professor.id)} key={professor.id}><Avatar name={professor.name} src={professor.avatarImageUrl} size="xl" /><b>{professor.name}</b>{professor.headline && <small>{professor.headline}</small>}<span className="num">{professor.courseCount} {professor.courseCount === 1 ? 'curso' : 'cursos'}</span></Link>)}</div>
</section>}
{normalized && results.paths.length > 0 && <section className="shelf">
<div className="rowhead"><h2>Trilhas</h2></div>
<div className="pgrid">{results.paths.map((trail) => <TrailPoster key={trail.id} path={trail} />)}</div>
</section>}
<section className="shelf">
<div className="rowhead"><h2>{normalized ? <>Cursos <span className="num" style={{ color: 'var(--fg-3)', fontWeight: 500 }}>{results.courses.length}</span></> : 'Todos os cursos'}</h2></div>
{results.courses.length ? <div className="grid">{results.courses.map((course) => {
const listed = courseById(course.id);
return <CourseCard key={course.id} course={listed ? { ...course, progress: listed.progress, views: listed.views, lastActivity: listed.lastActivity } : course} />;
})}</div> : <p className="empty">Nenhum curso encontrado. Tente outro termo, como “Meta Ads” ou “CRM”.</p>}
</section>
</>}
</main>;
};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,34 +1,43 @@
import React, { useEffect, useState } from 'react';
import { ArrowLeft, BookOpen, Loader2 } from 'lucide-react';
import { useNavigate, useParams } from 'react-router-dom';
import React from 'react';
import { Link, useParams } from 'react-router-dom';
import { CaretRightIcon, CircleNotchIcon, PlayIcon } from '@phosphor-icons/react';
import { Course } from '../types';
import { getCourses, getLearningPaths, PublicLearningPath } from '../services/db';
import { CourseCoverImage } from '../components/CourseCoverImage';
import { CourseCard } from '../components/CourseCard';
import { Cover, Thumb, pathCourses, pathProgress, Progress } from '../components/catalog/Artwork';
import { Avatar } from '../components/ui/Avatar';
import { useCatalog } from '../context/CatalogContext';
import { useAuth } from '../context/AuthContext';
import { courseMeta, plural, totalDuration } from '../lib/format';
import { paths } from '../lib/routes';
import { useIsMobile } from '../hooks/useMediaQuery';
export const TrailPage: React.FC<{ onPlay: (course: Course) => void }> = ({ onPlay }) => {
export const TrailPage: React.FC<{ onPlay: (course: Course) => void }> = () => {
const { trailId } = useParams<{ trailId: string }>();
const navigate = useNavigate();
const [trail, setTrail] = useState<PublicLearningPath | null>(null);
const [courses, setCourses] = useState<Course[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
if (!trailId) return;
Promise.all([getLearningPaths(), getCourses()])
.then(([paths, availableCourses]) => {
const found = paths.find((item) => item.id === trailId) || null;
setTrail(found);
if (found) {
const byId = new Map(availableCourses.map((course) => [course.id, course]));
setCourses(found.courses.map((course) => byId.get(course.id)).filter((course): course is Course => Boolean(course)));
}
})
.finally(() => setIsLoading(false));
}, [trailId]);
if (isLoading) return <main className="flex min-h-[65vh] items-center justify-center pt-24"><Loader2 className="h-8 w-8 animate-spin text-orange-400" /></main>;
if (!trail) return <main className="mx-auto flex min-h-[65vh] max-w-6xl items-center px-6 pt-24"><div><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-400">Trilha indisponível</p><h1 className="mt-3 text-3xl font-bold text-white">Esta trilha não está publicada.</h1></div></main>;
return <main className="min-h-screen pb-20 pt-20"><section className="relative overflow-hidden border-b border-white/10 bg-zinc-950"><div className="absolute inset-0 opacity-30">{trail.coverImageUrl && <CourseCoverImage source={trail.coverImageUrl} alt="" className="h-full w-full object-cover" style={{ transform: `scale(${trail.coverImageZoom})`, objectPosition: `${trail.coverImagePositionX}% ${trail.coverImagePositionY}%` }} />}</div><div className="absolute inset-0 bg-gradient-to-r from-black via-black/90 to-black/45" /><div className="relative mx-auto max-w-6xl px-6 py-14 sm:px-8 sm:py-20"><button onClick={() => navigate('/')} className="mb-8 inline-flex items-center gap-2 text-sm font-semibold text-gray-300 transition hover:text-orange-300"><ArrowLeft className="h-4 w-4" /> Voltar para cursos</button><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-400">Trilha de cursos</p><h1 className="mt-3 max-w-3xl text-4xl font-bold tracking-tight text-white sm:text-5xl">{trail.title}</h1>{trail.description && <p className="mt-5 max-w-2xl text-base leading-7 text-gray-300">{trail.description}</p>}<div className="mt-7 inline-flex items-center gap-2 rounded-full border border-white/15 bg-black/30 px-4 py-2 text-sm font-semibold text-white"><BookOpen className="h-4 w-4 text-orange-400" />{courses.length} {courses.length === 1 ? 'curso na trilha' : 'cursos na trilha'}</div></div></section><section className="mx-auto max-w-6xl px-6 py-12 sm:px-8"><div className="mb-7"><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-400">Sua sequência</p><h2 className="mt-2 text-2xl font-bold text-white">Cursos da trilha</h2></div>{courses.length ? <div className="grid gap-7 sm:grid-cols-2 lg:grid-cols-3">{courses.map((course, index) => <div key={course.id}><p className="mb-3 text-xs font-bold text-orange-300">{String(index + 1).padStart(2, '0')} · Curso</p><CourseCard course={course} variant="landscape" onClick={onPlay} /></div>)}</div> : <div className="rounded-2xl border border-dashed border-white/15 p-10 text-center text-sm text-gray-500">Nenhum curso publicado nesta trilha.</div>}</section></main>;
const { paths: trails, courseById, pathTone, isLoading } = useCatalog();
const { user } = useAuth();
const isMobile = useIsMobile();
const trail = trails.find((item) => item.id === trailId);
const courses = trail ? pathCourses(trail, courseById) : [];
const progress = pathProgress(courses);
const totalLessons = courses.reduce((sum, course) => sum + course.lessons.length, 0);
const seen = Math.round(totalLessons * progress / 100);
const next = courses.find((course) => (course.progress || 0) < 100) || courses[0];
const teachers = Array.from(new Map(courses.filter((course) => course.instructorId).map((course) => [course.instructorId, { id: course.instructorId!, name: course.instructor || 'Professor' }])).values());
if (isLoading) return <main className="wrap page"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
if (!trail) return <main className="wrap page"><p className="empty">Esta trilha não está disponível.</p></main>;
if (isMobile) return <main className="m-page has-cta m-gut enter">
<header className="m-hero-d"><span className={`m-part sm tr-${pathTone(trail)}`} aria-hidden="true" /><div><small>{courses[0]?.category}</small><h1>{trail.title}</h1><p>{trail.description}</p><p className="m-meta num">{plural(courses.length, 'curso', 'cursos')} · {plural(totalLessons, 'aula', 'aulas')}{totalDuration(courses) ? ` · ${totalDuration(courses)}` : ''}</p></div></header>
{user && seen > 0 && <div className="m-progress"><span className="m-bar"><i style={{ width: `${Math.round(progress)}%` }} /></span><span className="num">{seen} de {totalLessons} aulas</span></div>}
<section className="m-group"><h2>Cursos, em ordem</h2><div className="m-list">{courses.map((course, index) => <Link className="m-row" key={course.id} to={paths.course(course.id)}><span className="m-n num">{index + 1}</span><Thumb course={course} className="thumb" /><span className="m-rt"><b>{course.title}</b><small>{course.instructor} · {plural(course.lessons.length, 'aula', 'aulas')}</small></span><CaretRightIcon className="m-chev" /></Link>)}</div></section>
{next && <div className="m-cta"><Link className="btn m-big" to={user ? paths.continueCourse(next.id) : paths.signUp}>{user ? seen ? 'Continuar trilha' : 'Começar trilha' : 'Criar conta para começar'}</Link></div>}
</main>;
return <main className="wrap page enter">
<div className="crumb"><Link to={paths.trails}>Trilhas</Link><CaretRightIcon className="ph" /><span>{trail.title}</span></div>
<div className="split"><div>
<header className="ptitle"><div><h1>{trail.title}</h1><p>{trail.description}</p><p className="num">{plural(courses.length, 'curso', 'cursos')} · {plural(totalLessons, 'aula', 'aulas')}{totalDuration(courses) ? ` · ${totalDuration(courses)}` : ''}</p></div></header>
<ol className="list">{courses.map((course, index) => <li key={course.id}><Link className="row trail-course" to={paths.course(course.id)}><span className="i num">{index + 1}</span><Cover course={course} variant="mini" /><span className="t">{course.title}<small>{course.instructor} · {courseMeta(course)}</small></span><span className="r num">{course.progress ? `${Math.round(course.progress)}%` : ''}<CaretRightIcon className="ph" /></span></Link></li>)}</ol>
</div><aside className="side"><div className="box"><h3>Seu progresso</h3>{user ? <><Progress value={progress} /><p className="small num">{seen} de {totalLessons} aulas</p></> : <p className="small">Entre para acompanhar seu progresso nesta trilha.</p>}{next && <Link className="btn" style={{ marginTop: 16 }} to={user ? paths.continueCourse(next.id) : paths.signUp}><PlayIcon className="ph" />{seen ? 'Continuar trilha' : 'Começar trilha'}</Link>}</div>
{teachers.length > 0 && <div className="box"><h3>Professores</h3>{teachers.map((teacher) => <Link key={teacher.id} className="person trail-teacher" to={paths.professor(teacher.id)}><Avatar name={teacher.name} size="sm" /><span>{teacher.name}</span></Link>)}</div>}
</aside></div>
{isMobile && next && <div className="m-cta"><Link className="btn m-big" to={user ? paths.continueCourse(next.id) : paths.signUp}>{seen ? 'Continuar trilha' : 'Começar trilha'}</Link></div>}
</main>;
};

11
pages/TrailsPage.tsx Normal file
View File

@@ -0,0 +1,11 @@
import React from 'react';
import { CircleNotchIcon } from '@phosphor-icons/react';
import { TrailPoster } from '../components/catalog/Artwork';
import { useCatalog } from '../context/CatalogContext';
export const TrailsPage: React.FC = () => {
const { paths, isLoading } = useCatalog();
return <main className="wrap page enter"><header className="ptitle"><div><h1>Trilhas</h1><p>Cursos em sequência. Faça na ordem ou escolha um curso solto.</p></div></header>
{isLoading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : paths.length ? <div className="pgrid">{paths.map((path) => <TrailPoster key={path.id} path={path} />)}</div> : <p className="empty">Ainda não há trilhas publicadas.</p>}
</main>;
};

29
pages/YouPage.tsx Normal file
View File

@@ -0,0 +1,29 @@
import React from 'react';
import { Link, Navigate, useNavigate } from 'react-router-dom';
import { BooksIcon, CaretRightIcon, DownloadSimpleIcon, FolderIcon, GearIcon, MoonIcon, SignOutIcon, UserIcon, VideoCameraIcon } from '@phosphor-icons/react';
import { useAuth } from '../context/AuthContext';
import { useTheme } from '../context/ThemeContext';
import { Avatar } from '../components/ui/Avatar';
import { paths } from '../lib/routes';
import { useIsMobile } from '../hooks/useMediaQuery';
type Entry = { label: string; to: string; icon: React.ComponentType<{ className?: string }> };
const Group: React.FC<{ title: string; entries: Entry[] }> = ({ title, entries }) => <section className="m-group"><h2>{title}</h2><div className="m-list">{entries.map(({ label, to, icon: Icon }) => <Link className="m-row" to={to} key={label}><span className="m-ic"><Icon className="ph" /></span><span className="m-rt"><b>{label}</b></span><CaretRightIcon className="m-chev" /></Link>)}</div></section>;
export const YouPage: React.FC = () => {
const { user, logout } = useAuth();
const { theme, toggleTheme } = useTheme();
const navigate = useNavigate();
const isMobile = useIsMobile();
const canTeach = user?.role === 'professor' || user?.role === 'superadmin';
if (!isMobile) return <Navigate to={user ? paths.account : paths.signIn} replace />;
return <main className="m-page m-gut enter"><header className="m-large"><h1>Você</h1></header>
{user ? <><Link className="m-me" to={paths.account}><Avatar name={user.name} src={user.avatar} /><span><b>{user.name}</b><small>{user.email}</small></span><CaretRightIcon className="m-chev" /></Link>
<Group title="Aprendizado" entries={[{ label: 'Minha aprendizagem', to: paths.learning, icon: BooksIcon }, { label: 'Meus downloads', to: paths.downloads, icon: DownloadSimpleIcon }, { label: 'Biblioteca', to: paths.library, icon: FolderIcon }]} />
{canTeach && <Group title="Gestão" entries={[{ label: 'Gerenciar cursos', to: paths.manage, icon: VideoCameraIcon }, ...(user.role === 'superadmin' ? [{ label: 'Administração', to: paths.admin, icon: GearIcon }] : [])]} />}
<Group title="Conta" entries={[{ label: 'Dados pessoais', to: paths.account, icon: UserIcon }]} />
</> : <><div className="m-signin"><UserIcon className="m-ic xl" /><h2>Entre para continuar</h2><p>Com uma conta gratuita você assiste aos cursos, salva o progresso e participa da comunidade.</p><Link className="btn m-big" to={paths.signUp}>Criar conta</Link><Link className="btn sec m-big" to={paths.signIn}>Entrar</Link></div><Group title="Materiais" entries={[{ label: 'Biblioteca', to: paths.library, icon: FolderIcon }]} /></>}
<section className="m-group"><h2>Aparência</h2><div className="m-list"><div className="m-row"><span className="m-ic"><MoonIcon className="ph" /></span><span className="m-rt"><b>Modo escuro</b></span><button className="sw" type="button" role="switch" aria-checked={theme === 'dark'} aria-label="Modo escuro" onClick={toggleTheme} /></div></div></section>
{user && <section className="m-group"><div className="m-list"><button className="m-row m-danger" type="button" onClick={() => { logout(); navigate(paths.explore); }}><span className="m-ic"><SignOutIcon className="ph" /></span><span className="m-rt"><b>Sair</b></span></button></div></section>}
</main>;
};