Files
compor-academy/components/catalog/Hero.tsx
Cauê Faleiros 21085e887d
All checks were successful
CI / Validate frontend and API (push) Successful in 2m22s
CI / Build and publish Docker images (push) Successful in 1m6s
feat: finalize academy redesign and production readiness
Align admin, community, search, library, learning and course management with the mockup. Add saved courses, download history, public community feed, instructor directory, backend search, course views, admin content tools and community moderation. Harden API and Nginx for production.
2026-11-05 15:06:53 -03:00

174 lines
9.1 KiB
TypeScript

import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { CaretLeftIcon, CaretRightIcon, PlayIcon } from '@phosphor-icons/react';
import { Course } from '../../types';
import { getHomeBanners, PublicHomeBanner } from '../../services/db';
import { AreaTone, useCatalog } from '../../context/CatalogContext';
import { useAuth } from '../../context/AuthContext';
import { ArtImage, courseFraming } from './Artwork';
import { courseMeta, hasRealCover } from '../../lib/format';
import { paths } from '../../lib/routes';
import { useIsMobile } from '../../hooks/useMediaQuery';
const SLIDE_MS = 6000;
export interface Slide {
id: string;
title: string;
description: string;
tone: AreaTone;
image: string | null;
framing?: { zoom?: number; x?: number; y?: number };
course?: Course;
}
/** Home banners configured by the admin; without any, the first course is featured. */
export const useSlides = () => {
const { courses, courseById, toneOf, isLoading } = useCatalog();
const [banners, setBanners] = useState<PublicHomeBanner[] | null>(null);
useEffect(() => {
getHomeBanners().then(setBanners).catch(() => setBanners([]));
}, []);
return useMemo<Slide[]>(() => {
if (isLoading) return [];
const fromCourse = (course: Course): Slide => ({
id: course.id,
title: course.title,
description: course.description,
tone: toneOf(course.category),
image: hasRealCover(course.thumbnail) ? course.thumbnail : null,
framing: courseFraming(course),
course,
});
if (banners === null) return [];
if (!banners.length) return courses[0] ? [fromCourse(courses[0])] : [];
return banners.map((banner): Slide => {
const course = banner.courseId ? courseById(banner.courseId) : undefined;
if (banner.kind === 'course') {
const base = course ? fromCourse(course) : null;
return {
id: banner.id,
title: banner.courseTitle || banner.title || base?.title || '',
description: banner.courseDescription || banner.description || base?.description || '',
tone: base?.tone || 'midia',
image: banner.courseImageUrl && hasRealCover(banner.courseImageUrl) ? banner.courseImageUrl : base?.image || null,
framing: { zoom: banner.coverImageZoom ?? course?.coverImageZoom, x: banner.coverImagePositionX ?? course?.coverImagePositionX, y: banner.coverImagePositionY ?? course?.coverImagePositionY },
course,
};
}
return {
id: banner.id,
title: banner.title,
description: banner.description,
tone: 'midia',
image: banner.imageUrl,
framing: { zoom: banner.coverImageZoom ?? 1, x: banner.coverImagePositionX ?? 50, y: banner.coverImagePositionY ?? 50 },
course,
};
}).filter((slide) => slide.title || slide.image);
}, [banners, courseById, courses, isLoading, toneOf]);
};
export const SlideActions: React.FC<{ course: Course; className?: string; size?: string }> = ({ course, className = '', size = 'lg' }) => {
const { user } = useAuth();
const started = (course.progress || 0) > 0;
return (
<div className={`acts ${className}`}>
{user
? <Link className={`btn ${size} b1`} to={paths.continueCourse(course.id)}><PlayIcon className="ph" weight="fill" /> {started ? `Continuar aula ${Math.min(course.lessons.length, Math.floor((course.progress || 0) * course.lessons.length / 100) + 1)}` : 'Assistir'}</Link>
: <Link className={`btn ${size} b1`} to={paths.signUp} state={{ message: 'Crie uma conta gratuita para assistir aos cursos.' }}><PlayIcon className="ph" weight="fill" /> Assistir</Link>}
<Link className={`btn ${size} b2`} to={paths.course(course.id)}>Ver curso</Link>
</div>
);
};
/** Full-width carousel that runs underneath the glass sidebar, with "Explorar" over it. */
export const Hero: React.FC = () => {
const slides = useSlides();
const isMobile = useIsMobile();
const { user } = useAuth();
const [index, setIndex] = useState(0);
const [cycle, setCycle] = useState(0);
const [paused, setPaused] = useState(false);
const heroRef = useRef<HTMLElement>(null);
const reduceMotion = useMemo(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches, []);
const show = useCallback((next: number) => {
setIndex(() => (next + slides.length) % Math.max(slides.length, 1));
setCycle((value) => value + 1);
}, [slides.length]);
useEffect(() => {
if (isMobile || slides.length < 2 || paused || reduceMotion) return;
const timer = window.setTimeout(() => show(index + 1), SLIDE_MS);
return () => window.clearTimeout(timer);
}, [cycle, index, isMobile, paused, reduceMotion, show, slides.length]);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (!heroRef.current?.contains(document.activeElement)) return;
if (event.key === 'ArrowRight') show(index + 1);
if (event.key === 'ArrowLeft') show(index - 1);
};
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [index, show]);
if (!slides.length) return isMobile ? <div className="m-gut m-large"><h1>Explorar</h1>{user ? <Link className="m-av" to={paths.you} aria-label="Você">{user.name.slice(0, 2).toUpperCase()}</Link> : <Link className="btn m-sm" to={paths.signUp}>Criar conta</Link>}</div> : <div className="wrap page"><h1>Explorar</h1></div>;
const current = slides[Math.min(index, slides.length - 1)];
if (isMobile) return <section className="m-feat-wrap" aria-label="Cursos em destaque">
<div className="m-gut m-large"><h1>Explorar</h1>{user ? <Link className="m-av" to={paths.you} aria-label="Você">{user.name.slice(0, 2).toUpperCase()}</Link> : <Link className="btn m-sm" to={paths.signUp}>Criar conta</Link>}</div>
<div className="m-feat" onScroll={(event) => { const rail = event.currentTarget; setIndex(Math.round(rail.scrollLeft / (rail.firstElementChild?.clientWidth || 1))); }}>
{slides.map((slide) => <article key={slide.id} className={`m-fc tr-${slide.tone}${slide.image ? ' has-img' : ''}`}>
{slide.image && <ArtImage source={slide.image} framing={slide.framing} />}
{slide.course && <Link className="m-fc-link" to={paths.course(slide.course.id)} aria-label={`Ver curso ${slide.title}`} />}
<div className="m-fc-in"><small>{slide.course?.category}</small><h2>{slide.title}</h2>{slide.course && <p>{[slide.course.instructor, courseMeta(slide.course)].filter(Boolean).join(' · ')}</p>}{slide.course && <Link className="btn m-fc-btn" to={user ? paths.continueCourse(slide.course.id) : paths.signUp}><PlayIcon className="ph" weight="fill" />{user && slide.course.progress ? `Continuar aula ${Math.min(slide.course.lessons.length, Math.floor((slide.course.progress || 0) * slide.course.lessons.length / 100) + 1)}` : 'Assistir'}</Link>}</div>
</article>)}
</div>
{slides.length > 1 && <div className="m-dots">{slides.map((slide, slideIndex) => <i key={slide.id} className={slideIndex === index ? 'on' : ''} />)}</div>}
</section>;
return (
<section
ref={heroRef}
className={`hero tr-${current.tone}${current.image ? ' has-img' : ''}${paused ? ' paused' : ''}`}
style={{ '--hc': 'var(--co)', '--dur': `${SLIDE_MS}ms` } as React.CSSProperties}
aria-roledescription="carrossel"
aria-label="Cursos em destaque"
onMouseEnter={() => setPaused(true)}
onMouseLeave={() => { setPaused(false); setCycle((value) => value + 1); }}
>
{slides.map((slide, slideIndex) => (
<article key={slide.id} className={`slide tr-${slide.tone}${slide.image ? ' has-img' : ''}${slideIndex === index ? ' on' : ''}`} aria-hidden={slideIndex !== index} aria-label={`${slideIndex + 1} de ${slides.length}`}>
{slide.image && <ArtImage source={slide.image} framing={slide.framing} />}
<div className="wrap sl">
<div className="copy">
<h2>{slide.title}</h2>
{slide.course && <div className="meta num">{[slide.course.instructor, courseMeta(slide.course)].filter(Boolean).join(' · ')}</div>}
{slide.description && <p>{slide.description}</p>}
{slide.course && <SlideActions course={slide.course} />}
</div>
</div>
</article>
))}
<div className="wrap htitle"><h1>Explorar</h1></div>
{slides.length > 1 && (
<>
<div className="hdots">
{slides.map((slide, slideIndex) => (
<button key={slide.id} type="button" className={`dot${slideIndex === index ? ' on' : ''}`} onClick={() => show(slideIndex)} aria-label={`Destaque ${slideIndex + 1}`}>
{slideIndex === index && <i key={cycle} />}
</button>
))}
</div>
<button type="button" className="harrow l" onClick={() => show(index - 1)} aria-label="Destaque anterior"><CaretLeftIcon className="ph" weight="bold" /></button>
<button type="button" className="harrow r" onClick={() => show(index + 1)} aria-label="Próximo destaque"><CaretRightIcon className="ph" weight="bold" /></button>
</>
)}
</section>
);
};