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.
This commit is contained in:
@@ -1,5 +1,10 @@
|
||||
import React from 'react';
|
||||
import { PlayCircle, Download, FileText, CheckCircle2 } from 'lucide-react';
|
||||
import {
|
||||
PlayCircleIcon as PlayCircle,
|
||||
DownloadSimpleIcon as Download,
|
||||
FileTextIcon as FileText,
|
||||
CheckCircleIcon as CheckCircle2
|
||||
} from '@phosphor-icons/react';
|
||||
import { Course, SectionVariant } from '../types';
|
||||
import { CourseCoverImage } from './CourseCoverImage';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { CourseRow } from './CourseRow';
|
||||
import { Section, Course } from '../types';
|
||||
import { getCourses, getLearningPaths, PublicLearningPath } from '../services/db';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { Loader2, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { LearningPathRow } from './LearningPathRow';
|
||||
|
||||
interface CourseGridProps {
|
||||
onCourseSelect?: (course: Course) => void;
|
||||
selectedCategoryFilter?: string;
|
||||
}
|
||||
|
||||
export const CourseGrid: React.FC<CourseGridProps> = ({
|
||||
onCourseSelect,
|
||||
selectedCategoryFilter
|
||||
}) => {
|
||||
const [courses, setCourses] = useState<Course[]>([]);
|
||||
const [paths, setPaths] = useState<PublicLearningPath[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeCategory, setActiveCategory] = useState<string>('all');
|
||||
const { user } = useAuth();
|
||||
|
||||
// Slider State & Refs for Categories
|
||||
const categoryScrollRef = useRef<HTMLDivElement>(null);
|
||||
const isMouseDownRef = useRef(false);
|
||||
const startXRef = useRef(0);
|
||||
const scrollLeftRef = useRef(0);
|
||||
const draggedDistanceRef = useRef(0);
|
||||
const [isDraggingCategory, setIsDraggingCategory] = useState(false);
|
||||
const [canScrollCatLeft, setCanScrollCatLeft] = useState(false);
|
||||
const [canScrollCatRight, setCanScrollCatRight] = useState(false);
|
||||
|
||||
const checkCategoryBoundaries = useCallback(() => {
|
||||
if (!categoryScrollRef.current) return;
|
||||
const { scrollLeft, scrollWidth, clientWidth } = categoryScrollRef.current;
|
||||
setCanScrollCatLeft(scrollLeft > 10);
|
||||
setCanScrollCatRight(scrollLeft + clientWidth < scrollWidth - 10);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
try {
|
||||
const [loadedCourses, loadedPaths] = await Promise.all([getCourses(), getLearningPaths()]);
|
||||
setCourses(loadedCourses);
|
||||
setPaths(loadedPaths);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadData();
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
checkCategoryBoundaries();
|
||||
window.addEventListener('resize', checkCategoryBoundaries);
|
||||
return () => window.removeEventListener('resize', checkCategoryBoundaries);
|
||||
}, [checkCategoryBoundaries, courses]);
|
||||
|
||||
const handleCategoryScroll = (direction: 'left' | 'right') => {
|
||||
if (!categoryScrollRef.current) return;
|
||||
const scrollAmount = 300;
|
||||
categoryScrollRef.current.scrollBy({
|
||||
left: direction === 'left' ? -scrollAmount : scrollAmount,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
};
|
||||
|
||||
const handleCatMouseDown = (e: React.MouseEvent) => {
|
||||
if (!categoryScrollRef.current) return;
|
||||
isMouseDownRef.current = true;
|
||||
startXRef.current = e.pageX - categoryScrollRef.current.offsetLeft;
|
||||
scrollLeftRef.current = categoryScrollRef.current.scrollLeft;
|
||||
draggedDistanceRef.current = 0;
|
||||
setIsDraggingCategory(false);
|
||||
};
|
||||
|
||||
const handleCatMouseMove = (e: React.MouseEvent) => {
|
||||
if (!isMouseDownRef.current || !categoryScrollRef.current) return;
|
||||
e.preventDefault();
|
||||
const x = e.pageX - categoryScrollRef.current.offsetLeft;
|
||||
const walk = (x - startXRef.current) * 1.4;
|
||||
draggedDistanceRef.current = Math.abs(walk);
|
||||
|
||||
if (draggedDistanceRef.current > 5) {
|
||||
setIsDraggingCategory(true);
|
||||
categoryScrollRef.current.scrollLeft = scrollLeftRef.current - walk;
|
||||
}
|
||||
};
|
||||
|
||||
const handleCatMouseUp = () => {
|
||||
isMouseDownRef.current = false;
|
||||
setTimeout(() => {
|
||||
setIsDraggingCategory(false);
|
||||
draggedDistanceRef.current = 0;
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleCategoryClick = (cat: string) => {
|
||||
if (draggedDistanceRef.current < 8) {
|
||||
setActiveCategory(cat);
|
||||
}
|
||||
};
|
||||
|
||||
const categories = Array.from(new Set<string>(courses.map((course) => course.category)))
|
||||
.sort((left, right) => left.localeCompare(right, 'pt-BR'));
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-64 w-full">
|
||||
<Loader2 className="w-10 h-10 text-orange-500 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (courses.length === 0) {
|
||||
return (
|
||||
<section className="min-h-[60vh] flex items-center justify-center px-6 pt-28 pb-20">
|
||||
<div className="max-w-md text-center rounded-2xl border border-white/10 bg-zinc-950/80 p-8">
|
||||
<h2 className="text-xl font-bold text-white">Cursos em breve</h2>
|
||||
<p className="mt-3 text-sm leading-relaxed text-gray-400">Ainda não há cursos publicados. Cadastre o primeiro curso no Painel do Instrutor.</p>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// Filter courses if a specific category is active
|
||||
const filteredCourses = activeCategory === 'all'
|
||||
? courses
|
||||
: courses.filter(c => c.category === activeCategory);
|
||||
|
||||
// Group into curated sections for Netflix/Apple TV style layout
|
||||
const sections: Section[] = [
|
||||
{
|
||||
title: activeCategory === 'all' ? 'Cursos em Destaque' : activeCategory,
|
||||
variant: 'landscape',
|
||||
courses: filteredCourses
|
||||
},
|
||||
{
|
||||
title: 'Com Materiais & Planilhas para Download',
|
||||
variant: 'landscape',
|
||||
courses: courses.filter(c => (c.attachments && c.attachments.length > 0) || c.lessons.some(l => l.attachments && l.attachments.length > 0))
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<section className="relative z-20 pb-32 space-y-8">
|
||||
|
||||
{/* Category Pills Slider Container */}
|
||||
<div className="px-6 md:px-12 max-w-[1440px] mx-auto select-none">
|
||||
<div className="relative group/catslider flex items-center">
|
||||
|
||||
{/* Scroll Button Left */}
|
||||
{canScrollCatLeft && (
|
||||
<button
|
||||
onClick={() => handleCategoryScroll('left')}
|
||||
className="absolute -left-3 sm:-left-4 z-20 w-8 h-8 sm:w-9 sm:h-9 rounded-full bg-zinc-900/90 hover:bg-orange-500 text-white border border-white/20 backdrop-blur-md flex items-center justify-center shadow-xl transition-all hover:scale-110 active:scale-95 shrink-0"
|
||||
title="Categorias anteriores"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4 sm:w-5 sm:h-5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Left Gradient Fade */}
|
||||
{canScrollCatLeft && (
|
||||
<div className="absolute left-0 top-0 bottom-0 w-12 bg-gradient-to-r from-black via-black/80 to-transparent pointer-events-none z-10" />
|
||||
)}
|
||||
|
||||
{/* Scrollable Category Track */}
|
||||
<div
|
||||
ref={categoryScrollRef}
|
||||
onMouseDown={handleCatMouseDown}
|
||||
onMouseMove={handleCatMouseMove}
|
||||
onMouseUp={handleCatMouseUp}
|
||||
onMouseLeave={handleCatMouseUp}
|
||||
onScroll={checkCategoryBoundaries}
|
||||
className={`flex items-center gap-2.5 overflow-x-auto py-2 hide-scrollbar flex-1 min-w-0 overscroll-x-contain scroll-smooth ${
|
||||
isDraggingCategory ? 'cursor-grabbing' : 'cursor-grab'
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
onClick={() => handleCategoryClick('all')}
|
||||
className={`px-5 py-2.5 rounded-[980px] text-xs font-bold uppercase tracking-wider transition-all whitespace-nowrap shrink-0 shadow-sm ${
|
||||
activeCategory === 'all'
|
||||
? 'bg-orange-500 text-white shadow-lg shadow-orange-500/25 scale-[1.02]'
|
||||
: 'bg-zinc-900/90 text-gray-300 hover:bg-zinc-800 hover:text-white border border-white/10'
|
||||
}`}
|
||||
>
|
||||
Todos os Cursos ({courses.length})
|
||||
</button>
|
||||
|
||||
{categories.map(cat => {
|
||||
const count = courses.filter(c => c.category === cat).length;
|
||||
return (
|
||||
<button
|
||||
key={cat}
|
||||
onClick={() => handleCategoryClick(cat)}
|
||||
className={`px-5 py-2.5 rounded-[980px] text-xs font-bold uppercase tracking-wider transition-all whitespace-nowrap shrink-0 shadow-sm ${
|
||||
activeCategory === cat
|
||||
? 'bg-orange-500 text-white shadow-lg shadow-orange-500/25 scale-[1.02]'
|
||||
: 'bg-zinc-900/90 text-gray-300 hover:bg-zinc-800 hover:text-white border border-white/10'
|
||||
}`}
|
||||
>
|
||||
{cat} {count > 0 && `(${count})`}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Right Gradient Fade */}
|
||||
{canScrollCatRight && (
|
||||
<div className="absolute right-0 top-0 bottom-0 w-12 bg-gradient-to-l from-black via-black/80 to-transparent pointer-events-none z-10" />
|
||||
)}
|
||||
|
||||
{/* Scroll Button Right */}
|
||||
{canScrollCatRight && (
|
||||
<button
|
||||
onClick={() => handleCategoryScroll('right')}
|
||||
className="absolute -right-3 sm:-right-4 z-20 w-8 h-8 sm:w-9 sm:h-9 rounded-full bg-zinc-900/90 hover:bg-orange-500 text-white border border-white/20 backdrop-blur-md flex items-center justify-center shadow-xl transition-all hover:scale-110 active:scale-95 shrink-0"
|
||||
title="Mais categorias"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4 sm:w-5 sm:h-5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sections Rows */}
|
||||
{sections.map((section, index) => (
|
||||
section.courses.length > 0 && (
|
||||
<CourseRow
|
||||
key={`${section.title}-${index}`}
|
||||
section={section}
|
||||
onCourseClick={onCourseSelect}
|
||||
/>
|
||||
)
|
||||
))}
|
||||
{activeCategory === 'all' && paths.length > 0 && <LearningPathRow paths={paths} courses={courses} onCourseSelect={onCourseSelect} />}
|
||||
</section>
|
||||
);
|
||||
};
|
||||
@@ -1,682 +0,0 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import {
|
||||
X,
|
||||
Send,
|
||||
User as UserIcon,
|
||||
Lightbulb,
|
||||
Paperclip,
|
||||
Lock,
|
||||
Unlock,
|
||||
ListVideo,
|
||||
Play,
|
||||
Download,
|
||||
Sparkles,
|
||||
MessageSquare,
|
||||
CheckCircle2,
|
||||
Check,
|
||||
Share2,
|
||||
FileText
|
||||
} from 'lucide-react';
|
||||
import { Course, Comment, Lesson, Attachment } from '../types';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { getComments, getLessonProgress, saveComment, saveLessonCompletion, saveLessonProgress, incrementViews } from '../services/db';
|
||||
import { LoginModal } from './LoginModal';
|
||||
import { MaterialCard } from './MaterialCard';
|
||||
import { courseApi, LessonPlayback } from '../services/api';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
playerjs?: {
|
||||
Player: new (element: HTMLIFrameElement) => {
|
||||
on: (event: string, listener: (data?: { seconds?: number; duration?: number }) => void) => void;
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let bunnyPlayerJsPromise: Promise<void> | null = null;
|
||||
|
||||
const loadBunnyPlayerJs = () => {
|
||||
if (window.playerjs) return Promise.resolve();
|
||||
if (bunnyPlayerJsPromise) return bunnyPlayerJsPromise;
|
||||
bunnyPlayerJsPromise = new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://assets.mediadelivery.net/playerjs/player-0.1.0.min.js';
|
||||
script.async = true;
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error('Bunny player events could not be loaded'));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
return bunnyPlayerJsPromise;
|
||||
};
|
||||
|
||||
interface CoursePlayerModalProps {
|
||||
course: Course | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export const CoursePlayerModal: React.FC<CoursePlayerModalProps> = ({ course, onClose }) => {
|
||||
const { user } = useAuth();
|
||||
const [comments, setComments] = useState<Comment[]>([]);
|
||||
const [newComment, setNewComment] = useState('');
|
||||
const [currentLesson, setCurrentLesson] = useState<Lesson | null>(null);
|
||||
const [completedLessonIds, setCompletedLessonIds] = useState<string[]>([]);
|
||||
const [watchedSecondsByLesson, setWatchedSecondsByLesson] = useState<Record<string, number>>({});
|
||||
const [showLoginPrompt, setShowLoginPrompt] = useState(false);
|
||||
const [activeTab, setActiveTab] = useState<'playlist' | 'materials' | 'discussion'>('playlist');
|
||||
const [copiedLink, setCopiedLink] = useState(false);
|
||||
const [playback, setPlayback] = useState<LessonPlayback | null>(null);
|
||||
const [playbackError, setPlaybackError] = useState('');
|
||||
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const bunnyFrameRef = useRef<HTMLIFrameElement>(null);
|
||||
const lastProgressSave = useRef<Record<string, number>>({});
|
||||
|
||||
// Load course data and this learner's saved state from PostgreSQL.
|
||||
useEffect(() => {
|
||||
if (course) {
|
||||
incrementViews(course.id);
|
||||
setCompletedLessonIds([]);
|
||||
setWatchedSecondsByLesson({});
|
||||
lastProgressSave.current = {};
|
||||
if (user) {
|
||||
getComments(course.id).then(setComments).catch(() => setComments([]));
|
||||
getLessonProgress(course.id).then((progress) => {
|
||||
const completed = progress.filter((item) => item.completedAt).map((item) => item.lessonId);
|
||||
setCompletedLessonIds(completed);
|
||||
setWatchedSecondsByLesson(Object.fromEntries(progress.map((item) => [item.lessonId, item.watchedSeconds])));
|
||||
lastProgressSave.current = Object.fromEntries(progress.map((item) => [item.lessonId, item.watchedSeconds]));
|
||||
const nextIncomplete = course.lessons.find((lesson) => !completed.includes(lesson.id));
|
||||
if (nextIncomplete) setCurrentLesson(nextIncomplete);
|
||||
}).catch(() => setCompletedLessonIds([]));
|
||||
} else {
|
||||
setComments([]);
|
||||
}
|
||||
|
||||
// Select first lesson by default
|
||||
if (course.lessons && course.lessons.length > 0) {
|
||||
setCurrentLesson(course.lessons[0]);
|
||||
}
|
||||
}
|
||||
}, [course, user]);
|
||||
|
||||
// The API verifies the session before returning a time-limited Bunny embed
|
||||
// URL. A video provider key is never sent to the browser.
|
||||
useEffect(() => {
|
||||
if (!course || !user || !currentLesson) {
|
||||
setPlayback(null);
|
||||
setPlaybackError('');
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setPlayback(null);
|
||||
setPlaybackError('');
|
||||
courseApi.playback(course.id, currentLesson.id)
|
||||
.then((response) => {
|
||||
if (!cancelled) setPlayback(response.data);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!cancelled) setPlaybackError(error instanceof Error ? error.message : 'Não foi possível carregar este vídeo.');
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [course, user, currentLesson]);
|
||||
|
||||
// Persist completed lessons and recalculate progress
|
||||
const updateCompletedLessons = (newCompleted: string[]) => {
|
||||
setCompletedLessonIds(newCompleted);
|
||||
if (course) {
|
||||
}
|
||||
};
|
||||
|
||||
const toggleLessonCompleted = (lessonId: string) => {
|
||||
if (!user) {
|
||||
setShowLoginPrompt(true);
|
||||
return;
|
||||
}
|
||||
if (completedLessonIds.includes(lessonId)) {
|
||||
const updated = completedLessonIds.filter(id => id !== lessonId);
|
||||
updateCompletedLessons(updated);
|
||||
saveLessonCompletion(lessonId, false).catch(() => updateCompletedLessons(completedLessonIds));
|
||||
} else {
|
||||
markLessonCompleted(lessonId);
|
||||
}
|
||||
};
|
||||
|
||||
const markLessonCompleted = (lessonId: string, watchedSeconds?: number) => {
|
||||
if (!user || completedLessonIds.includes(lessonId)) return;
|
||||
const previous = completedLessonIds;
|
||||
updateCompletedLessons([...previous, lessonId]);
|
||||
saveLessonCompletion(lessonId, true, watchedSeconds).catch(() => updateCompletedLessons(previous));
|
||||
};
|
||||
|
||||
// Video finished automatically -> mark lesson as completed
|
||||
const handleVideoEnded = () => {
|
||||
if (currentLesson && !completedLessonIds.includes(currentLesson.id)) {
|
||||
markLessonCompleted(currentLesson.id, Math.round(videoRef.current?.duration || 0));
|
||||
}
|
||||
|
||||
// Auto-advance to next lesson if available
|
||||
if (course?.lessons && currentLesson) {
|
||||
const currentIndex = course.lessons.findIndex(l => l.id === currentLesson.id);
|
||||
if (currentIndex >= 0 && currentIndex < course.lessons.length - 1) {
|
||||
const nextLesson = course.lessons[currentIndex + 1];
|
||||
if (user) {
|
||||
setTimeout(() => {
|
||||
setCurrentLesson(nextLesson);
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Track video progress
|
||||
const handleTimeUpdate = () => {
|
||||
if (videoRef.current) {
|
||||
const { currentTime, duration } = videoRef.current;
|
||||
if (duration > 0) {
|
||||
if (user && currentLesson && currentTime - (lastProgressSave.current[currentLesson.id] || 0) >= 30) {
|
||||
const watchedSeconds = Math.floor(currentTime);
|
||||
lastProgressSave.current[currentLesson.id] = watchedSeconds;
|
||||
setWatchedSecondsByLesson((current) => ({ ...current, [currentLesson.id]: watchedSeconds }));
|
||||
saveLessonProgress(currentLesson.id, watchedSeconds).catch(() => undefined);
|
||||
}
|
||||
const percent = Math.round((currentTime / duration) * 100);
|
||||
// Automatically mark as complete when reaching 95%+
|
||||
if (percent >= 95 && currentLesson && !completedLessonIds.includes(currentLesson.id)) {
|
||||
markLessonCompleted(currentLesson.id, Math.round(currentTime));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Bunny's iframe does not expose an HTMLVideoElement. Player.js receives
|
||||
// Bunny's trusted playback events and sends the same progress updates used
|
||||
// for external video providers.
|
||||
useEffect(() => {
|
||||
if (!playback || playback.kind !== 'embed' || !currentLesson || !user) return;
|
||||
let disposed = false;
|
||||
const lessonId = currentLesson.id;
|
||||
void loadBunnyPlayerJs().then(() => {
|
||||
if (disposed || !bunnyFrameRef.current || !window.playerjs) return;
|
||||
const player = new window.playerjs.Player(bunnyFrameRef.current);
|
||||
player.on('timeupdate', (data) => {
|
||||
const watchedSeconds = Math.floor(data?.seconds || 0);
|
||||
if (disposed || watchedSeconds <= 0 || watchedSeconds - (lastProgressSave.current[lessonId] || 0) < 30) return;
|
||||
lastProgressSave.current[lessonId] = watchedSeconds;
|
||||
setWatchedSecondsByLesson((current) => ({ ...current, [lessonId]: watchedSeconds }));
|
||||
saveLessonProgress(lessonId, watchedSeconds).catch(() => undefined);
|
||||
});
|
||||
player.on('ended', (data) => {
|
||||
if (disposed) return;
|
||||
markLessonCompleted(lessonId, Math.floor(data?.duration || data?.seconds || 0));
|
||||
});
|
||||
}).catch(() => undefined);
|
||||
return () => { disposed = true; };
|
||||
}, [playback, currentLesson, user, completedLessonIds]);
|
||||
|
||||
const restoreWatchPosition = () => {
|
||||
if (!currentLesson || !videoRef.current) return;
|
||||
const watchedSeconds = watchedSecondsByLesson[currentLesson.id] || 0;
|
||||
if (watchedSeconds > 0 && watchedSeconds < videoRef.current.duration - 5) videoRef.current.currentTime = watchedSeconds;
|
||||
};
|
||||
|
||||
const handleAddComment = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newComment.trim() || !course) return;
|
||||
|
||||
const comment = {
|
||||
courseId: course.id,
|
||||
lessonId: currentLesson?.id,
|
||||
text: newComment,
|
||||
};
|
||||
|
||||
try {
|
||||
const savedComment = await saveComment(comment);
|
||||
setComments([savedComment, ...comments]);
|
||||
setNewComment('');
|
||||
} catch {
|
||||
// The server remains the source of truth; leave the text intact for a retry.
|
||||
}
|
||||
};
|
||||
|
||||
const changeLesson = (lesson: Lesson) => {
|
||||
setCurrentLesson(lesson);
|
||||
};
|
||||
|
||||
const handleShare = () => {
|
||||
navigator.clipboard.writeText(window.location.href);
|
||||
setCopiedLink(true);
|
||||
setTimeout(() => setCopiedLink(false), 2500);
|
||||
};
|
||||
|
||||
// Collect all downloadable materials for this course (Global + All Lessons)
|
||||
const allCourseAttachments: Array<{ attachment: Attachment; source: string }> = [];
|
||||
|
||||
if (course?.attachments) {
|
||||
course.attachments.forEach(att => {
|
||||
allCourseAttachments.push({ attachment: att, source: 'Material Geral do Curso' });
|
||||
});
|
||||
}
|
||||
|
||||
if (course?.lessons) {
|
||||
course.lessons.forEach(l => {
|
||||
if (l.attachments) {
|
||||
l.attachments.forEach(att => {
|
||||
allCourseAttachments.push({ attachment: att, source: l.title });
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const currentLessonAttachments = currentLesson?.attachments || [];
|
||||
|
||||
// Access Control Logic
|
||||
const canWatch = currentLesson && Boolean(user);
|
||||
|
||||
if (!course) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] bg-[#09090b] text-white overflow-y-auto animate-fade-in-up">
|
||||
{/* Top Bar Floating Controls */}
|
||||
<div className="fixed top-0 left-0 right-0 p-4 md:p-6 z-30 flex items-center justify-between bg-gradient-to-b from-black/90 via-black/40 to-transparent pointer-events-none">
|
||||
<div className="flex items-center gap-3 pointer-events-auto bg-black/60 backdrop-blur-md px-4 py-2 rounded-[980px] border border-white/10">
|
||||
<span className="w-2 h-2 rounded-[980px] bg-orange-500 animate-pulse"></span>
|
||||
<span className="text-caption font-semibold tracking-caption text-gray-200 truncate max-w-[200px] md:max-w-md">
|
||||
{course.title}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 pointer-events-auto">
|
||||
<button
|
||||
onClick={handleShare}
|
||||
className="flex items-center gap-2 bg-white/10 hover:bg-white/20 backdrop-blur-md text-white text-body-sm font-semibold tracking-body-sm px-4 py-2.5 rounded-[980px] transition-all active:scale-95 shadow-xl"
|
||||
title="Copiar Link"
|
||||
>
|
||||
<Share2 className="w-4 h-4 text-orange-400" />
|
||||
<span className="hidden sm:inline">{copiedLink ? 'Link Copiado!' : 'Compartilhar'}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="bg-white/10 hover:bg-white/20 backdrop-blur-md p-2.5 rounded-[980px] transition-all active:scale-95 text-white shadow-xl"
|
||||
title="Fechar"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-[1440px] mx-auto min-h-screen pt-16 md:pt-20 pb-20">
|
||||
<div className="flex flex-col lg:flex-row gap-8 px-4 md:px-8">
|
||||
|
||||
{/* Main Left Column: Video & Lesson Details */}
|
||||
<div className="flex-1 lg:max-w-[65%] xl:max-w-[68%]">
|
||||
|
||||
{/* Video Player Section */}
|
||||
<div className="w-full aspect-video bg-black rounded-[8px] overflow-hidden relative shadow-xl border border-white/10 group">
|
||||
{canWatch ? (
|
||||
playback ? (
|
||||
playback.kind === 'embed' && playback.embedUrl ? (
|
||||
<iframe
|
||||
key={currentLesson?.id}
|
||||
ref={bunnyFrameRef}
|
||||
src={playback.embedUrl}
|
||||
title={currentLesson?.title || 'Vídeo da aula'}
|
||||
className="w-full h-full border-0 rounded-[8px]"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; fullscreen"
|
||||
allowFullScreen
|
||||
/>
|
||||
) : playback.source ? (
|
||||
<video
|
||||
key={currentLesson?.id}
|
||||
ref={videoRef}
|
||||
src={playback.source}
|
||||
className="w-full h-full object-contain rounded-[8px]"
|
||||
controls
|
||||
autoPlay
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
onEnded={handleVideoEnded}
|
||||
onLoadedMetadata={restoreWatchPosition}
|
||||
>
|
||||
Seu navegador não suporta a tag de vídeo.
|
||||
</video>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-sm text-gray-400">Vídeo indisponível.</div>
|
||||
)
|
||||
) : (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center text-center p-6 text-sm text-gray-400">
|
||||
{playbackError ? <span className="text-amber-300">{playbackError}</span> : <span>Carregando vídeo seguro...</span>}
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
// Locked State
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center bg-zinc-950/90 backdrop-blur-md z-10 text-center p-6 rounded-[8px]">
|
||||
<div className="bg-orange-500/10 border border-orange-500/20 p-4 rounded-[8px] mb-4 text-orange-400">
|
||||
<Lock className="w-8 h-8" />
|
||||
</div>
|
||||
<h2 className="font-display text-subheading md:text-heading-sm font-bold tracking-heading-sm leading-heading-sm mb-2">Aula Exclusiva (Pro)</h2>
|
||||
<p className="text-body-sm font-normal text-gray-400 mb-6 max-w-md leading-body-sm tracking-body-sm">
|
||||
Esta aula e seus materiais de download complementares estão disponíveis para membros. Faça login para continuar assistindo.
|
||||
</p>
|
||||
<button
|
||||
onClick={() => setShowLoginPrompt(true)}
|
||||
className="bg-orange-500 hover:bg-orange-600 text-white text-body-sm font-semibold tracking-body-sm px-8 py-3 rounded-[980px] transition-all shadow-xl shadow-orange-500/25 active:scale-95"
|
||||
>
|
||||
Fazer Login para Acessar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Current Lesson Header Info */}
|
||||
<div className="mt-6 mb-8">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-3">
|
||||
<div className="flex items-center gap-2.5 text-caption font-semibold uppercase tracking-caption text-orange-400">
|
||||
<span>{course.category}</span>
|
||||
<span className="w-1 h-1 rounded-[980px] bg-zinc-700"></span>
|
||||
<span className="text-gray-400">{currentLesson?.duration || '15m'}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Mark as completed toggle button */}
|
||||
{currentLesson && (
|
||||
<button
|
||||
onClick={() => toggleLessonCompleted(currentLesson.id)}
|
||||
className={`inline-flex items-center gap-1.5 text-xs font-semibold px-3.5 py-1.5 rounded-[980px] transition-all active:scale-95 ${
|
||||
completedLessonIds.includes(currentLesson.id)
|
||||
? 'bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 border border-emerald-500/30 font-bold'
|
||||
: 'bg-white/10 hover:bg-emerald-500/20 hover:text-emerald-300 text-gray-300'
|
||||
}`}
|
||||
>
|
||||
<CheckCircle2 className="w-3.5 h-3.5" />
|
||||
<span>{completedLessonIds.includes(currentLesson.id) ? 'Aula Concluída' : 'Concluir Aula'}</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Direct Button to Materials Tab if Available */}
|
||||
{allCourseAttachments.length > 0 && (
|
||||
<button
|
||||
onClick={() => setActiveTab('materials')}
|
||||
className="inline-flex items-center gap-2 text-caption font-semibold tracking-caption bg-orange-500/10 hover:bg-orange-500/20 text-orange-400 border border-orange-500/20 px-3.5 py-1.5 rounded-[980px] transition-all"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
<span>{allCourseAttachments.length} {allCourseAttachments.length === 1 ? 'Material' : 'Materiais'}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h1 className="font-display text-subheading sm:text-heading-sm md:text-heading font-bold tracking-heading leading-heading text-white mb-3">
|
||||
{currentLesson?.title || course.title}
|
||||
</h1>
|
||||
|
||||
<p className="text-body-sm sm:text-body text-gray-300 leading-body tracking-body font-normal mb-6">
|
||||
{currentLesson?.description || course.description}
|
||||
</p>
|
||||
|
||||
{/* Lesson Specific Quick Downloads (if present) */}
|
||||
{currentLessonAttachments.length > 0 && (
|
||||
<div className="p-6 rounded-[8px] bg-zinc-900/80 border border-orange-500/20 mb-8 space-y-4 shadow-xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="text-caption font-semibold uppercase tracking-caption text-orange-400 flex items-center gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
Downloads Desta Aula
|
||||
</h4>
|
||||
<span className="text-caption font-mono text-gray-400">
|
||||
{currentLessonAttachments.length} {currentLessonAttachments.length === 1 ? 'arquivo' : 'arquivos'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{currentLessonAttachments.map(att => (
|
||||
<MaterialCard key={att.id} attachment={att} compact />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Instructor Key Takeaways / Tips */}
|
||||
{course.tips && course.tips.length > 0 && (
|
||||
<div className="bg-gradient-to-br from-zinc-900 to-black border border-white/10 rounded-[8px] p-6 mb-8 shadow-xl">
|
||||
<h3 className="font-display text-subheading font-bold text-white mb-4 flex items-center gap-2.5 tracking-subheading leading-subheading">
|
||||
<Lightbulb className="w-5 h-5 text-amber-400" />
|
||||
Recomendações Práticas do Instrutor
|
||||
</h3>
|
||||
<ul className="space-y-3">
|
||||
{course.tips.map((tip, i) => (
|
||||
<li key={i} className="flex gap-3 text-gray-300 text-body-sm font-normal leading-body-sm tracking-body-sm">
|
||||
<span className="block w-2 h-2 rounded-[980px] bg-orange-500 mt-2 shrink-0"></span>
|
||||
<span>{tip}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Sidebar: Tabs for Playlist, Materials, and Discussion */}
|
||||
<div className="lg:w-[35%] xl:w-[32%] shrink-0 flex flex-col space-y-6">
|
||||
|
||||
{/* Tab Navigation */}
|
||||
<div className="flex items-center justify-between bg-zinc-950/90 p-1.5 rounded-[980px] border border-white/10 shadow-xl gap-1">
|
||||
<button
|
||||
onClick={() => setActiveTab('playlist')}
|
||||
className={`flex-1 flex items-center justify-center gap-1.5 py-2 px-3 sm:px-3.5 rounded-[980px] text-xs font-semibold whitespace-nowrap transition-all ${
|
||||
activeTab === 'playlist'
|
||||
? 'bg-orange-500 text-white shadow-md shadow-orange-500/25'
|
||||
: 'text-gray-400 hover:text-white hover:bg-white/5'
|
||||
}`}
|
||||
>
|
||||
<ListVideo className="w-3.5 h-3.5 shrink-0" />
|
||||
<span>Aulas ({course.lessons.length})</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('materials')}
|
||||
className={`flex-1 flex items-center justify-center gap-1.5 py-2 px-3 sm:px-3.5 rounded-[980px] text-xs font-semibold whitespace-nowrap transition-all ${
|
||||
activeTab === 'materials'
|
||||
? 'bg-orange-500 text-white shadow-md shadow-orange-500/25'
|
||||
: 'text-gray-400 hover:text-white hover:bg-white/5'
|
||||
}`}
|
||||
>
|
||||
<Download className="w-3.5 h-3.5 shrink-0" />
|
||||
<span>Downloads ({allCourseAttachments.length})</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('discussion')}
|
||||
className={`flex-1 flex items-center justify-center gap-1.5 py-2 px-3 sm:px-3.5 rounded-[980px] text-xs font-semibold whitespace-nowrap transition-all ${
|
||||
activeTab === 'discussion'
|
||||
? 'bg-orange-500 text-white shadow-md shadow-orange-500/25'
|
||||
: 'text-gray-400 hover:text-white hover:bg-white/5'
|
||||
}`}
|
||||
>
|
||||
<MessageSquare className="w-3.5 h-3.5 shrink-0" />
|
||||
<span>Dúvidas ({comments.length})</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* TAB CONTENT: Playlist */}
|
||||
{activeTab === 'playlist' && (
|
||||
<div className="bg-zinc-950/80 rounded-2xl p-5 space-y-3 shadow-xl">
|
||||
<div className="flex items-center justify-between pb-3 border-b border-white/5">
|
||||
<span className="text-xs font-bold uppercase tracking-wider text-gray-400">Trilha de Aulas</span>
|
||||
<span className="text-xs text-orange-400 font-mono font-bold">{course.duration}</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 max-h-[600px] overflow-y-auto pr-1">
|
||||
{course.lessons.map((lesson, index) => {
|
||||
const isActive = currentLesson?.id === lesson.id;
|
||||
const isCompleted = completedLessonIds.includes(lesson.id);
|
||||
const isLocked = !user;
|
||||
const hasAttachments = lesson.attachments && lesson.attachments.length > 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={lesson.id}
|
||||
onClick={() => changeLesson(lesson)}
|
||||
className={`
|
||||
group flex items-start gap-3.5 p-3.5 rounded-xl cursor-pointer transition-all border
|
||||
${isActive
|
||||
? 'bg-orange-500/15 border-orange-500/40 text-orange-400 shadow-md shadow-orange-500/10'
|
||||
: isCompleted
|
||||
? 'bg-emerald-950/40 hover:bg-emerald-900/50 border-emerald-500/30 text-emerald-300 shadow-sm'
|
||||
: 'bg-zinc-900/80 hover:bg-zinc-800/90 border-transparent text-gray-200'
|
||||
}
|
||||
${isLocked ? 'opacity-70' : 'opacity-100'}
|
||||
`}
|
||||
>
|
||||
{/* Status Icon */}
|
||||
<div className="mt-0.5 shrink-0">
|
||||
{isActive ? (
|
||||
<div className="p-2 rounded-lg bg-orange-500 text-white shadow-md">
|
||||
<Play className="w-3.5 h-3.5 fill-white" />
|
||||
</div>
|
||||
) : isCompleted ? (
|
||||
<div className="p-2 rounded-lg bg-emerald-500 text-white shadow-md">
|
||||
<Check className="w-3.5 h-3.5 stroke-[3]" />
|
||||
</div>
|
||||
) : isLocked ? (
|
||||
<div className="p-2 rounded-lg bg-white/5 text-gray-400">
|
||||
<Lock className="w-3.5 h-3.5" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-2 rounded-lg bg-white/5 text-gray-400 font-mono text-xs font-bold w-8 h-8 flex items-center justify-center">
|
||||
{index + 1}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className={`text-xs sm:text-sm font-semibold truncate ${
|
||||
isActive
|
||||
? 'text-orange-400 font-bold'
|
||||
: isCompleted
|
||||
? 'text-emerald-300 group-hover:text-emerald-200 font-semibold'
|
||||
: 'text-gray-200 group-hover:text-white'
|
||||
}`}>
|
||||
{lesson.title}
|
||||
</h4>
|
||||
<div className="flex items-center gap-2 text-xs text-gray-400 mt-1 font-normal">
|
||||
<span>{lesson.duration}</span>
|
||||
|
||||
{isCompleted && (
|
||||
<span className="bg-emerald-500/20 text-emerald-400 px-2 py-0.5 rounded-md text-[10px] font-bold uppercase flex items-center gap-1">
|
||||
<CheckCircle2 className="w-2.5 h-2.5" /> Concluída
|
||||
</span>
|
||||
)}
|
||||
|
||||
{lesson.isFree ? (
|
||||
<span className="bg-emerald-500/15 text-emerald-400 px-2 py-0.5 rounded-md text-[10px] font-bold uppercase">Grátis</span>
|
||||
) : (
|
||||
<span className="bg-purple-500/15 text-purple-400 px-2 py-0.5 rounded-md text-[10px] font-bold uppercase">Exclusiva</span>
|
||||
)}
|
||||
{hasAttachments && (
|
||||
<span className="flex items-center gap-1 text-[10px] text-orange-400 bg-orange-500/15 px-2 py-0.5 rounded-md font-bold">
|
||||
<Paperclip className="w-2.5 h-2.5" />
|
||||
{lesson.attachments!.length} anexo(s)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* TAB CONTENT: Materials & Downloads */}
|
||||
{activeTab === 'materials' && (
|
||||
<div className="bg-zinc-950/80 rounded-2xl p-5 space-y-4 shadow-xl">
|
||||
<div className="flex items-center justify-between pb-3 border-b border-white/5">
|
||||
<div>
|
||||
<h3 className="text-sm font-bold text-white">Materiais para Download</h3>
|
||||
<p className="text-xs text-gray-400 mt-0.5">Arquivos anexados a este curso</p>
|
||||
</div>
|
||||
<span className="text-xs bg-orange-500/15 text-orange-400 font-bold px-2.5 py-1 rounded-full">
|
||||
{allCourseAttachments.length} Total
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{allCourseAttachments.length === 0 ? (
|
||||
<div className="py-12 text-center text-gray-500">
|
||||
<Download className="w-8 h-8 mx-auto mb-2 opacity-30 text-orange-400" />
|
||||
<p className="text-xs text-gray-400">Nenhum material cadastrado para este curso ainda.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3 max-h-[600px] overflow-y-auto pr-1">
|
||||
{allCourseAttachments.map((item, idx) => (
|
||||
<div key={`${item.attachment.id}-${idx}`} className="space-y-1.5">
|
||||
<span className="text-xs text-gray-400 font-semibold px-1 flex items-center gap-1.5">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-orange-500"></span>
|
||||
{item.source}
|
||||
</span>
|
||||
<MaterialCard attachment={item.attachment} compact />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* TAB CONTENT: Discussion */}
|
||||
{activeTab === 'discussion' && (
|
||||
<div className="bg-zinc-950/80 rounded-2xl p-5 flex flex-col space-y-4 shadow-xl">
|
||||
<h3 className="text-sm font-bold text-white pb-2 border-b border-white/5">Dúvidas & Comentários</h3>
|
||||
|
||||
{/* Comment Form */}
|
||||
<form onSubmit={handleAddComment} className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={newComment}
|
||||
onChange={(e) => setNewComment(e.target.value)}
|
||||
placeholder={user ? "Faça uma pergunta sobre a aula..." : "Faça login para comentar"}
|
||||
disabled={!user}
|
||||
className="flex-1 bg-zinc-900/90 rounded-xl px-3.5 py-2.5 text-xs text-white placeholder:text-gray-500 focus:outline-none focus:ring-1 focus:ring-orange-500"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!newComment.trim() || !user}
|
||||
className="p-2.5 rounded-xl bg-orange-500 hover:bg-orange-600 disabled:opacity-30 text-white transition-colors"
|
||||
>
|
||||
<Send className="w-4 h-4" />
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* Comments List */}
|
||||
<div className="space-y-3 max-h-[450px] overflow-y-auto pr-1">
|
||||
{comments.length === 0 ? (
|
||||
<p className="text-xs text-gray-500 text-center py-8">Nenhum comentário ainda. Seja o primeiro a perguntar!</p>
|
||||
) : (
|
||||
comments.map(c => (
|
||||
<div key={c.id} className="p-3 rounded-xl bg-zinc-900/90 space-y-1">
|
||||
<div className="flex items-center justify-between text-xs font-semibold">
|
||||
<span className="text-gray-200">{c.user}</span>
|
||||
<span className="text-gray-500 font-mono text-[11px]">{c.date}</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-300 font-normal leading-relaxed">{c.text}</p>
|
||||
|
||||
{c.reply && (
|
||||
<div className="mt-2 pl-3 border-l-2 border-orange-500 text-xs bg-white/[0.02] p-2 rounded-r-lg">
|
||||
<span className="font-bold text-orange-400 uppercase text-[10px]">Instrutor:</span>
|
||||
<p className="text-gray-300 text-xs mt-0.5">{c.reply}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoginModal isOpen={showLoginPrompt} onClose={() => setShowLoginPrompt(false)} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,176 +0,0 @@
|
||||
import React, { useRef, useState, useEffect, useCallback } from 'react';
|
||||
import { CourseCard } from './CourseCard';
|
||||
import { Section, Course } from '../types';
|
||||
import { ChevronRight, ChevronLeft } from 'lucide-react';
|
||||
|
||||
interface CourseRowProps {
|
||||
section: Section;
|
||||
onCourseClick?: (course: Course) => void;
|
||||
}
|
||||
|
||||
export const CourseRow: React.FC<CourseRowProps> = ({ section, onCourseClick }) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const isMouseDownRef = useRef(false);
|
||||
const startXRef = useRef(0);
|
||||
const scrollLeftRef = useRef(0);
|
||||
const draggedDistanceRef = useRef(0);
|
||||
|
||||
const [canScrollLeft, setCanScrollLeft] = useState(false);
|
||||
const [canScrollRight, setCanScrollRight] = useState(true);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
|
||||
const checkScrollBoundaries = useCallback(() => {
|
||||
if (!containerRef.current) return;
|
||||
const { scrollLeft, scrollWidth, clientWidth } = containerRef.current;
|
||||
setCanScrollLeft(scrollLeft > 20);
|
||||
setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 20);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
checkScrollBoundaries();
|
||||
window.addEventListener('resize', checkScrollBoundaries);
|
||||
return () => window.removeEventListener('resize', checkScrollBoundaries);
|
||||
}, [checkScrollBoundaries, section.courses]);
|
||||
|
||||
// Arrow button handlers
|
||||
const handleScroll = (direction: 'left' | 'right') => {
|
||||
if (!containerRef.current) return;
|
||||
const scrollAmount = containerRef.current.clientWidth * 0.75;
|
||||
containerRef.current.scrollBy({
|
||||
left: direction === 'left' ? -scrollAmount : scrollAmount,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
};
|
||||
|
||||
// Mouse Drag-to-Scroll Handlers
|
||||
const handleMouseDown = (e: React.MouseEvent) => {
|
||||
if (!containerRef.current) return;
|
||||
// Don't drag if clicking buttons or specific interactive items
|
||||
isMouseDownRef.current = true;
|
||||
startXRef.current = e.pageX - containerRef.current.offsetLeft;
|
||||
scrollLeftRef.current = containerRef.current.scrollLeft;
|
||||
draggedDistanceRef.current = 0;
|
||||
setIsDragging(false);
|
||||
};
|
||||
|
||||
const handleMouseMove = (e: React.MouseEvent) => {
|
||||
if (!isMouseDownRef.current || !containerRef.current) return;
|
||||
e.preventDefault();
|
||||
const x = e.pageX - containerRef.current.offsetLeft;
|
||||
const walk = (x - startXRef.current) * 1.5; // Drag sensitivity multiplier
|
||||
draggedDistanceRef.current = Math.abs(walk);
|
||||
|
||||
if (draggedDistanceRef.current > 6) {
|
||||
setIsDragging(true);
|
||||
containerRef.current.scrollLeft = scrollLeftRef.current - walk;
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
isMouseDownRef.current = false;
|
||||
setTimeout(() => {
|
||||
setIsDragging(false);
|
||||
draggedDistanceRef.current = 0;
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleCardClick = (course: Course) => {
|
||||
// Only trigger play/open if user wasn't dragging
|
||||
if (draggedDistanceRef.current < 10) {
|
||||
onCourseClick?.(course);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col py-6 group/row animate-fade-in-up relative select-none">
|
||||
{/* Title Header */}
|
||||
<div className="px-6 md:px-12 max-w-[1440px] w-full mx-auto mb-4 flex items-center justify-between">
|
||||
<div className="flex items-baseline gap-4 group-hover/row:text-white transition-colors duration-300">
|
||||
<h2 className="font-display text-xl sm:text-2xl md:text-2xl font-bold text-gray-100 tracking-tight">
|
||||
{section.title}
|
||||
</h2>
|
||||
<span className="text-xs font-semibold text-gray-500 uppercase tracking-wider hidden sm:inline">
|
||||
{section.courses.length} {section.courses.length === 1 ? 'curso' : 'cursos'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Inline Navigation Arrows for Desktop */}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => handleScroll('left')}
|
||||
disabled={!canScrollLeft}
|
||||
className="w-9 h-9 rounded-full bg-zinc-900/80 hover:bg-orange-500 disabled:opacity-20 disabled:hover:bg-zinc-900/80 text-white border border-white/10 flex items-center justify-center transition-all active:scale-95 shadow-lg"
|
||||
title="Rolar para a esquerda"
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleScroll('right')}
|
||||
disabled={!canScrollRight}
|
||||
className="w-9 h-9 rounded-full bg-zinc-900/80 hover:bg-orange-500 disabled:opacity-20 disabled:hover:bg-zinc-900/80 text-white border border-white/10 flex items-center justify-center transition-all active:scale-95 shadow-lg"
|
||||
title="Rolar para a direita"
|
||||
>
|
||||
<ChevronRight className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Horizontal Carousel Container */}
|
||||
<div className="relative w-full max-w-[1440px] mx-auto group/carousel">
|
||||
|
||||
{/* Floating Side Arrow Left (Hover Overlay) */}
|
||||
{canScrollLeft && (
|
||||
<button
|
||||
onClick={() => handleScroll('left')}
|
||||
className="absolute left-2 top-1/2 -translate-y-1/2 z-20 w-11 h-11 rounded-full bg-black/80 hover:bg-orange-500 text-white border border-white/20 backdrop-blur-md hidden md:flex items-center justify-center opacity-0 group-hover/carousel:opacity-100 transition-all duration-200 shadow-2xl hover:scale-110 active:scale-95"
|
||||
title="Anterior"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Scroll Container with drag-to-scroll */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={handleMouseUp}
|
||||
onScroll={checkScrollBoundaries}
|
||||
className={`flex overflow-x-auto gap-6 px-6 md:px-12 pb-8 pt-1 hide-scrollbar overscroll-x-contain scroll-smooth ${
|
||||
isDragging ? 'cursor-grabbing select-none' : 'cursor-grab'
|
||||
}`}
|
||||
style={{ scrollSnapType: isDragging ? 'none' : 'x mandatory' }}
|
||||
>
|
||||
{section.courses.map((course) => (
|
||||
<div key={course.id} className="snap-start shrink-0">
|
||||
<CourseCard
|
||||
course={course}
|
||||
variant={section.variant}
|
||||
onClick={handleCardClick}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{/* Padding at the end */}
|
||||
<div className="w-8 md:w-12 flex-none" />
|
||||
</div>
|
||||
|
||||
{/* Floating Side Arrow Right (Hover Overlay) */}
|
||||
{canScrollRight && (
|
||||
<button
|
||||
onClick={() => handleScroll('right')}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 z-20 w-11 h-11 rounded-full bg-black/80 hover:bg-orange-500 text-white border border-white/20 backdrop-blur-md hidden md:flex items-center justify-center opacity-0 group-hover/carousel:opacity-100 transition-all duration-200 shadow-2xl hover:scale-110 active:scale-95"
|
||||
title="Próximo"
|
||||
>
|
||||
<ChevronRight className="w-6 h-6" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Subtle Vignette on the right */}
|
||||
<div className="absolute top-0 bottom-0 right-0 w-16 bg-gradient-to-l from-black to-transparent pointer-events-none z-10 hidden md:block" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { ChevronLeft, ChevronRight, Play, Sparkles } from 'lucide-react';
|
||||
import { Course } from '../types';
|
||||
import { getCourses, getHomeBanners, PublicHomeBanner } from '../services/db';
|
||||
import { CourseCoverImage } from './CourseCoverImage';
|
||||
|
||||
interface HeroProps { onPlay?: (course: Course) => void; }
|
||||
|
||||
export const Hero: React.FC<HeroProps> = ({ onPlay }) => {
|
||||
const [banners, setBanners] = useState<PublicHomeBanner[]>([]);
|
||||
const [courses, setCourses] = useState<Course[]>([]);
|
||||
const [index, setIndex] = useState(0);
|
||||
useEffect(() => { Promise.all([getHomeBanners(), getCourses()]).then(([loadedBanners, loadedCourses]) => { setBanners(loadedBanners); setCourses(loadedCourses); }).catch(() => setBanners([])); }, []);
|
||||
useEffect(() => { if (banners.length < 2) return; const timer = window.setInterval(() => setIndex((current) => (current + 1) % banners.length), 7000); return () => window.clearInterval(timer); }, [banners.length]);
|
||||
const fallback = courses[0];
|
||||
const banner = banners[index];
|
||||
const course = banner?.courseId ? courses.find((item) => item.id === banner.courseId) : fallback;
|
||||
if (!banner && !fallback) return null;
|
||||
const title = banner ? (banner.kind === 'course' ? banner.courseTitle || banner.title : banner.title) : fallback.title;
|
||||
const description = banner ? (banner.kind === 'course' ? banner.courseDescription || banner.description : banner.description) : fallback.description;
|
||||
const image = banner ? (banner.kind === 'course' ? banner.courseImageUrl : banner.imageUrl) : fallback.thumbnail;
|
||||
const canPlay = Boolean(course && (banner?.kind !== 'custom' || banner.courseId));
|
||||
return <div className="relative flex h-[75vh] max-h-[800px] min-h-[560px] w-full flex-col justify-end overflow-hidden px-6 pb-12 pt-28 md:px-12"><div className="absolute inset-0">{image && <CourseCoverImage source={image} alt={title} className="h-full w-full object-cover" style={{ transform: `scale(${banner?.coverImageZoom || course?.coverImageZoom || 1})`, objectPosition: `${banner?.coverImagePositionX ?? course?.coverImagePositionX ?? 50}% ${banner?.coverImagePositionY ?? course?.coverImagePositionY ?? 50}%` }} />}<div className="absolute inset-0 bg-gradient-to-t from-black via-black/60 to-black/75" /><div className="absolute inset-0 bg-gradient-to-r from-black/95 via-black/60 to-transparent" /></div><div className="relative z-10 mx-auto w-full max-w-[1440px]"><div className="max-w-3xl"><div className="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-white/90"><span className="flex items-center gap-1 rounded-full bg-orange-500 px-3 py-1"><Sparkles className="h-3 w-3" /> Destaque</span>{banner?.kind === 'course' && <span>{course?.category}</span>}</div><h1 className="font-display text-4xl font-extrabold leading-tight tracking-tight text-white md:text-6xl">{title}</h1>{description && <p className="mt-4 max-w-2xl text-base leading-relaxed text-gray-200 md:text-lg">{description}</p>}{canPlay && <button onClick={() => onPlay?.(course!)} className="mt-7 inline-flex items-center gap-3 rounded-full bg-white px-8 py-3.5 text-sm font-bold text-black"><Play className="h-5 w-5 fill-current" /> Assistir curso</button>}</div></div>{banners.length > 1 && <div className="absolute bottom-7 right-6 z-20 flex items-center gap-3 md:right-12"><button onClick={() => setIndex((index - 1 + banners.length) % banners.length)} className="rounded-full bg-black/50 p-2 text-white"><ChevronLeft className="h-5 w-5" /></button><div className="flex gap-1.5">{banners.map((item, itemIndex) => <button key={item.id} onClick={() => setIndex(itemIndex)} className={`h-2 rounded-full transition-all ${itemIndex === index ? 'w-6 bg-orange-500' : 'w-2 bg-white/50'}`} aria-label={`Banner ${itemIndex + 1}`} />)}</div><button onClick={() => setIndex((index + 1) % banners.length)} className="rounded-full bg-black/50 p-2 text-white"><ChevronRight className="h-5 w-5" /></button></div>}</div>;
|
||||
};
|
||||
@@ -1,38 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { ArrowRight, Check, Layers3, X } from 'lucide-react';
|
||||
import { Course } from '../types';
|
||||
import { PublicLearningPath } from '../services/db';
|
||||
import { CourseCoverImage } from './CourseCoverImage';
|
||||
|
||||
interface LearningPathRowProps {
|
||||
paths: PublicLearningPath[];
|
||||
courses: Course[];
|
||||
onCourseSelect?: (course: Course) => void;
|
||||
}
|
||||
|
||||
export const LearningPathRow: React.FC<LearningPathRowProps> = ({ paths, courses, onCourseSelect }) => {
|
||||
const [selectedPath, setSelectedPath] = useState<PublicLearningPath | null>(null);
|
||||
const courseById = new Map(courses.map((course) => [course.id, course]));
|
||||
|
||||
return <>
|
||||
<section className="mx-auto w-full max-w-[1440px] px-6 py-6 md:px-12">
|
||||
<div className="mb-4 flex items-baseline gap-3">
|
||||
<h2 className="font-display text-xl font-bold text-gray-100 md:text-2xl">Trilhas</h2>
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-gray-500">{paths.length} {paths.length === 1 ? 'trilha' : 'trilhas'}</span>
|
||||
</div>
|
||||
<div className="flex gap-5 overflow-x-auto pb-4 hide-scrollbar snap-x snap-mandatory">
|
||||
{paths.map((path) => <button key={path.id} onClick={() => setSelectedPath(path)} className="group relative w-[300px] shrink-0 snap-start overflow-hidden rounded-xl border border-white/10 bg-zinc-950 text-left shadow-xl transition hover:-translate-y-1 hover:border-orange-500/60">
|
||||
<div className="relative aspect-[16/8] overflow-hidden bg-zinc-900">
|
||||
{path.coverImageUrl ? <CourseCoverImage source={path.coverImageUrl} alt={path.title} className="h-full w-full object-cover transition duration-500 group-hover:scale-105" style={{ transform: `scale(${path.coverImageZoom || 1})`, objectPosition: `${path.coverImagePositionX ?? 50}% ${path.coverImagePositionY ?? 50}%` }} /> : <div className="flex h-full items-center justify-center bg-gradient-to-br from-orange-500/30 to-zinc-900"><Layers3 className="h-9 w-9 text-orange-300" /></div>}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent" />
|
||||
<span className="absolute bottom-3 left-3 rounded-full bg-black/60 px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider text-white backdrop-blur">{path.courses.length} {path.courses.length === 1 ? 'curso' : 'cursos'}</span>
|
||||
</div>
|
||||
<div className="p-4"><h3 className="truncate font-semibold text-white group-hover:text-orange-300">{path.title}</h3><p className="mt-1 line-clamp-2 min-h-10 text-sm leading-relaxed text-gray-500">{path.description || 'Uma trilha organizada para avançar passo a passo.'}</p><span className="mt-3 inline-flex items-center gap-1 text-sm font-semibold text-orange-400">Ver trilha <ArrowRight className="h-4 w-4" /></span></div>
|
||||
</button>)}
|
||||
</div>
|
||||
</section>
|
||||
{selectedPath && <div className="fixed inset-0 z-[90] flex items-center justify-center bg-black/80 p-4 backdrop-blur-sm" role="dialog" aria-modal="true" aria-label={selectedPath.title}>
|
||||
<div className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-white/10 bg-zinc-950 shadow-2xl"><div className="flex items-start justify-between border-b border-white/10 p-6"><div><div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-orange-400"><Layers3 className="h-4 w-4" /> Formação</div><h2 className="mt-2 text-2xl font-bold text-white">{selectedPath.title}</h2><p className="mt-2 text-sm leading-relaxed text-gray-400">{selectedPath.description}</p></div><button onClick={() => setSelectedPath(null)} className="rounded-full p-2 text-gray-400 hover:bg-white/10 hover:text-white" aria-label="Fechar"><X className="h-5 w-5" /></button></div><ol className="space-y-2 p-5">{selectedPath.courses.map((pathCourse, index) => { const course = courseById.get(pathCourse.id); return <li key={pathCourse.id}><button onClick={() => { if (course) { setSelectedPath(null); onCourseSelect?.(course); } }} disabled={!course} className="flex w-full items-center gap-4 rounded-xl bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.07] disabled:cursor-default"><span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-orange-500/15 text-xs font-bold text-orange-400">{index + 1}</span><span className="min-w-0 flex-1"><span className="block truncate font-semibold text-white">{pathCourse.title}</span><span className="mt-0.5 block text-xs text-gray-500">{pathCourse.category}</span></span>{course && <span className="text-xs font-semibold text-orange-400">Abrir curso</span>}</button></li>; })}</ol><div className="border-t border-white/10 p-4 text-center text-xs text-gray-500"><Check className="mr-1 inline h-3.5 w-3.5 text-emerald-400" /> Siga os cursos nesta ordem.</div></div>
|
||||
</div>}
|
||||
</>;
|
||||
};
|
||||
@@ -1,119 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { X, Loader2, GraduationCap, School, UserPlus } from 'lucide-react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { UserRole } from '../types';
|
||||
|
||||
interface LoginModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export const LoginModal: React.FC<LoginModalProps> = ({ isOpen, onClose }) => {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [role, setRole] = useState<UserRole>('student');
|
||||
const [isRegistering, setIsRegistering] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const { login, register, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
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);
|
||||
|
||||
if (isRegistering && role === 'professor') {
|
||||
setIsSubmitting(false);
|
||||
setError('Contas de instrutor são liberadas pelo administrador da plataforma.');
|
||||
return;
|
||||
}
|
||||
|
||||
const signedInUser = isRegistering
|
||||
? await register(name, email, password)
|
||||
: await login(email, password);
|
||||
setIsSubmitting(false);
|
||||
|
||||
if (!signedInUser) {
|
||||
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;
|
||||
}
|
||||
|
||||
if (signedInUser.role !== 'superadmin' && signedInUser.role !== role) {
|
||||
logout();
|
||||
setError(role === 'professor'
|
||||
? 'Esta conta não possui acesso de instrutor.'
|
||||
: 'Esta conta possui acesso de instrutor. Selecione a opção Instrutor.');
|
||||
return;
|
||||
}
|
||||
|
||||
onClose();
|
||||
navigate(signedInUser.role === 'superadmin' ? '/admin' : signedInUser.role === 'professor' ? '/gerenciar' : '/');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
|
||||
<div className="absolute inset-0 bg-black/60 backdrop-blur-xl transition-opacity" onClick={onClose} />
|
||||
|
||||
<div className="relative w-full max-w-md bg-[#1c1c1e] rounded-[8px] shadow-xl border border-white/10 p-6 md:p-8 animate-fade-in-up">
|
||||
<button onClick={onClose} className="absolute top-5 right-5 text-white/40 hover:text-white transition-colors" aria-label="Fechar">
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="text-center mb-6">
|
||||
<h2 className="font-display text-heading-sm font-bold text-white mb-1.5 tracking-heading-sm leading-heading-sm">Compor HUB ID</h2>
|
||||
<p className="text-body-sm font-normal text-white/60 tracking-body-sm leading-body-sm">Acesse seu espaço de aprendizado e materiais</p>
|
||||
</div>
|
||||
|
||||
<div className="flex bg-black/40 p-1 rounded-[8px] mb-6 border border-white/5 relative">
|
||||
<div className={`absolute top-1 bottom-1 w-[calc(50%-4px)] bg-orange-500/20 rounded-[8px] transition-all duration-300 ease-out border border-orange-500/30 shadow-md ${role === 'student' ? 'left-1' : 'left-[calc(50%+4px)]'}`} />
|
||||
<button type="button" onClick={() => setRole('student')} className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-[8px] relative z-10 transition-colors duration-300 ${role === 'student' ? 'text-white font-semibold' : 'text-gray-400 hover:text-gray-300'}`}>
|
||||
<GraduationCap className="w-4 h-4" />
|
||||
<span className="text-body-sm font-semibold tracking-body-sm">Aluno</span>
|
||||
</button>
|
||||
<button type="button" onClick={() => setRole('professor')} className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-[8px] relative z-10 transition-colors duration-300 ${role === 'professor' ? 'text-white font-semibold' : 'text-gray-400 hover:text-gray-300'}`}>
|
||||
<School className="w-4 h-4" />
|
||||
<span className="text-body-sm font-semibold tracking-body-sm">Instrutor</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form noValidate onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="space-y-3">
|
||||
{isRegistering && <input type="text" placeholder="Seu nome" value={name} onChange={(event) => setName(event.target.value)} className="w-full bg-white/10 text-white placeholder:text-white/30 px-4 py-3 rounded-[8px] focus:outline-none focus:ring-2 focus:ring-orange-500/50 focus:bg-white/15 transition-all text-body tracking-body" autoFocus />}
|
||||
<input type="email" placeholder="Seu e-mail" value={email} onChange={(event) => setEmail(event.target.value)} className="w-full bg-white/10 text-white placeholder:text-white/30 px-4 py-3 rounded-[8px] focus:outline-none focus:ring-2 focus:ring-orange-500/50 focus:bg-white/15 transition-all text-body tracking-body" autoFocus={!isRegistering} />
|
||||
<input type="password" placeholder="Sua senha" value={password} onChange={(event) => setPassword(event.target.value)} className="w-full bg-white/10 text-white placeholder:text-white/30 px-4 py-3 rounded-[8px] focus:outline-none focus:ring-2 focus:ring-orange-500/50 focus:bg-white/15 transition-all text-body tracking-body" />
|
||||
</div>
|
||||
|
||||
{error && <div className="bg-red-500/10 border border-red-500/20 rounded-[8px] p-3"><p className="text-red-400 text-caption font-semibold tracking-caption text-center">{error}</p></div>}
|
||||
|
||||
<button type="submit" disabled={isSubmitting} className="w-full bg-white text-black text-body-sm font-semibold tracking-body-sm py-3.5 rounded-[980px] hover:bg-gray-200 active:scale-95 transition-all duration-200 flex items-center justify-center gap-2 shadow-xl">
|
||||
{isSubmitting ? <Loader2 className="w-5 h-5 animate-spin" /> : isRegistering ? <UserPlus className="w-5 h-5" /> : null}
|
||||
{isRegistering ? 'Criar conta' : 'Entrar'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<button type="button" onClick={() => { setIsRegistering((value) => !value); setError(''); }} className="w-full mt-5 text-xs text-orange-400 hover:text-orange-300 transition-colors">
|
||||
{isRegistering ? 'Já possui conta? Entrar' : 'Não possui conta? Criar acesso de aluno'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
File diff suppressed because one or more lines are too long
@@ -1,16 +1,16 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
FileText,
|
||||
FileSpreadsheet,
|
||||
FileArchive,
|
||||
FileCode,
|
||||
Image as ImageIcon,
|
||||
Link as LinkIcon,
|
||||
Download,
|
||||
ExternalLink,
|
||||
CheckCircle2,
|
||||
Paperclip
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
FileTextIcon as FileText,
|
||||
FileXlsIcon as FileSpreadsheet,
|
||||
FileArchiveIcon as FileArchive,
|
||||
FileCodeIcon as FileCode,
|
||||
ImageIcon as ImageIcon,
|
||||
LinkIcon as LinkIcon,
|
||||
DownloadSimpleIcon as Download,
|
||||
ArrowSquareOutIcon as ExternalLink,
|
||||
CheckCircleIcon as CheckCircle2,
|
||||
PaperclipIcon as Paperclip
|
||||
} from '@phosphor-icons/react';
|
||||
import { Attachment, AttachmentType } from '../types';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { downloadCourseAsset } from '../services/api';
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Download,
|
||||
Search,
|
||||
Filter,
|
||||
FileText,
|
||||
FileSpreadsheet,
|
||||
FileArchive,
|
||||
FileCode,
|
||||
Sparkles,
|
||||
ExternalLink,
|
||||
BookOpen,
|
||||
Layers
|
||||
} from 'lucide-react';
|
||||
import { Course, Attachment, AttachmentType } from '../types';
|
||||
import { MaterialCard } from './MaterialCard';
|
||||
|
||||
interface MaterialsHubModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
courses: Course[];
|
||||
onSelectCourse?: (course: Course) => void;
|
||||
}
|
||||
|
||||
export const MaterialsHubModal: React.FC<MaterialsHubModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
courses,
|
||||
onSelectCourse,
|
||||
}) => {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [selectedType, setSelectedType] = useState<string>('all');
|
||||
const [selectedCategory, setSelectedCategory] = useState<string>('all');
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
// Aggregate all materials across all courses and lessons
|
||||
const allMaterials: Array<{ attachment: Attachment; course: Course; lessonTitle?: string }> = [];
|
||||
|
||||
courses.forEach(course => {
|
||||
// Global course attachments
|
||||
if (course.attachments && course.attachments.length > 0) {
|
||||
course.attachments.forEach(att => {
|
||||
allMaterials.push({ attachment: att, course });
|
||||
});
|
||||
}
|
||||
|
||||
// Lesson specific attachments
|
||||
if (course.lessons) {
|
||||
course.lessons.forEach(lesson => {
|
||||
if (lesson.attachments && lesson.attachments.length > 0) {
|
||||
lesson.attachments.forEach(att => {
|
||||
allMaterials.push({ attachment: att, course, lessonTitle: lesson.title });
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Filtered materials
|
||||
const filtered = allMaterials.filter(item => {
|
||||
const matchesSearch =
|
||||
item.attachment.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
item.course.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
(item.attachment.description && item.attachment.description.toLowerCase().includes(searchTerm.toLowerCase()));
|
||||
|
||||
const matchesType = selectedType === 'all' || item.attachment.type === selectedType;
|
||||
const matchesCategory = selectedCategory === 'all' || item.course.category === selectedCategory;
|
||||
|
||||
return matchesSearch && matchesType && matchesCategory;
|
||||
});
|
||||
|
||||
const categories = Array.from(new Set(courses.map(c => c.category)));
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[120] bg-black/80 backdrop-blur-xl flex items-center justify-center p-4 md:p-8 animate-fade-in-up">
|
||||
<div className="bg-[#101012] border border-white/10 rounded-[8px] w-full max-w-6xl max-h-[90vh] flex flex-col shadow-xl overflow-hidden">
|
||||
|
||||
{/* Header */}
|
||||
<div className="p-6 md:p-8 border-b border-white/10 flex flex-col md:flex-row md:items-center justify-between gap-6 bg-gradient-to-r from-orange-950/20 via-black to-black">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-caption font-semibold uppercase tracking-caption text-orange-400 mb-2">
|
||||
<Sparkles className="w-4 h-4" />
|
||||
<span>Central de Recursos & Downloads</span>
|
||||
</div>
|
||||
<h2 className="font-display text-subheading md:text-heading-sm font-bold text-white tracking-heading-sm leading-heading-sm">
|
||||
Biblioteca de Materiais Complementares
|
||||
</h2>
|
||||
<p className="text-body-sm font-normal text-gray-400 mt-1 leading-body-sm tracking-body-sm">
|
||||
Baixe planilhas, modelos, e-books, checklists e PDFs de todos os cursos do Compor HUB.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="self-end md:self-center px-5 py-2.5 rounded-[980px] bg-white/10 hover:bg-white/20 text-white text-body-sm font-semibold tracking-body-sm transition-all shadow-xl"
|
||||
>
|
||||
Fechar
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters and Search Bar */}
|
||||
<div className="p-6 border-b border-white/5 bg-[#141417] space-y-4">
|
||||
<div className="flex flex-col md:flex-row gap-4 items-stretch md:items-center justify-between">
|
||||
{/* Search Input */}
|
||||
<div className="relative flex-1">
|
||||
<Search className="w-5 h-5 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
placeholder="Pesquisar material por nome, curso ou palavra-chave..."
|
||||
className="w-full bg-black/60 border border-white/10 rounded-[8px] pl-12 pr-4 py-3 text-body-sm text-white placeholder:text-gray-500 focus:outline-none focus:border-orange-500/50 focus:ring-1 focus:ring-orange-500/50 transition-all"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Type Filters Pills */}
|
||||
<div className="flex items-center gap-2 overflow-x-auto pb-1 md:pb-0 hide-scrollbar">
|
||||
{[
|
||||
{ id: 'all', label: 'Todos' },
|
||||
{ id: 'pdf', label: 'PDFs' },
|
||||
{ id: 'spreadsheet', label: 'Planilhas' },
|
||||
{ id: 'zip', label: 'Pacotes ZIP' },
|
||||
{ id: 'doc', label: 'Documentos' },
|
||||
{ id: 'link', label: 'Links' },
|
||||
].map(t => (
|
||||
<button
|
||||
key={t.id}
|
||||
onClick={() => setSelectedType(t.id)}
|
||||
className={`px-4 py-2 rounded-[980px] text-body-sm font-semibold tracking-body-sm whitespace-nowrap transition-all ${
|
||||
selectedType === t.id
|
||||
? 'bg-orange-500 text-white shadow-xl shadow-orange-500/20'
|
||||
: 'bg-white/5 text-gray-400 hover:bg-white/10 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Filter */}
|
||||
<div className="flex items-center gap-2 flex-wrap text-caption font-semibold tracking-caption text-gray-400 pt-1">
|
||||
<span className="text-gray-300 flex items-center gap-1.5 mr-1">
|
||||
<Filter className="w-3.5 h-3.5 text-orange-400" /> Categoria:
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setSelectedCategory('all')}
|
||||
className={`px-3 py-1 rounded-[980px] transition-colors ${
|
||||
selectedCategory === 'all' ? 'bg-white/20 text-white' : 'hover:text-white'
|
||||
}`}
|
||||
>
|
||||
Todas ({allMaterials.length})
|
||||
</button>
|
||||
{categories.map(cat => {
|
||||
const count = allMaterials.filter(m => m.course.category === cat).length;
|
||||
return (
|
||||
<button
|
||||
key={cat}
|
||||
onClick={() => setSelectedCategory(cat)}
|
||||
className={`px-3 py-1 rounded-[980px] transition-colors ${
|
||||
selectedCategory === cat ? 'bg-white/20 text-white' : 'hover:text-white'
|
||||
}`}
|
||||
>
|
||||
{cat} ({count})
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Material Cards Grid */}
|
||||
<div className="flex-1 overflow-y-auto p-6 md:p-8 space-y-6">
|
||||
{filtered.length === 0 ? (
|
||||
<div className="py-20 text-center text-gray-500">
|
||||
<Download className="w-12 h-12 mx-auto mb-3 opacity-30 text-orange-400" />
|
||||
<p className="text-body font-semibold text-gray-400">Nenhum material encontrado</p>
|
||||
<p className="text-caption text-gray-600 mt-1">Tente ajustar seus termos de pesquisa ou filtros.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{filtered.map((item, index) => (
|
||||
<div key={`${item.attachment.id}-${index}`} className="flex flex-col">
|
||||
{/* Context Badge: Which Course / Lesson */}
|
||||
<div className="flex items-center justify-between text-caption font-semibold tracking-caption text-gray-400 mb-2 px-1">
|
||||
<span
|
||||
onClick={() => {
|
||||
onClose();
|
||||
onSelectCourse?.(item.course);
|
||||
}}
|
||||
className="hover:text-orange-400 cursor-pointer truncate flex items-center gap-1.5"
|
||||
>
|
||||
<BookOpen className="w-3.5 h-3.5 text-orange-500/80" />
|
||||
{item.course.title}
|
||||
</span>
|
||||
{item.lessonTitle && (
|
||||
<span className="text-gray-500 truncate max-w-[120px] font-normal" title={item.lessonTitle}>
|
||||
{item.lessonTitle}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<MaterialCard attachment={item.attachment} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer info */}
|
||||
<div className="p-4 px-8 border-t border-white/5 bg-[#0a0a0c] flex items-center justify-between text-caption font-semibold tracking-caption text-gray-500">
|
||||
<span>{filtered.length} materiais disponíveis para download</span>
|
||||
<span>Compor HUB • Materiais Exclusivos</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,143 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { User as UserIcon, LogOut, Search, Folder, BookOpenCheck, ChevronDown, ShieldCheck, Settings, UserRound } from 'lucide-react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { LoginModal } from './LoginModal';
|
||||
import { SearchModal } from './SearchModal';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import { Course } from '../types';
|
||||
import { Logo } from './Logo';
|
||||
|
||||
interface NavbarProps {
|
||||
onPlay: (course: Course) => void;
|
||||
}
|
||||
|
||||
export const Navbar: React.FC<NavbarProps> = ({ onPlay }) => {
|
||||
const [scrolled, setScrolled] = useState(false);
|
||||
const [showLoginModal, setShowLoginModal] = useState(false);
|
||||
const [showSearchModal, setShowSearchModal] = useState(false);
|
||||
const [showAccountMenu, setShowAccountMenu] = useState(false);
|
||||
const { user, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
setScrolled(window.scrollY > 20);
|
||||
};
|
||||
window.addEventListener('scroll', handleScroll);
|
||||
return () => window.removeEventListener('scroll', handleScroll);
|
||||
}, []);
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
const isMaterialsPage = location.pathname === '/materiais';
|
||||
const isHomePage = location.pathname === '/';
|
||||
const goTo = (path: string) => {
|
||||
setShowAccountMenu(false);
|
||||
navigate(path);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<nav
|
||||
className={`fixed top-0 left-0 right-0 z-50 transition-all duration-500 ease-in-out px-6 md:px-12 py-4 ${
|
||||
scrolled || location.pathname !== '/'
|
||||
? 'bg-[#09090b]/95 backdrop-blur-xl shadow-2xl shadow-black/80'
|
||||
: 'bg-transparent bg-gradient-to-b from-black/90 via-black/40 to-transparent'
|
||||
}`}
|
||||
>
|
||||
<div className="max-w-[1440px] mx-auto flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-6 md:gap-8">
|
||||
<div
|
||||
className="flex items-center gap-2 group cursor-pointer"
|
||||
onClick={() => navigate('/')}
|
||||
>
|
||||
<Logo variant="dark" size="lg" />
|
||||
</div>
|
||||
|
||||
{/* Quick Navigation Links */}
|
||||
<div className="hidden md:flex items-center gap-2 text-sm font-medium">
|
||||
<button
|
||||
onClick={() => navigate('/')}
|
||||
className={`px-4 py-2 rounded-[980px] transition-colors ${
|
||||
isHomePage
|
||||
? 'text-white bg-white/10 font-semibold'
|
||||
: 'text-gray-400 hover:text-white hover:bg-white/5'
|
||||
}`}
|
||||
>
|
||||
Cursos
|
||||
</button>
|
||||
<button
|
||||
onClick={() => navigate('/materiais')}
|
||||
className={`px-4 py-2 rounded-[980px] transition-colors flex items-center gap-2 ${
|
||||
isMaterialsPage
|
||||
? 'text-orange-400 bg-orange-500/15 font-semibold border border-orange-500/30'
|
||||
: 'text-gray-400 hover:text-orange-400 hover:bg-white/5'
|
||||
}`}
|
||||
>
|
||||
<Folder className="w-4 h-4 text-orange-400" />
|
||||
<span>Biblioteca de Materiais</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 sm:gap-4">
|
||||
|
||||
{/* Search */}
|
||||
<button
|
||||
onClick={() => setShowSearchModal(true)}
|
||||
className="text-gray-300 hover:text-white text-sm font-medium transition-colors flex items-center gap-2 px-3.5 py-2.5 rounded-[980px] hover:bg-white/10 border border-transparent hover:border-white/10"
|
||||
>
|
||||
<Search className="w-4 h-4" />
|
||||
<span className="hidden lg:inline">Buscar</span>
|
||||
</button>
|
||||
|
||||
{!user ? (
|
||||
<button
|
||||
onClick={() => setShowLoginModal(true)}
|
||||
className="flex items-center gap-2.5 bg-orange-500 hover:bg-orange-600 active:scale-95 transition-all duration-300 px-6 py-2.5 rounded-[980px] text-sm font-bold text-white shadow-xl shadow-orange-500/25 shrink-0"
|
||||
>
|
||||
<UserIcon className="w-4 h-4 text-white" />
|
||||
<span>Entrar</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative">
|
||||
<button onClick={() => setShowAccountMenu((current) => !current)} className="flex items-center gap-2 rounded-[980px] px-3 py-2 text-sm text-gray-300 hover:bg-white/10 hover:text-white transition-colors" aria-expanded={showAccountMenu} aria-haspopup="menu">
|
||||
<span className="hidden md:block">Olá, <strong className="font-semibold text-white">{user.name.split(' ')[0]}</strong></span>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${showAccountMenu ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
{showAccountMenu && <div role="menu" className="absolute right-0 top-full mt-2 w-56 overflow-hidden rounded-xl border border-white/10 bg-zinc-950 p-1.5 shadow-2xl shadow-black/60">
|
||||
<button role="menuitem" onClick={() => goTo('/perfil')} className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2.5 text-left text-sm text-gray-200 hover:bg-white/10"><UserRound className="h-4 w-4 text-orange-400" /> Meu perfil</button>
|
||||
{user.role === 'student' && <button role="menuitem" onClick={() => goTo('/meu-aprendizado')} className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2.5 text-left text-sm text-gray-200 hover:bg-white/10"><BookOpenCheck className="h-4 w-4 text-orange-400" /> Meu aprendizado</button>}
|
||||
{user.role === 'professor' && <button role="menuitem" onClick={() => goTo('/gerenciar')} className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2.5 text-left text-sm text-gray-200 hover:bg-white/10"><Settings className="h-4 w-4 text-orange-400" /> Painel do instrutor</button>}
|
||||
{user.role === 'superadmin' && <><button role="menuitem" onClick={() => goTo('/admin')} className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2.5 text-left text-sm text-gray-200 hover:bg-white/10"><ShieldCheck className="h-4 w-4 text-orange-400" /> Painel administrativo</button><button role="menuitem" onClick={() => goTo('/gerenciar')} className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2.5 text-left text-sm text-gray-200 hover:bg-white/10"><Settings className="h-4 w-4 text-orange-400" /> Gerenciar cursos</button></>}
|
||||
</div>}
|
||||
</div>
|
||||
|
||||
<div className="h-4 w-[1px] bg-white/20 hidden sm:block"></div>
|
||||
|
||||
<div className="flex items-center gap-2.5">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="flex items-center gap-2 bg-red-500/10 hover:bg-red-500/20 active:scale-95 transition-all duration-300 px-4 py-2 rounded-[980px] border border-red-500/20 group text-xs font-semibold text-red-400"
|
||||
title="Encerrar Sessão"
|
||||
>
|
||||
<LogOut className="w-3.5 h-3.5" />
|
||||
<span className="hidden sm:inline">Sair</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<LoginModal isOpen={showLoginModal} onClose={() => setShowLoginModal(false)} />
|
||||
<SearchModal isOpen={showSearchModal} onClose={() => setShowSearchModal(false)} onPlay={onPlay} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,175 +0,0 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Search, X, Loader2, PlayCircle, Download } from 'lucide-react';
|
||||
import { Course } from '../types';
|
||||
import { getCourses } from '../services/db';
|
||||
import { CourseCoverImage } from './CourseCoverImage';
|
||||
|
||||
interface SearchModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onPlay: (course: Course) => void;
|
||||
}
|
||||
|
||||
export const SearchModal: React.FC<SearchModalProps> = ({ isOpen, onClose, onPlay }) => {
|
||||
const [query, setQuery] = useState('');
|
||||
const [allCourses, setAllCourses] = useState<Course[]>([]);
|
||||
const [results, setResults] = useState<Course[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Load courses on mount
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
const courses = await getCourses();
|
||||
setAllCourses(courses);
|
||||
setLoading(false);
|
||||
};
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
// Focus input when opened
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setTimeout(() => {
|
||||
inputRef.current?.focus();
|
||||
}, 100);
|
||||
document.body.style.overflow = 'hidden';
|
||||
} else {
|
||||
document.body.style.overflow = 'unset';
|
||||
}
|
||||
return () => { document.body.style.overflow = 'unset'; };
|
||||
}, [isOpen]);
|
||||
|
||||
// Filter logic across Title, Category, Instructor and Materials
|
||||
useEffect(() => {
|
||||
if (!query.trim()) {
|
||||
setResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
const filtered = allCourses.filter(c => {
|
||||
const matchesTitle = c.title.toLowerCase().includes(lowerQuery);
|
||||
const matchesCat = c.category.toLowerCase().includes(lowerQuery);
|
||||
const matchesInstructor = c.instructor?.toLowerCase().includes(lowerQuery);
|
||||
const matchesLessons = c.lessons.some(l => l.title.toLowerCase().includes(lowerQuery));
|
||||
const matchesAttachments = c.attachments?.some(a => a.name.toLowerCase().includes(lowerQuery));
|
||||
|
||||
return matchesTitle || matchesCat || matchesInstructor || matchesLessons || matchesAttachments;
|
||||
});
|
||||
setResults(filtered);
|
||||
}, [query, allCourses]);
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] bg-[#0a0a0c]/95 backdrop-blur-xl animate-fade-in-up flex flex-col">
|
||||
{/* Header / Search Input */}
|
||||
<div className="pt-20 px-6 md:px-12 pb-6 border-b border-white/10 relative">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-6 right-6 md:right-12 p-2.5 bg-white/10 hover:bg-white/20 rounded-[980px] text-white transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="max-w-[1440px] mx-auto w-full">
|
||||
<div className="flex items-center gap-4">
|
||||
<Search className="w-7 h-7 text-orange-400 shrink-0" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Buscar por cursos, aulas, instrutor ou materiais..."
|
||||
className="w-full bg-transparent font-display text-2xl md:text-heading font-bold text-white placeholder:text-gray-600 focus:outline-none tracking-heading leading-heading"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Results Area */}
|
||||
<div className="flex-1 overflow-y-auto px-6 md:px-12 py-8">
|
||||
<div className="max-w-[1440px] mx-auto">
|
||||
{loading ? (
|
||||
<div className="flex justify-center mt-20">
|
||||
<Loader2 className="w-10 h-10 text-orange-500 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{!query && (
|
||||
<div className="text-center mt-20 opacity-40 space-y-2">
|
||||
<p className="font-display text-subheading font-normal text-gray-300 tracking-subheading leading-subheading">Digite um termo para pesquisar cursos ou arquivos</p>
|
||||
<p className="text-caption font-normal text-gray-500 tracking-caption">Ex: Meta Ads, ROAS, Planilha, Criativos, Funil</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{query && results.length === 0 && (
|
||||
<div className="text-center mt-20">
|
||||
<p className="text-body font-normal text-gray-400 tracking-body">Nenhum curso ou material encontrado para "{query}"</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{results.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-gray-400 font-semibold mb-6 uppercase tracking-caption text-caption flex items-center gap-2">
|
||||
<span className="w-2 h-2 rounded-[980px] bg-orange-500"></span>
|
||||
{results.length} Curso{results.length !== 1 ? 's' : ''} Encontrado{results.length !== 1 ? 's' : ''}
|
||||
</h3>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
|
||||
{results.map(course => {
|
||||
const matCount = (course.attachments?.length || 0) + course.lessons.reduce((acc, l) => acc + (l.attachments?.length || 0), 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={course.id}
|
||||
onClick={() => { onPlay(course); onClose(); }}
|
||||
className="cursor-pointer group bg-zinc-900/60 rounded-[8px] p-3 border border-white/5 hover:border-orange-500/40 transition-all duration-300 shadow-xl"
|
||||
>
|
||||
<div className="aspect-video bg-gray-900 rounded-[8px] overflow-hidden mb-3 relative">
|
||||
<CourseCoverImage
|
||||
source={course.thumbnail}
|
||||
alt={course.title}
|
||||
className="w-full h-full object-cover opacity-80 group-hover:opacity-100 group-hover:scale-105 transition-all duration-300 rounded-[8px]"
|
||||
style={{
|
||||
transform: `scale(${course.coverImageZoom || 1})`,
|
||||
objectPosition: `${course.coverImagePositionX ?? 50}% ${course.coverImagePositionY ?? 50}%`,
|
||||
}}
|
||||
/>
|
||||
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/40">
|
||||
<PlayCircle className="w-10 h-10 text-orange-500" />
|
||||
</div>
|
||||
{matCount > 0 && (
|
||||
<div className="absolute bottom-2 right-2 bg-black/70 backdrop-blur-md px-2 py-0.5 rounded-[980px] text-caption font-semibold text-orange-400 border border-orange-500/30 flex items-center gap-1">
|
||||
<Download className="w-2.5 h-2.5" />
|
||||
{matCount}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h4 className="text-white font-semibold text-body-sm truncate group-hover:text-orange-400 transition-colors leading-body-sm tracking-body-sm">
|
||||
{course.title}
|
||||
</h4>
|
||||
<div className="flex items-center justify-between text-caption font-normal tracking-caption text-gray-500 mt-1">
|
||||
<span className="truncate">{course.category}</span>
|
||||
<span>{course.duration}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,8 +1,19 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Copy, Download, KeyRound, Loader2, Pencil, Plus, Trash2, UserCheck, UserX, X } from 'lucide-react';
|
||||
import {
|
||||
CopyIcon as Copy,
|
||||
DownloadSimpleIcon as Download,
|
||||
KeyIcon as KeyRound,
|
||||
CircleNotchIcon as Loader2,
|
||||
PencilIcon as Pencil,
|
||||
PlusIcon as Plus,
|
||||
TrashIcon as Trash2,
|
||||
UserCheckIcon as UserCheck,
|
||||
UserMinusIcon as UserX,
|
||||
XIcon as X
|
||||
} from '@phosphor-icons/react';
|
||||
import { ManagedUser } from '../services/api';
|
||||
|
||||
const roleLabel: Record<ManagedUser['role'], string> = { admin: 'Superadmin', instructor: 'Instrutor', student: 'Aluno' };
|
||||
const roleLabel: Record<ManagedUser['role'], string> = { admin: 'Admin', instructor: 'Instrutor', student: 'Aluno' };
|
||||
const inputClass = 'w-full rounded-xl border border-white/10 bg-zinc-900 px-3 py-2.5 text-sm text-white outline-none focus:border-orange-500/70 focus:ring-2 focus:ring-orange-500/15';
|
||||
|
||||
type Props = {
|
||||
|
||||
115
components/admin/BannerManager.tsx
Normal file
115
components/admin/BannerManager.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { adminApi, HomeBanner } from '../../services/api';
|
||||
import { instructorApi } from '../../services/api';
|
||||
import { useToast } from '../../context/ToastContext';
|
||||
import { CourseCoverImage } from '../CourseCoverImage';
|
||||
import { Select } from '../ui/Select';
|
||||
import { ArrowDownIcon, ArrowUpIcon, PlusIcon, TrashIcon } from '@phosphor-icons/react';
|
||||
import { PlusMockIcon } from '../ui/MockupIcons';
|
||||
|
||||
type CourseOption = { id: string; title: string; category: string; coverImageUrl: string | null };
|
||||
|
||||
export const BannerManager: React.FC<{ courses: CourseOption[]; onChanged?: () => void }> = ({ courses, onChanged }) => {
|
||||
const { showToast } = useToast();
|
||||
const [banners, setBanners] = useState<HomeBanner[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [kind, setKind] = useState<'course' | 'custom'>('course');
|
||||
const [courseId, setCourseId] = useState('');
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [imageUrl, setImageUrl] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [coverConfigured, setCoverConfigured] = useState(false);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
adminApi.homeBanners().then((response) => setBanners(response.data)).catch(() => showToast('Não foi possível carregar os banners.', 'error')).finally(() => setLoading(false));
|
||||
instructorApi.coverConfiguration().then((response) => setCoverConfigured(response.data.configured)).catch(() => setCoverConfigured(false));
|
||||
}, []);
|
||||
|
||||
const persist = async (next: HomeBanner[]) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const response = await adminApi.updateHomeBanners(next.map(({ kind: bannerKind, courseId: bannerCourseId, imageUrl: bannerImage, title: bannerTitle, description: bannerDescription }) => ({ kind: bannerKind, courseId: bannerCourseId, imageUrl: bannerImage, title: bannerTitle, description: bannerDescription })));
|
||||
setBanners(response.data);
|
||||
showToast('Banners atualizados.', 'success');
|
||||
onChanged?.();
|
||||
} catch {
|
||||
showToast('Não foi possível salvar os banners.', 'error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const upload = async (file?: File) => {
|
||||
if (!file) return;
|
||||
if (!coverConfigured) { showToast('O envio de imagens ainda não está configurado.', 'error'); return; }
|
||||
setUploading(true);
|
||||
try {
|
||||
const response = await instructorApi.uploadCover(file);
|
||||
setImageUrl(response.data.coverImageUrl);
|
||||
} catch {
|
||||
showToast('Não foi possível enviar a imagem.', 'error');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const add = () => {
|
||||
if (kind === 'course' && !courseId) { showToast('Selecione um curso para o banner.', 'error'); return; }
|
||||
if (kind === 'custom' && !imageUrl) { showToast('Envie uma imagem para o banner.', 'error'); return; }
|
||||
const next: HomeBanner[] = [...banners, {
|
||||
id: `banner-${Date.now()}`,
|
||||
kind,
|
||||
courseId: kind === 'course' ? courseId : null,
|
||||
imageUrl: kind === 'custom' ? imageUrl : null,
|
||||
title,
|
||||
description,
|
||||
position: banners.length + 1,
|
||||
courseTitle: kind === 'course' ? courses.find((course) => course.id === courseId)?.title || null : null,
|
||||
courseDescription: null,
|
||||
courseImageUrl: kind === 'course' ? courses.find((course) => course.id === courseId)?.coverImageUrl || null : null,
|
||||
}];
|
||||
setKind('course');
|
||||
setCourseId('');
|
||||
setTitle('');
|
||||
setDescription('');
|
||||
setImageUrl('');
|
||||
void persist(next);
|
||||
};
|
||||
|
||||
const move = (index: number, direction: -1 | 1) => {
|
||||
const target = index + direction;
|
||||
if (target < 0 || target >= banners.length) return;
|
||||
const next = [...banners];
|
||||
[next[index], next[target]] = [next[target], next[index]];
|
||||
setBanners(next);
|
||||
void persist(next);
|
||||
};
|
||||
|
||||
if (loading) return <div className="loading">Carregando banners…</div>;
|
||||
|
||||
return <>
|
||||
<div className="box" style={{ marginBottom: 24 }}>
|
||||
<h3>Novo banner</h3>
|
||||
<div className="form" style={{ marginTop: 16 }}>
|
||||
<div className="field"><label>Tipo</label><Select variant="field" value={kind} options={[{ value: 'course', label: 'Curso publicado' }, { value: 'custom', label: 'Imagem personalizada' }]} onChange={(value) => setKind(value as 'course' | 'custom')} ariaLabel="Tipo do banner" /></div>
|
||||
{kind === 'course' ? <div className="field"><label>Curso</label><Select variant="field" value={courseId} options={[{ value: '', label: 'Selecione um curso' }, ...courses.map((course) => ({ value: course.id, label: course.title }))]} onChange={setCourseId} ariaLabel="Curso do banner" /></div> : <>
|
||||
<div className="field"><label>Imagem</label><div style={{ display: 'flex', alignItems: 'center', gap: 12 }}><button className="btn sec" type="button" disabled={!coverConfigured || uploading} onClick={() => fileInput.current?.click()}><PlusMockIcon className="ph" /> {uploading ? 'Enviando…' : 'Enviar imagem'}</button>{imageUrl && <CourseCoverImage source={imageUrl} alt="" style={{ width: 96, height: 54, borderRadius: 8, objectFit: 'cover' }} />}</div><input ref={fileInput} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={(event) => { const file = event.target.files?.[0]; event.currentTarget.value = ''; void upload(file); }} /></div>
|
||||
{!coverConfigured && <p className="muted" style={{ fontSize: 12 }}>O armazenamento de imagens ainda não está configurado.</p>}
|
||||
</>}
|
||||
<div className="field"><label>Título (opcional)</label><input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Título do banner" /></div>
|
||||
<div className="field"><label>Descrição (opcional)</label><input value={description} onChange={(event) => setDescription(event.target.value)} placeholder="Descrição do banner" /></div>
|
||||
<button className="btn" type="button" onClick={add} disabled={saving}><PlusIcon className="ph" /> Adicionar banner</button>
|
||||
</div>
|
||||
</div>
|
||||
{banners.length ? <div className="list">{banners.map((banner, index) => <div className="row" key={banner.id} style={{ gridTemplateColumns: '96px minmax(0, 1fr) auto' }}>
|
||||
<span style={{ width: 96, height: 54, borderRadius: 8, overflow: 'hidden', background: 'var(--bg-2)', display: 'block' }}>
|
||||
{(banner.imageUrl || banner.courseImageUrl) ? <CourseCoverImage source={banner.imageUrl || banner.courseImageUrl || ''} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : null}
|
||||
</span>
|
||||
<span className="t">{banner.kind === 'course' ? banner.courseTitle || 'Curso' : banner.title || 'Banner personalizado'}<small>{banner.kind === 'course' ? 'Capa do curso' : 'Imagem enviada'}</small></span>
|
||||
<span style={{ display: 'flex', gap: 4 }}><button className="iconbtn" type="button" disabled={index === 0} onClick={() => move(index, -1)} aria-label="Mover banner para cima"><ArrowUpIcon className="ph" /></button><button className="iconbtn" type="button" disabled={index === banners.length - 1} onClick={() => move(index, 1)} aria-label="Mover banner para baixo"><ArrowDownIcon className="ph" /></button><button className="iconbtn" type="button" onClick={() => void persist(banners.filter((item) => item.id !== banner.id))} aria-label="Remover banner"><TrashIcon className="ph" /></button></span>
|
||||
</div>)}</div> : <p className="empty">Nenhum banner configurado. A home usa o primeiro curso como destaque.</p>}
|
||||
</>;
|
||||
};
|
||||
66
components/admin/CategoryManager.tsx
Normal file
66
components/admin/CategoryManager.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { adminApi } from '../../services/api';
|
||||
import { useToast } from '../../context/ToastContext';
|
||||
import { Switch } from '../ui/Switch';
|
||||
import { PlusMockIcon } from '../ui/MockupIcons';
|
||||
|
||||
type Category = { id: string; name: string; position: number; isActive: boolean };
|
||||
|
||||
const CategoryRow: React.FC<{ category: Category; onSave: (category: Category, update: { name: string; isActive: boolean }) => Promise<void> }> = ({ category, onSave }) => {
|
||||
const [name, setName] = useState(category.name);
|
||||
useEffect(() => setName(category.name), [category.name]);
|
||||
const dirty = name.trim() !== category.name && name.trim().length > 0;
|
||||
return <div className="row" style={{ gridTemplateColumns: 'minmax(0, 1fr) auto auto' }}>
|
||||
<input className="input" style={{ height: 40, fontSize: 15 }} value={name} onChange={(event) => setName(event.target.value)} aria-label={`Nome da categoria ${category.name}`} />
|
||||
{dirty ? <button className="btn sec" type="button" onClick={() => void onSave(category, { name: name.trim(), isActive: category.isActive })}>Salvar</button> : <span />}
|
||||
<Switch checked={category.isActive} onChange={(checked) => void onSave(category, { name: name.trim() || category.name, isActive: checked })} label={`Categoria ${category.name} ativa`} />
|
||||
</div>;
|
||||
};
|
||||
|
||||
export const CategoryManager: React.FC<{ onChanged?: () => void }> = ({ onChanged }) => {
|
||||
const { showToast } = useToast();
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [newName, setNewName] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
adminApi.categories().then((response) => setCategories(response.data)).catch(() => showToast('Não foi possível carregar as categorias.', 'error')).finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const create = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!newName.trim()) return;
|
||||
try {
|
||||
const response = await adminApi.createCategory(newName.trim());
|
||||
setCategories((current) => [...current, response.data].sort((a, b) => a.position - b.position || a.name.localeCompare(b.name)));
|
||||
setNewName('');
|
||||
showToast('Categoria criada.', 'success');
|
||||
onChanged?.();
|
||||
} catch {
|
||||
showToast('Não foi possível criar a categoria. Ela pode já existir.', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const save = async (category: Category, update: { name: string; isActive: boolean }) => {
|
||||
try {
|
||||
const response = await adminApi.updateCategory(category.id, update);
|
||||
setCategories((current) => current.map((item) => item.id === category.id ? response.data : item));
|
||||
showToast('Categoria atualizada.', 'success');
|
||||
onChanged?.();
|
||||
} catch {
|
||||
showToast('Não foi possível atualizar a categoria.', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="loading">Carregando categorias…</div>;
|
||||
|
||||
return <>
|
||||
<form className="toolbar" onSubmit={create}>
|
||||
<input className="input" style={{ flex: 1, minWidth: 220 }} value={newName} onChange={(event) => setNewName(event.target.value)} placeholder="Nome da categoria" aria-label="Nova categoria" />
|
||||
<button className="btn" type="submit" disabled={!newName.trim()}><PlusMockIcon className="ph" /> Adicionar categoria</button>
|
||||
</form>
|
||||
<p className="muted" style={{ marginBottom: 12 }}>Categorias ativas aparecem na criação de cursos e nas áreas do catálogo.</p>
|
||||
<div className="list">{categories.map((category) => <CategoryRow key={category.id} category={category} onSave={save} />)}</div>
|
||||
{!categories.length && <p className="empty">Nenhuma categoria cadastrada.</p>}
|
||||
</>;
|
||||
};
|
||||
143
components/admin/TrailManager.tsx
Normal file
143
components/admin/TrailManager.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ArrowDownIcon, ArrowUpIcon, PencilIcon, TrashIcon } from '@phosphor-icons/react';
|
||||
import { adminApi, instructorApi, LearningPath, LearningPathInput, TrailCourseOption } from '../../services/api';
|
||||
import { useToast } from '../../context/ToastContext';
|
||||
import { CourseCoverImage } from '../CourseCoverImage';
|
||||
import { Select } from '../ui/Select';
|
||||
import { ConfirmDialog } from '../ui/ConfirmDialog';
|
||||
import { PlusMockIcon } from '../ui/MockupIcons';
|
||||
|
||||
const emptyInput = (): LearningPathInput => ({ title: '', description: '', coverImageUrl: null, coverImageZoom: 1, coverImagePositionX: 50, coverImagePositionY: 50, status: 'draft', courseIds: [] });
|
||||
const toInput = (path: LearningPath): LearningPathInput => ({ title: path.title, description: path.description, coverImageUrl: path.coverImageUrl, coverImageZoom: path.coverImageZoom, coverImagePositionX: path.coverImagePositionX, coverImagePositionY: path.coverImagePositionY, status: path.status === 'published' ? 'published' : 'draft', courseIds: path.courses.map((course) => course.id) });
|
||||
|
||||
export const TrailManager: React.FC<{ onChanged?: () => void }> = ({ onChanged }) => {
|
||||
const { showToast } = useToast();
|
||||
const [paths, setPaths] = useState<LearningPath[]>([]);
|
||||
const [courses, setCourses] = useState<TrailCourseOption[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<LearningPath | null>(null);
|
||||
const [input, setInput] = useState<LearningPathInput>(emptyInput());
|
||||
const [courseToAdd, setCourseToAdd] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [coverConfigured, setCoverConfigured] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<LearningPath | null>(null);
|
||||
const coverInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [pathsResponse, coursesResponse] = await Promise.all([adminApi.listPaths(), adminApi.listPathCourses()]);
|
||||
setPaths(pathsResponse.data);
|
||||
setCourses(coursesResponse.data);
|
||||
} catch {
|
||||
showToast('Não foi possível carregar as trilhas.', 'error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
instructorApi.coverConfiguration().then((response) => setCoverConfigured(response.data.configured)).catch(() => setCoverConfigured(false));
|
||||
}, []);
|
||||
|
||||
const selectedCourses = useMemo(() => input.courseIds.map((id) => courses.find((course) => course.id === id)).filter((course): course is TrailCourseOption => Boolean(course)), [courses, input.courseIds]);
|
||||
const availableCourses = courses.filter((course) => !input.courseIds.includes(course.id));
|
||||
|
||||
const openNew = () => { setEditing(null); setInput(emptyInput()); setCourseToAdd(''); setEditorOpen(true); };
|
||||
const openEdit = (path: LearningPath) => { setEditing(path); setInput(toInput(path)); setCourseToAdd(''); setEditorOpen(true); };
|
||||
|
||||
const uploadCover = async (file?: File) => {
|
||||
if (!file) return;
|
||||
if (!coverConfigured) { showToast('O envio de imagens ainda não está configurado.', 'error'); return; }
|
||||
setUploading(true);
|
||||
try {
|
||||
const response = await instructorApi.uploadCover(file);
|
||||
setInput((current) => ({ ...current, coverImageUrl: response.data.coverImageUrl }));
|
||||
} catch {
|
||||
showToast('Não foi possível enviar a capa.', 'error');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const save = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!input.title.trim()) { showToast('Informe o nome da trilha.', 'error'); return; }
|
||||
if (!input.courseIds.length) { showToast('Adicione pelo menos um curso.', 'error'); return; }
|
||||
setSaving(true);
|
||||
try {
|
||||
if (editing) await adminApi.updatePath(editing.id, input);
|
||||
else await adminApi.createPath(input);
|
||||
showToast(editing ? 'Trilha atualizada.' : 'Trilha criada.', 'success');
|
||||
setEditorOpen(false);
|
||||
await load();
|
||||
onChanged?.();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Não foi possível salvar a trilha.', 'error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const addCourse = () => {
|
||||
if (!courseToAdd) return;
|
||||
setInput((current) => ({ ...current, courseIds: [...current.courseIds, courseToAdd] }));
|
||||
setCourseToAdd('');
|
||||
};
|
||||
|
||||
const moveCourse = (index: number, direction: -1 | 1) => {
|
||||
const target = index + direction;
|
||||
if (target < 0 || target >= input.courseIds.length) return;
|
||||
const next = [...input.courseIds];
|
||||
[next[index], next[target]] = [next[target], next[index]];
|
||||
setInput((current) => ({ ...current, courseIds: next }));
|
||||
};
|
||||
|
||||
const removeCourse = (courseId: string) => setInput((current) => ({ ...current, courseIds: current.courseIds.filter((id) => id !== courseId) }));
|
||||
|
||||
const performDelete = async () => {
|
||||
if (!deleteTarget) return;
|
||||
try {
|
||||
await adminApi.deletePath(deleteTarget.id);
|
||||
setPaths((current) => current.filter((path) => path.id !== deleteTarget.id));
|
||||
setDeleteTarget(null);
|
||||
showToast('Trilha excluída. Os cursos foram preservados.', 'success');
|
||||
onChanged?.();
|
||||
} catch {
|
||||
showToast('Não foi possível excluir a trilha.', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="loading">Carregando trilhas…</div>;
|
||||
|
||||
return <>
|
||||
<div className="toolbar"><h2 style={{ fontSize: 20, marginRight: 'auto' }}>Trilhas</h2><button className="btn" type="button" onClick={openNew}><PlusMockIcon className="ph" /> Nova trilha</button></div>
|
||||
{paths.length ? <div className="list">{paths.map((path) => <div className="row" key={path.id} style={{ gridTemplateColumns: '96px minmax(0, 1fr) auto' }}>
|
||||
<span style={{ width: 96, height: 54, borderRadius: 8, overflow: 'hidden', background: 'var(--bg-2)', display: 'block' }}>{path.coverImageUrl ? <CourseCoverImage source={path.coverImageUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : null}</span>
|
||||
<span className="t">{path.title}<small>{path.status === 'published' ? 'Publicada' : 'Rascunho'} · {path.courses.length} {path.courses.length === 1 ? 'curso' : 'cursos'}</small></span>
|
||||
<span style={{ display: 'flex', gap: 4 }}><button className="iconbtn" type="button" onClick={() => openEdit(path)} aria-label={`Editar trilha ${path.title}`}><PencilIcon className="ph" /></button><button className="iconbtn" type="button" onClick={() => setDeleteTarget(path)} aria-label={`Excluir trilha ${path.title}`}><TrashIcon className="ph" /></button></span>
|
||||
</div>)}</div> : <p className="empty">Nenhuma trilha criada ainda.</p>}
|
||||
|
||||
{editorOpen && <div className="scrim" role="dialog" aria-modal="true" aria-label={editing ? 'Editar trilha' : 'Nova trilha'} onMouseDown={(event) => { if (event.target === event.currentTarget) setEditorOpen(false); }}>
|
||||
<div className="dialog" style={{ maxWidth: 760 }}>
|
||||
<header><div><h2>{editing ? 'Editar trilha' : 'Nova trilha'}</h2><p>Organize cursos existentes na ordem em que os alunos devem assisti-los.</p></div><button type="button" className="iconbtn" onClick={() => setEditorOpen(false)} aria-label="Fechar">×</button></header>
|
||||
<form className="form" onSubmit={save}>
|
||||
<div className="field"><label htmlFor="trail-title">Nome</label><input id="trail-title" value={input.title} onChange={(event) => setInput((current) => ({ ...current, title: event.target.value }))} maxLength={160} required /></div>
|
||||
<div className="field"><label htmlFor="trail-description">Descrição</label><textarea id="trail-description" rows={3} value={input.description} onChange={(event) => setInput((current) => ({ ...current, description: event.target.value }))} maxLength={2000} /></div>
|
||||
<div className="field"><label>Status</label><Select variant="field" value={input.status} options={[{ value: 'draft', label: 'Rascunho' }, { value: 'published', label: 'Publicada' }]} onChange={(status) => setInput((current) => ({ ...current, status: status as LearningPathInput['status'] }))} ariaLabel="Status da trilha" /></div>
|
||||
<div className="field"><label>Capa</label><div style={{ display: 'flex', alignItems: 'center', gap: 12 }}><button className="btn sec" type="button" disabled={!coverConfigured || uploading} onClick={() => coverInput.current?.click()}>{uploading ? 'Enviando…' : 'Enviar imagem'}</button>{input.coverImageUrl && <CourseCoverImage source={input.coverImageUrl} alt="" style={{ width: 120, height: 68, borderRadius: 8, objectFit: 'cover' }} />}</div><input ref={coverInput} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={(event) => { const file = event.target.files?.[0]; event.currentTarget.value = ''; void uploadCover(file); }} />{!coverConfigured && <p className="muted" style={{ fontSize: 12 }}>O armazenamento de imagens ainda não está configurado.</p>}</div>
|
||||
<div className="field"><label>Cursos da trilha</label>
|
||||
<div className="list">{selectedCourses.map((course, index) => <div className="row" key={course.id} style={{ gridTemplateColumns: '28px minmax(0, 1fr) auto' }}><span className="i num">{index + 1}</span><span className="t">{course.title}<small>{course.category}</small></span><span style={{ display: 'flex', gap: 2 }}><button className="iconbtn" type="button" disabled={index === 0} onClick={() => moveCourse(index, -1)} aria-label="Mover para cima"><ArrowUpIcon className="ph" /></button><button className="iconbtn" type="button" disabled={index === selectedCourses.length - 1} onClick={() => moveCourse(index, 1)} aria-label="Mover para baixo"><ArrowDownIcon className="ph" /></button><button className="iconbtn" type="button" onClick={() => removeCourse(course.id)} aria-label="Remover curso"><TrashIcon className="ph" /></button></span></div>)}</div>
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 10 }}><div style={{ flex: 1 }}><Select variant="field" value={courseToAdd} options={[{ value: '', label: availableCourses.length ? 'Selecione um curso' : 'Nenhum curso disponível' }, ...availableCourses.map((course) => ({ value: course.id, label: course.title }))]} onChange={setCourseToAdd} ariaLabel="Curso para adicionar" disabled={!availableCourses.length} /></div><button className="btn sec" type="button" onClick={addCourse} disabled={!courseToAdd}><PlusMockIcon className="ph" /> Adicionar</button></div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 24 }}><button className="btn sec" type="button" onClick={() => setEditorOpen(false)}>Cancelar</button><button className="btn" type="submit" disabled={saving}>{saving ? 'Salvando…' : 'Salvar trilha'}</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
<ConfirmDialog open={Boolean(deleteTarget)} title="Excluir trilha" message={deleteTarget ? `Excluir a trilha “${deleteTarget.title}”? Os cursos serão preservados.` : ''} confirmLabel="Excluir trilha" onCancel={() => setDeleteTarget(null)} onConfirm={() => void performDelete()} />
|
||||
</>;
|
||||
};
|
||||
140
components/catalog/Artwork.tsx
Normal file
140
components/catalog/Artwork.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Course } from '../../types';
|
||||
import { PublicLearningPath } from '../../services/db';
|
||||
import { CourseCoverImage } from '../CourseCoverImage';
|
||||
import { useCatalog } from '../../context/CatalogContext';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { courseMeta, hasRealCover, plural, totalDuration } from '../../lib/format';
|
||||
import { paths } from '../../lib/routes';
|
||||
|
||||
type Framing = { zoom?: number; x?: number; y?: number };
|
||||
|
||||
/** A real cover (Bunny) replaces the colour block in the same format. */
|
||||
export const ArtImage: React.FC<{ source: string; framing?: Framing; onMissing?: () => void }> = ({ source, framing, onMissing }) => (
|
||||
<CourseCoverImage
|
||||
source={source}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
className="art-img"
|
||||
onFinalError={onMissing}
|
||||
style={{ transform: framing?.zoom && framing.zoom !== 1 ? `scale(${framing.zoom})` : undefined, objectPosition: `${framing?.x ?? 50}% ${framing?.y ?? 50}%` }}
|
||||
/>
|
||||
);
|
||||
|
||||
export const courseFraming = (course: Course): Framing => ({ zoom: course.coverImageZoom, x: course.coverImagePositionX, y: course.coverImagePositionY });
|
||||
|
||||
/** Hook that tells whether a course shows its uploaded image, falling back to colour if it fails to load. */
|
||||
export const useCoverImage = (source?: string | null) => {
|
||||
const [broken, setBroken] = useState(false);
|
||||
const show = hasRealCover(source) && !broken;
|
||||
return { show, onMissing: () => setBroken(true) };
|
||||
};
|
||||
|
||||
export const Progress: React.FC<{ value: number; inside?: boolean }> = ({ value, inside }) => {
|
||||
const pct = Math.max(0, Math.min(100, Math.round(value)));
|
||||
return (
|
||||
<span className={inside ? 'inprog' : 'prog'} role="progressbar" aria-label={`${pct}% concluído`} aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100} style={inside ? undefined : { display: 'block' }}>
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
interface CoverProps {
|
||||
course: Course;
|
||||
variant?: 'big' | 'mini';
|
||||
progress?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Course artwork: 16:10 block in the area colour with the title, or the uploaded image. */
|
||||
export const Cover: React.FC<CoverProps> = ({ course, variant, progress, className = '' }) => {
|
||||
const { toneOf } = useCatalog();
|
||||
const image = useCoverImage(course.thumbnail);
|
||||
const showBar = progress !== undefined && progress > 0;
|
||||
return (
|
||||
<div className={`cover tr-${toneOf(course.category)}${variant ? ` ${variant}` : ''}${showBar ? ' hp' : ''}${image.show ? ' has-img' : ''} ${className}`}>
|
||||
{image.show && <ArtImage source={course.thumbnail} framing={courseFraming(course)} onMissing={image.onMissing} />}
|
||||
{!image.show && <span className="t">{course.title}</span>}
|
||||
{showBar && <Progress value={progress} inside />}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
/** Small colour/image chip used next to titles in lists. */
|
||||
export const Thumb: React.FC<{ course: Course; className?: string }> = ({ course, className = 'thumb' }) => {
|
||||
const { toneOf } = useCatalog();
|
||||
const image = useCoverImage(course.thumbnail);
|
||||
return (
|
||||
<span className={`${className} tr-${toneOf(course.category)}`} aria-hidden="true">
|
||||
{image.show && <ArtImage source={course.thumbnail} framing={courseFraming(course)} onMissing={image.onMissing} />}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export const CourseCard: React.FC<{ course: Course }> = ({ course }) => {
|
||||
const { user } = useAuth();
|
||||
const image = useCoverImage(course.thumbnail);
|
||||
const progress = user ? course.progress || 0 : 0;
|
||||
return (
|
||||
<Link className="card" to={paths.course(course.id)}>
|
||||
<Cover course={course} progress={progress} />
|
||||
<div className="m">
|
||||
{image.show ? (
|
||||
<><b>{course.title}</b><span className="num one">{[course.instructor, courseMeta(course)].filter(Boolean).join(' · ')}</span></>
|
||||
) : (
|
||||
<><b>{course.instructor || course.category}</b><span className="num one">{[course.category, courseMeta(course)].join(' · ')}</span></>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
/** "Continue assistindo": opens the next unfinished lesson directly. */
|
||||
export const ContinueCard: React.FC<{ course: Course }> = ({ course }) => (
|
||||
<Link className="card" to={paths.continueCourse(course.id)}>
|
||||
<Cover course={course} progress={course.progress || 0} />
|
||||
<div className="m">
|
||||
<b>{course.title}</b>
|
||||
<span className="num one">{`${Math.round(course.progress || 0)}% concluído · ${course.lessons.length} aulas`}</span>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
|
||||
export const pathCourses = (path: PublicLearningPath, courseById: (id: string) => Course | undefined) => path.courses
|
||||
.slice()
|
||||
.sort((a, b) => a.position - b.position)
|
||||
.map((item) => courseById(item.id))
|
||||
.filter((course): course is Course => Boolean(course));
|
||||
|
||||
export const pathProgress = (courses: Course[]) => {
|
||||
const lessons = courses.reduce((sum, course) => sum + course.lessons.length, 0);
|
||||
if (!lessons) return 0;
|
||||
const seen = courses.reduce((sum, course) => sum + ((course.progress || 0) / 100) * course.lessons.length, 0);
|
||||
return (seen / lessons) * 100;
|
||||
};
|
||||
|
||||
/** Trilha: 2:3 poster with two cards stacked behind it. */
|
||||
export const TrailPoster: React.FC<{ path: PublicLearningPath }> = ({ path }) => {
|
||||
const { pathTone, courseById } = useCatalog();
|
||||
const { user } = useAuth();
|
||||
const image = useCoverImage(path.coverImageUrl);
|
||||
const tone = pathTone(path);
|
||||
const courses = pathCourses(path, courseById);
|
||||
const duration = totalDuration(courses);
|
||||
const progress = user ? pathProgress(courses) : 0;
|
||||
return (
|
||||
<Link className={`poster-card tr-${tone}`} to={paths.trail(path.id)}>
|
||||
<div className={`poster tr-${tone}${image.show ? ' has-img' : ''}`}>
|
||||
{image.show && path.coverImageUrl && <ArtImage source={path.coverImageUrl} framing={{ zoom: path.coverImageZoom, x: path.coverImagePositionX, y: path.coverImagePositionY }} onMissing={image.onMissing} />}
|
||||
<div>
|
||||
{!image.show && <span className="t">{path.title}</span>}
|
||||
<span className="n num">{[plural(path.courses.length, 'curso', 'cursos'), duration].filter(Boolean).join(' · ')}</span>
|
||||
</div>
|
||||
{progress > 0 && <Progress value={progress} inside />}
|
||||
</div>
|
||||
{image.show && <div className="card"><div className="m"><b>{path.title}</b></div></div>}
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
173
components/catalog/Hero.tsx
Normal file
173
components/catalog/Hero.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
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>
|
||||
);
|
||||
};
|
||||
55
components/catalog/Shelf.tsx
Normal file
55
components/catalog/Shelf.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { CaretLeftIcon, CaretRightIcon } from '@phosphor-icons/react';
|
||||
|
||||
interface ShelfProps {
|
||||
title: string;
|
||||
to?: string;
|
||||
kind?: 'wide' | 'tall';
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/** A horizontal row with scroll-snap; the title is a link and the arrows appear on hover. */
|
||||
export const Shelf: React.FC<ShelfProps> = ({ title, to, kind, children }) => {
|
||||
const railRef = useRef<HTMLDivElement>(null);
|
||||
const [edges, setEdges] = useState({ start: true, end: false, fits: true });
|
||||
|
||||
const update = useCallback(() => {
|
||||
const rail = railRef.current;
|
||||
if (!rail) return;
|
||||
setEdges({
|
||||
start: rail.scrollLeft < 4,
|
||||
end: rail.scrollLeft + rail.clientWidth >= rail.scrollWidth - 4,
|
||||
fits: rail.scrollWidth <= rail.clientWidth + 4,
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
update();
|
||||
const rail = railRef.current;
|
||||
if (!rail) return;
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(rail);
|
||||
return () => observer.disconnect();
|
||||
}, [update, children]);
|
||||
|
||||
const scroll = (direction: -1 | 1) => {
|
||||
const rail = railRef.current;
|
||||
if (rail) rail.scrollBy({ left: direction * rail.clientWidth * 0.9 });
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="shelf">
|
||||
<div className="rowhead">
|
||||
{to ? <Link className="shead" to={to}><h2>{title}</h2><CaretRightIcon className="ph" weight="bold" /></Link> : <h2>{title}</h2>}
|
||||
{!edges.fits && (
|
||||
<div className="nav2">
|
||||
<button type="button" className="iconbtn" onClick={() => scroll(-1)} disabled={edges.start} aria-label="Anterior"><CaretLeftIcon className="ph" weight="bold" /></button>
|
||||
<button type="button" className="iconbtn" onClick={() => scroll(1)} disabled={edges.end} aria-label="Próximo"><CaretRightIcon className="ph" weight="bold" /></button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div ref={railRef} className={`rail${kind ? ` ${kind}` : ''}`} onScroll={update}>{children}</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
129
components/course/LessonVideo.tsx
Normal file
129
components/course/LessonVideo.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { CircleNotchIcon, WarningCircleIcon } from '@phosphor-icons/react';
|
||||
import { Lesson } from '../../types';
|
||||
import { courseApi, LessonPlayback } from '../../services/api';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
playerjs?: {
|
||||
Player: new (element: HTMLIFrameElement) => {
|
||||
on: (event: string, listener: (data?: { seconds?: number; duration?: number }) => void) => void;
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let bunnyPlayerJsPromise: Promise<void> | null = null;
|
||||
|
||||
const loadBunnyPlayerJs = () => {
|
||||
if (window.playerjs) return Promise.resolve();
|
||||
if (bunnyPlayerJsPromise) return bunnyPlayerJsPromise;
|
||||
bunnyPlayerJsPromise = new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://assets.mediadelivery.net/playerjs/player-0.1.0.min.js';
|
||||
script.async = true;
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error('Bunny player events could not be loaded'));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
return bunnyPlayerJsPromise;
|
||||
};
|
||||
|
||||
interface LessonVideoProps {
|
||||
courseId: string;
|
||||
lesson: Lesson;
|
||||
/** Saved position to resume from (HTML video only; Bunny resumes on its own). */
|
||||
resumeAt: number;
|
||||
/** Called on playback progress with the current second (and duration when known). */
|
||||
onTime: (seconds: number, duration?: number) => void;
|
||||
/** Called when the video finished playing. `autoAdvance` is true for HTML video, as before. */
|
||||
onEnded: (seconds: number, autoAdvance: boolean) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The API verifies the session before returning a time-limited Bunny embed URL;
|
||||
* a video provider key is never sent to the browser.
|
||||
*/
|
||||
export const LessonVideo: React.FC<LessonVideoProps> = ({ courseId, lesson, resumeAt, onTime, onEnded, className = 'player' }) => {
|
||||
const [playback, setPlayback] = useState<LessonPlayback | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const frameRef = useRef<HTMLIFrameElement>(null);
|
||||
const handlers = useRef({ onTime, onEnded });
|
||||
handlers.current = { onTime, onEnded };
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setPlayback(null);
|
||||
setError('');
|
||||
courseApi.playback(courseId, lesson.id)
|
||||
.then((response) => { if (!cancelled) setPlayback(response.data); })
|
||||
.catch((reason) => { if (!cancelled) setError(reason instanceof Error ? reason.message : 'Não foi possível carregar este vídeo.'); });
|
||||
return () => { cancelled = true; };
|
||||
}, [courseId, lesson.id]);
|
||||
|
||||
// Bunny's iframe has no HTMLVideoElement; Player.js relays its playback events.
|
||||
useEffect(() => {
|
||||
if (!playback || playback.kind !== 'embed') return;
|
||||
let disposed = false;
|
||||
void loadBunnyPlayerJs().then(() => {
|
||||
if (disposed || !frameRef.current || !window.playerjs) return;
|
||||
const player = new window.playerjs.Player(frameRef.current);
|
||||
player.on('timeupdate', (data) => {
|
||||
// Bunny only saves the watched position; completion comes from its "ended" event.
|
||||
if (!disposed) handlers.current.onTime(Math.floor(data?.seconds || 0));
|
||||
});
|
||||
player.on('ended', (data) => {
|
||||
if (!disposed) handlers.current.onEnded(Math.floor(data?.duration || data?.seconds || 0), false);
|
||||
});
|
||||
}).catch(() => undefined);
|
||||
return () => { disposed = true; };
|
||||
}, [playback]);
|
||||
|
||||
const restorePosition = () => {
|
||||
const video = videoRef.current;
|
||||
if (video && resumeAt > 0 && resumeAt < video.duration - 5) video.currentTime = resumeAt;
|
||||
};
|
||||
|
||||
let content: React.ReactNode;
|
||||
if (error) {
|
||||
content = <div className="pl msg"><WarningCircleIcon className="ph" size={28} /><span>{error}</span></div>;
|
||||
} else if (!playback) {
|
||||
content = <div className="pl msg"><CircleNotchIcon className="ph spin" size={28} /><span>Carregando vídeo</span></div>;
|
||||
} else if (playback.kind === 'embed' && playback.embedUrl) {
|
||||
content = (
|
||||
<iframe
|
||||
key={lesson.id}
|
||||
ref={frameRef}
|
||||
src={playback.embedUrl}
|
||||
title={lesson.title || 'Vídeo da aula'}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; fullscreen"
|
||||
allowFullScreen
|
||||
/>
|
||||
);
|
||||
} else if (playback.source) {
|
||||
content = (
|
||||
<video
|
||||
key={lesson.id}
|
||||
ref={videoRef}
|
||||
src={playback.source}
|
||||
controls
|
||||
autoPlay
|
||||
playsInline
|
||||
onTimeUpdate={(event) => {
|
||||
const { currentTime, duration } = event.currentTarget;
|
||||
if (duration > 0) handlers.current.onTime(currentTime, duration);
|
||||
}}
|
||||
onEnded={(event) => handlers.current.onEnded(Math.round(event.currentTarget.duration || 0), true)}
|
||||
onLoadedMetadata={restorePosition}
|
||||
>
|
||||
Seu navegador não suporta vídeo.
|
||||
</video>
|
||||
);
|
||||
} else {
|
||||
content = <div className="pl msg"><span>Vídeo indisponível.</span></div>;
|
||||
}
|
||||
|
||||
return <div className={className}>{content}</div>;
|
||||
};
|
||||
86
components/course/Materials.tsx
Normal file
86
components/course/Materials.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
ArrowSquareOutIcon, CheckIcon, CircleNotchIcon, FileIcon,
|
||||
ImageIcon, LinkSimpleIcon, VideoCameraIcon,
|
||||
} from '@phosphor-icons/react';
|
||||
import { DocMockIcon, DownloadMockIcon, PdfMockIcon, XlsMockIcon, ZipMockIcon } from '../ui/MockupIcons';
|
||||
import { Attachment, AttachmentType } from '../../types';
|
||||
import { downloadCourseAsset } from '../../services/api';
|
||||
import { recordDownloadHistory } from '../../services/db';
|
||||
import { useToast } from '../../context/ToastContext';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { paths } from '../../lib/routes';
|
||||
|
||||
export const attachmentIcon = (type: AttachmentType) => {
|
||||
switch (type) {
|
||||
case 'pdf': return <PdfMockIcon className="ph" />;
|
||||
case 'spreadsheet': return <XlsMockIcon className="ph" />;
|
||||
case 'zip': return <ZipMockIcon className="ph" />;
|
||||
case 'doc': return <DocMockIcon className="ph" />;
|
||||
case 'image': return <ImageIcon className="ph" />;
|
||||
case 'link': return <LinkSimpleIcon className="ph" />;
|
||||
case 'video': return <VideoCameraIcon className="ph" />;
|
||||
default: return <FileIcon className="ph" />;
|
||||
}
|
||||
};
|
||||
|
||||
export const attachmentLabel = (type: AttachmentType) => ({
|
||||
pdf: 'PDF', spreadsheet: 'Planilha', zip: 'ZIP', doc: 'Documento', image: 'Imagem', link: 'Link', video: 'Vídeo',
|
||||
}[type] || 'Arquivo');
|
||||
|
||||
/** Downloads through the Academy (or opens a link) with the same feedback as before. */
|
||||
export const useMaterialAction = () => {
|
||||
const { showDownloadToast, showToast } = useToast();
|
||||
const { user } = useAuth();
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const [doneId, setDoneId] = useState<string | null>(null);
|
||||
|
||||
const open = async (attachment: Attachment) => {
|
||||
if (attachment.type === 'link') {
|
||||
showToast(`Abrindo “${attachment.name}”.`, 'info');
|
||||
window.open(attachment.url, '_blank', 'noopener,noreferrer');
|
||||
if (user) void recordDownloadHistory(attachment.id).catch(() => undefined);
|
||||
return false;
|
||||
}
|
||||
setBusyId(attachment.id);
|
||||
try {
|
||||
await downloadCourseAsset(attachment.id, attachment.name);
|
||||
showDownloadToast(attachment.name, attachment.size);
|
||||
if (user) void recordDownloadHistory(attachment.id).catch(() => undefined);
|
||||
setDoneId(attachment.id);
|
||||
window.setTimeout(() => setDoneId((current) => (current === attachment.id ? null : current)), 3000);
|
||||
return true;
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Não foi possível baixar este material.', 'error');
|
||||
return false;
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
};
|
||||
|
||||
return { open, busyId, doneId };
|
||||
};
|
||||
|
||||
export const MaterialButton: React.FC<{ attachment: Attachment; action: ReturnType<typeof useMaterialAction>; label?: boolean; className?: string }> = ({ attachment, action, label = true, className = 'btn sec' }) => {
|
||||
const { user } = useAuth();
|
||||
if (!user) return label ? <Link className={className} to={paths.signIn}>Entrar para baixar</Link> : null;
|
||||
const isLink = attachment.type === 'link';
|
||||
const busy = action.busyId === attachment.id;
|
||||
const done = action.doneId === attachment.id;
|
||||
const icon = busy ? <CircleNotchIcon className="ph spin" /> : done ? <CheckIcon className="ph" /> : isLink ? <ArrowSquareOutIcon className="ph" /> : <DownloadMockIcon className="ph" />;
|
||||
const text = isLink ? 'Abrir' : done ? 'Baixado' : 'Baixar';
|
||||
return (
|
||||
<button type="button" className={className} onClick={() => void action.open(attachment)} disabled={busy} aria-label={`${text} ${attachment.name}`}>
|
||||
{icon}{label && ` ${text}`}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
export const MaterialRow: React.FC<{ attachment: Attachment; detail?: string; action: ReturnType<typeof useMaterialAction>; compact?: boolean }> = ({ attachment, detail, action, compact }) => (
|
||||
<div className="file" style={compact ? { paddingBlock: 8 } : undefined}>
|
||||
<span className="ic">{attachmentIcon(attachment.type)}</span>
|
||||
<span>{attachment.name}<small className="num">{[detail, attachmentLabel(attachment.type), attachment.size].filter(Boolean).join(' · ')}</small></span>
|
||||
{compact ? <MaterialButton attachment={attachment} action={action} label={false} className="iconbtn" /> : <MaterialButton attachment={attachment} action={action} />}
|
||||
</div>
|
||||
);
|
||||
26
components/shell/AppShell.tsx
Normal file
26
components/shell/AppShell.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { Sidebar } from './Sidebar';
|
||||
import { MobileBack, MobileTabBar } from './MobileNavigation';
|
||||
import { useIsMobile } from '../../hooks/useMediaQuery';
|
||||
|
||||
export const AppShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const location = useLocation();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
useEffect(() => {
|
||||
window.scrollTo(0, 0);
|
||||
document.body.classList.toggle('immersive', location.pathname.includes('/aulas/'));
|
||||
return () => document.body.classList.remove('immersive');
|
||||
}, [location.pathname]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{!isMobile && <Sidebar />}
|
||||
{isMobile && <MobileBack />}
|
||||
{/* Keyed by path: the arrival animation only plays when navigating to a new page. */}
|
||||
<div className="main" key={location.pathname}>{children}</div>
|
||||
{isMobile && <MobileTabBar />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
47
components/shell/MobileNavigation.tsx
Normal file
47
components/shell/MobileNavigation.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import React from 'react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { CaretLeftIcon } from '@phosphor-icons/react';
|
||||
import {
|
||||
CommunityTabFilledMockIcon, CommunityTabMockIcon, ExploreTabFilledMockIcon, ExploreTabMockIcon,
|
||||
SearchTabFilledMockIcon, SearchTabMockIcon, TrailsTabFilledMockIcon, TrailsTabMockIcon, UserMockIcon,
|
||||
} from '../ui/MockupIcons';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { Avatar } from '../ui/Avatar';
|
||||
import { paths } from '../../lib/routes';
|
||||
import { navKeyFor } from '../../lib/navigation';
|
||||
|
||||
const root = new Set([paths.explore, paths.trails, paths.search, paths.community, paths.you]);
|
||||
const parentFor = (path: string) => path.startsWith('/cursos/') && path.includes('/aulas/') ? path.split('/aulas/')[0]
|
||||
: path.startsWith('/trilhas/') ? paths.trails
|
||||
: path.startsWith('/cursos/') ? paths.explore
|
||||
: path.startsWith('/instrutores/') || path.startsWith('/perfis/') ? paths.community
|
||||
: paths.you;
|
||||
|
||||
export const MobileBack: React.FC = () => {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
if (root.has(location.pathname)) return null;
|
||||
const parent = parentFor(location.pathname);
|
||||
const label = parent === paths.trails ? 'Trilhas' : parent === paths.explore ? 'Explorar' : parent === paths.community ? 'Comunidade' : parent === paths.you ? 'Você' : 'Curso';
|
||||
const back = () => { if ((window.history.state?.idx ?? 0) > 0) navigate(-1); else navigate(parent); };
|
||||
return <nav className="m-nav" aria-label="Voltar"><button type="button" className="m-back" onClick={back}><CaretLeftIcon className="ph" /><span>Voltar</span></button><span className="m-nt">{label}</span><span /></nav>;
|
||||
};
|
||||
|
||||
export const MobileTabBar: React.FC = () => {
|
||||
const location = useLocation();
|
||||
const { user } = useAuth();
|
||||
if (location.pathname.includes('/aulas/')) return null;
|
||||
const key = navKeyFor(location.pathname);
|
||||
const active = key === 'trails' ? 'trails' : key === 'search' ? 'search' : key === 'community' || key === 'professors' ? 'community' : key === 'explore' ? 'explore' : 'you';
|
||||
const items = [
|
||||
{ key: 'explore', label: 'Explorar', to: paths.explore, icon: ExploreTabMockIcon, activeIcon: ExploreTabFilledMockIcon },
|
||||
{ key: 'trails', label: 'Trilhas', to: paths.trails, icon: TrailsTabMockIcon, activeIcon: TrailsTabFilledMockIcon },
|
||||
{ key: 'search', label: 'Buscar', to: paths.search, icon: SearchTabMockIcon, activeIcon: SearchTabFilledMockIcon },
|
||||
{ key: 'community', label: 'Comunidade', to: paths.community, icon: CommunityTabMockIcon, activeIcon: CommunityTabFilledMockIcon },
|
||||
{ key: 'you', label: 'Você', to: paths.you, icon: UserMockIcon, activeIcon: UserMockIcon },
|
||||
] as const;
|
||||
return <nav className="tabbar" aria-label="Navegação mobile">{items.map(({ key: itemKey, label, to, icon: InactiveIcon, activeIcon: ActiveIcon }) => {
|
||||
const Icon = active === itemKey ? ActiveIcon : InactiveIcon;
|
||||
return <Link key={itemKey} to={to} aria-current={active === itemKey ? 'page' : undefined}>{itemKey === 'you' && user ? <Avatar name={user.name} src={user.avatar} size="sm" /> : <Icon className="ph" />}<span>{label}</span></Link>;
|
||||
})}</nav>;
|
||||
};
|
||||
197
components/shell/Sidebar.tsx
Normal file
197
components/shell/Sidebar.tsx
Normal file
@@ -0,0 +1,197 @@
|
||||
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
BooksMockIcon, ChatsMockIcon, ChevronDownMockIcon, CompassMockIcon, FolderMockIcon, GearMockIcon,
|
||||
MoonMockIcon, PathMockIcon, SearchMockIcon, SignOutMockIcon, SunMockIcon, TeacherMockIcon,
|
||||
TrayMockIcon, UserMockIcon, VideoMockIcon,
|
||||
} from '../ui/MockupIcons';
|
||||
import { SidebarSimpleIcon } from '@phosphor-icons/react';
|
||||
import { Logo } from '../Logo';
|
||||
import { Avatar } from '../ui/Avatar';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { useTheme } from '../../context/ThemeContext';
|
||||
import { useCatalog } from '../../context/CatalogContext';
|
||||
import { NavKey, navKeyFor } from '../../lib/navigation';
|
||||
import { paths } from '../../lib/routes';
|
||||
import { readPreference, writePreference } from '../../lib/storage';
|
||||
|
||||
const GROUPS_KEY = 'ca-groups';
|
||||
const COLLAPSED_KEY = 'ca-side';
|
||||
|
||||
type Item = { key: NavKey; to: string; label: string; icon: React.ReactNode; count?: number };
|
||||
|
||||
const readGroups = (): Record<string, boolean> => {
|
||||
try {
|
||||
return JSON.parse(readPreference(GROUPS_KEY) || '{}');
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const SideItem: React.FC<{ item: Item; current: NavKey }> = ({ item, current }) => (
|
||||
<Link className="sitem" to={item.to} title={item.label} aria-current={current === item.key ? 'page' : undefined}>
|
||||
{item.icon}
|
||||
<span className="lbl">{item.label}</span>
|
||||
{item.count ? <span className="cnt">{item.count}</span> : null}
|
||||
</Link>
|
||||
);
|
||||
|
||||
export const Sidebar: React.FC = () => {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { user, logout } = useAuth();
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
const { courses } = useCatalog();
|
||||
const current = navKeyFor(location.pathname);
|
||||
const [shut, setShut] = useState<Record<string, boolean>>(readGroups);
|
||||
const [collapsed, setCollapsed] = useState(() => readPreference(COLLAPSED_KEY) === '1');
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const whoRef = useRef<HTMLButtonElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const [menuStyle, setMenuStyle] = useState<React.CSSProperties>({});
|
||||
|
||||
const canTeach = user?.role === 'professor' || user?.role === 'superadmin';
|
||||
const inProgress = user ? courses.filter((course) => (course.progress || 0) > 0 && (course.progress || 0) < 100).length : 0;
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle('collapsed', collapsed);
|
||||
}, [collapsed]);
|
||||
|
||||
useEffect(() => setMenuOpen(false), [location.pathname]);
|
||||
|
||||
// The account menu lives on <body> with position: fixed, so the sidebar never clips it.
|
||||
useLayoutEffect(() => {
|
||||
if (!menuOpen || !whoRef.current) return;
|
||||
const button = whoRef.current.getBoundingClientRect();
|
||||
const sidebar = whoRef.current.closest('.sidebar')?.getBoundingClientRect();
|
||||
setMenuStyle(collapsed && sidebar
|
||||
? { left: sidebar.right + 10, bottom: Math.max(12, window.innerHeight - button.bottom) }
|
||||
: { left: Math.max(12, button.left), bottom: window.innerHeight - button.top + 8 });
|
||||
}, [collapsed, menuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!menuOpen) return;
|
||||
const close = (event: MouseEvent) => {
|
||||
const target = event.target as Node;
|
||||
if (!menuRef.current?.contains(target) && !whoRef.current?.contains(target)) setMenuOpen(false);
|
||||
};
|
||||
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') setMenuOpen(false); };
|
||||
const onResize = () => setMenuOpen(false);
|
||||
document.addEventListener('mousedown', close);
|
||||
document.addEventListener('keydown', onKey);
|
||||
window.addEventListener('resize', onResize);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', close);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('resize', onResize);
|
||||
};
|
||||
}, [menuOpen]);
|
||||
|
||||
const toggleGroup = (id: string) => setShut((state) => {
|
||||
const next = { ...state, [id]: !state[id] };
|
||||
writePreference(GROUPS_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
|
||||
const toggleCollapsed = () => setCollapsed((value) => {
|
||||
writePreference(COLLAPSED_KEY, value ? '0' : '1');
|
||||
return !value;
|
||||
});
|
||||
|
||||
const signOut = () => {
|
||||
setMenuOpen(false);
|
||||
logout();
|
||||
navigate(paths.explore);
|
||||
};
|
||||
|
||||
const group = (id: string, title: string, items: Array<Item | false>) => {
|
||||
const visible = items.filter(Boolean) as Item[];
|
||||
if (!visible.length) return null;
|
||||
return (
|
||||
<div className={`sgroup${shut[id] ? ' shut' : ''}`}>
|
||||
<button type="button" className="ghead" onClick={() => toggleGroup(id)} aria-expanded={!shut[id]}>
|
||||
<span className="lbl">{title}</span>
|
||||
<ChevronDownMockIcon className="ph" />
|
||||
</button>
|
||||
<div className="gbody"><div>{visible.map((item) => <SideItem key={item.key} item={item} current={current} />)}</div></div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const themeButton = (
|
||||
<button type="button" className="iconbtn" onClick={toggleTheme} aria-label={theme === 'dark' ? 'Usar modo claro' : 'Usar modo escuro'} title={theme === 'dark' ? 'Modo claro' : 'Modo escuro'}>
|
||||
{theme === 'dark' ? <SunMockIcon className="ph" /> : <MoonMockIcon className="ph" />}
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<aside className="sidebar" aria-label="Navegação principal">
|
||||
<div className="side-top">
|
||||
<button type="button" className="iconbtn" onClick={toggleCollapsed} aria-label={collapsed ? 'Expandir barra lateral' : 'Recolher barra lateral'} title={collapsed ? 'Expandir barra lateral' : 'Recolher barra lateral'}>
|
||||
<SidebarSimpleIcon className="ph" />
|
||||
</button>
|
||||
</div>
|
||||
<Link to={paths.explore} className="logo" aria-label="Compor Academy, início">
|
||||
<Logo width={96} />
|
||||
<span className="mark" aria-hidden="true">c</span>
|
||||
</Link>
|
||||
<nav>
|
||||
<div className="sgroup solo">
|
||||
<SideItem current={current} item={{ key: 'search', to: paths.search, label: 'Buscar', icon: <SearchMockIcon className="ph" /> }} />
|
||||
<SideItem current={current} item={{ key: 'explore', to: paths.explore, label: 'Explorar', icon: <CompassMockIcon className="ph" /> }} />
|
||||
</div>
|
||||
{group('apr', 'Aprendizado', [
|
||||
{ key: 'trails', to: paths.trails, label: 'Trilhas', icon: <PathMockIcon className="ph" /> },
|
||||
Boolean(user) && { key: 'learning', to: paths.learning, label: 'Minha aprendizagem', icon: <BooksMockIcon className="ph" />, count: inProgress },
|
||||
])}
|
||||
{group('com', 'Comunidade', [
|
||||
{ key: 'community', to: paths.community, label: 'Discussões', icon: <ChatsMockIcon className="ph" /> },
|
||||
{ key: 'professors', to: paths.professors, label: 'Professores', icon: <TeacherMockIcon className="ph" /> },
|
||||
])}
|
||||
{group('mat', 'Materiais', [
|
||||
{ key: 'library', to: paths.library, label: 'Biblioteca', icon: <FolderMockIcon className="ph" /> },
|
||||
Boolean(user) && { key: 'downloads', to: paths.downloads, label: 'Meus downloads', icon: <TrayMockIcon className="ph" /> },
|
||||
])}
|
||||
{canTeach && group('ges', 'Gestão', [
|
||||
{ key: 'manage', to: paths.manage, label: 'Gerenciar cursos', icon: <VideoMockIcon className="ph" /> },
|
||||
user?.role === 'superadmin' && { key: 'admin', to: paths.admin, label: 'Administração', icon: <GearMockIcon className="ph" /> },
|
||||
])}
|
||||
</nav>
|
||||
<div className="side-foot">
|
||||
{user ? (
|
||||
<div className="frow">
|
||||
<button ref={whoRef} type="button" className="who-row" onClick={() => setMenuOpen((open) => !open)} aria-haspopup="menu" aria-expanded={menuOpen} title={user.name}>
|
||||
<Avatar name={user.name} src={user.avatar} size="sm" />
|
||||
<span className="lbl">{user.name}</span>
|
||||
</button>
|
||||
{themeButton}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Link className="btn guestbtn" to={paths.signUp}>Criar conta</Link>
|
||||
<div className="frow">
|
||||
<Link className="who-row" to={paths.signIn} title="Entrar">
|
||||
<span className="av sm guestav"><UserMockIcon className="ph" /></span>
|
||||
<span className="lbl">Entrar</span>
|
||||
</Link>
|
||||
{themeButton}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{menuOpen && user && createPortal(
|
||||
<div ref={menuRef} className="menu" role="menu" style={menuStyle}>
|
||||
<div className="who"><b>{user.name}</b><small>{user.email}</small></div>
|
||||
<Link role="menuitem" to={paths.account}><UserMockIcon className="ph" /> Conta</Link>
|
||||
<Link role="menuitem" to={paths.learning}><BooksMockIcon className="ph" /> Minha aprendizagem</Link>
|
||||
<Link role="menuitem" to={paths.downloads}><TrayMockIcon className="ph" /> Meus downloads</Link>
|
||||
{canTeach && <Link role="menuitem" to={paths.manage}><VideoMockIcon className="ph" /> Gerenciar cursos</Link>}
|
||||
{user.role === 'superadmin' && <Link role="menuitem" to={paths.admin}><GearMockIcon className="ph" /> Administração</Link>}
|
||||
<button role="menuitem" type="button" onClick={signOut}><SignOutMockIcon className="ph" /> Sair</button>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
15
components/ui/Avatar.tsx
Normal file
15
components/ui/Avatar.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import React from 'react';
|
||||
import { initials } from '../../lib/format';
|
||||
|
||||
interface AvatarProps {
|
||||
name: string;
|
||||
src?: string | null;
|
||||
size?: 'sm' | 'md' | 'xl';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const Avatar: React.FC<AvatarProps> = ({ name, src, size, className = '' }) => (
|
||||
<span className={`av${size ? ` ${size}` : ''} ${className}`} aria-hidden="true">
|
||||
{src ? <img src={src} alt="" /> : initials(name)}
|
||||
</span>
|
||||
);
|
||||
33
components/ui/ConfirmDialog.tsx
Normal file
33
components/ui/ConfirmDialog.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
interface ConfirmDialogProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel?: string;
|
||||
busy?: boolean;
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void;
|
||||
}
|
||||
|
||||
/** In-app confirmation dialog instead of window.confirm. */
|
||||
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ open, title, message, confirmLabel = 'Confirmar', busy = false, onCancel, onConfirm }) => {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onCancel(); };
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => document.removeEventListener('keydown', onKey);
|
||||
}, [open, onCancel]);
|
||||
|
||||
if (!open) return null;
|
||||
return createPortal(<div className="scrim" role="dialog" aria-modal="true" aria-label={title} onMouseDown={(event) => { if (event.target === event.currentTarget) onCancel(); }}>
|
||||
<div className="dialog" style={{ maxWidth: 420 }}>
|
||||
<header><div><h2>{title}</h2><p>{message}</p></div></header>
|
||||
<footer>
|
||||
<button className="btn sec" type="button" onClick={onCancel} disabled={busy}>Cancelar</button>
|
||||
<button className="btn danger" type="button" onClick={onConfirm} disabled={busy}>{busy ? 'Aguarde…' : confirmLabel}</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>, document.body);
|
||||
};
|
||||
58
components/ui/MockupIcons.tsx
Normal file
58
components/ui/MockupIcons.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import React from 'react';
|
||||
|
||||
type MockIconProps = { className?: string };
|
||||
|
||||
const MockIcon: React.FC<MockIconProps & { path: string }> = ({ path, className = 'ph' }) => (
|
||||
<svg className={className} aria-hidden="true" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor" width="1em" height="1em" focusable="false">
|
||||
<path d={path} />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const SearchMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M229.66,218.34l-50.07-50.06a88.11,88.11,0,1,0-11.31,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Z" {...props} />;
|
||||
export const ArrowRightMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M184.49,136.49l-80,80a12,12,0,0,1-17-17L159,128,87.51,56.49a12,12,0,1,1,17-17l80,80A12,12,0,0,1,184.49,136.49Z" {...props} />;
|
||||
export const PlayMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z" {...props} />;
|
||||
export const CheckMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm45.66,85.66-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35a8,8,0,0,1,11.32,11.32Z" {...props} />;
|
||||
export const ClockMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm64-88a8,8,0,0,1-8,8H128a8,8,0,0,1-8-8V72a8,8,0,0,1,16,0v48h48A8,8,0,0,1,192,128Z" {...props} />;
|
||||
export const DownloadMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40a8,8,0,0,0-11.32-11.32L136,124.69V32a8,8,0,0,0-16,0v92.69L93.66,98.34a8,8,0,0,0-11.32,11.32Z" {...props} />;
|
||||
export const ChatMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M128,24A104,104,0,0,0,36.18,176.88L24.83,210.93a16,16,0,0,0,20.24,20.24l34.05-11.35A104,104,0,1,0,128,24Zm0,192a87.87,87.87,0,0,1-44.06-11.81,8,8,0,0,0-6.54-.67L40,216,52.47,178.6a8,8,0,0,0-.66-6.54A88,88,0,1,1,128,216Z" {...props} />;
|
||||
export const SaveMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M184,32H72A16,16,0,0,0,56,48V224a8,8,0,0,0,12.24,6.78L128,193.43l59.77,37.35A8,8,0,0,0,200,224V48A16,16,0,0,0,184,32Zm0,177.57-51.77-32.35a8,8,0,0,0-8.48,0L72,209.57V48H184Z" {...props} />;
|
||||
export const UserMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M230.92,212c-15.23-26.33-38.7-45.21-66.09-54.16a72,72,0,1,0-73.66,0C63.78,166.78,40.31,185.66,25.08,212a8,8,0,1,0,13.85,8c18.84-32.56,52.14-52,89.07-52s70.23,19.44,89.07,52a8,8,0,1,0,13.85-8ZM72,96a56,56,0,1,1,56,56A56.06,56.06,0,0,1,72,96Z" {...props} />;
|
||||
export const BooksMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M231.65,194.55,198.46,36.75a16,16,0,0,0-19-12.39L132.65,34.42a16.08,16.08,0,0,0-12.3,19l33.19,157.8A16,16,0,0,0,169.16,224a16.25,16.25,0,0,0,3.38-.36l46.81-10.06A16.09,16.09,0,0,0,231.65,194.55ZM136,50.15c0-.06,0-.09,0-.09l46.8-10,3.33,15.87L139.33,66Zm6.62,31.47,46.82-10.05,3.34,15.9L146,97.53Zm6.64,31.57,46.82-10.06,13.3,63.24-46.82,10.06ZM216,197.94l-46.8,10-3.33-15.87L212.67,182,216,197.85C216,197.91,216,197.94,216,197.94ZM104,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16h48a16,16,0,0,0,16-16V48A16,16,0,0,0,104,32ZM56,48h48V64H56Zm0,32h48v96H56Zm48,128H56V192h48v16Z" {...props} />;
|
||||
export const GearMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M128,80a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Zm88-29.84q.06-2.16,0-4.32l14.92-18.64a8,8,0,0,0,1.48-7.06,107.21,107.21,0,0,0-10.88-26.25,8,8,0,0,0-6-3.93l-23.72-2.64q-1.48-1.56-3-3L186,40.54a8,8,0,0,0-3.94-6,107.71,107.71,0,0,0-26.25-10.87,8,8,0,0,0-7.06,1.49L130.16,40Q128,40,125.84,40L107.2,25.11a8,8,0,0,0-7.06-1.48A107.6,107.6,0,0,0,73.89,34.51a8,8,0,0,0-3.93,6L67.32,64.27q-1.56,1.49-3,3L40.54,70a8,8,0,0,0-6,3.94,107.71,107.71,0,0,0-10.87,26.25,8,8,0,0,0,1.49,7.06L40,125.84Q40,128,40,130.16L25.11,148.8a8,8,0,0,0-1.48,7.06,107.21,107.21,0,0,0,10.88,26.25,8,8,0,0,0,6,3.93l23.72,2.64q1.49,1.56,3,3L70,215.46a8,8,0,0,0,3.94,6,107.71,107.71,0,0,0,26.25,10.87,8,8,0,0,0,7.06-1.49L125.84,216q2.16.06,4.32,0l18.64,14.92a8,8,0,0,0,7.06,1.48,107.21,107.21,0,0,0,26.25-10.88,8,8,0,0,0,3.93-6l2.64-23.72q1.56-1.48,3-3L215.46,186a8,8,0,0,0,6-3.94,107.71,107.71,0,0,0,10.87-26.25,8,8,0,0,0-1.49-7.06Zm-16.1-6.5a73.93,73.93,0,0,1,0,8.68,8,8,0,0,0,1.74,5.48l14.19,17.73a91.57,91.57,0,0,1-6.23,15L187,173.11a8,8,0,0,0-5.1,2.64,74.11,74.11,0,0,1-6.14,6.14,8,8,0,0,0-2.64,5.1l-2.51,22.58a91.32,91.32,0,0,1-15,6.23l-17.74-14.19a8,8,0,0,0-5-1.75h-.48a73.93,73.93,0,0,1-8.68,0,8,8,0,0,0-5.48,1.74L100.45,215.8a91.57,91.57,0,0,1-15-6.23L82.89,187a8,8,0,0,0-2.64-5.1,74.11,74.11,0,0,1-6.14-6.14,8,8,0,0,0-5.1-2.64L46.43,170.6a91.32,91.32,0,0,1-6.23-15l14.19-17.74a8,8,0,0,0,1.74-5.48,73.93,73.93,0,0,1,0-8.68,8,8,0,0,0-1.74-5.48L40.2,100.45a91.57,91.57,0,0,1,6.23-15L69,82.89a8,8,0,0,0,5.1-2.64,74.11,74.11,0,0,1,6.14-6.14A8,8,0,0,0,82.89,69L85.4,46.43a91.32,91.32,0,0,1,15-6.23l17.74,14.19a8,8,0,0,0,5.48,1.74,73.93,73.93,0,0,1,8.68,0,8,8,0,0,0,5.48-1.74L155.55,40.2a91.57,91.57,0,0,1,15,6.23L173.11,69a8,8,0,0,0,2.64,5.1,74.11,74.11,0,0,1,6.14,6.14,8,8,0,0,0,5.1,2.64l22.58,2.51a91.32,91.32,0,0,1,6.23,15l-14.19,17.74A8,8,0,0,0,199.87,123.66Z" {...props} />;
|
||||
export const SignOutMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M120,216a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H56V208h56A8,8,0,0,1,120,216Zm109.66-93.66-40-40a8,8,0,0,0-11.32,11.32L204.69,120H112a8,8,0,0,0,0,16h92.69l-26.35,26.34a8,8,0,0,0,11.32,11.32l40-40A8,8,0,0,0,229.66,122.34Z" {...props} />;
|
||||
export const UploadMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0ZM93.66,77.66,120,51.31V144a8,8,0,0,0,16,0V51.31l26.34,26.35a8,8,0,0,0,11.32-11.32l-40-40a8,8,0,0,0-11.32,0l-40,40A8,8,0,0,0,93.66,77.66Z" {...props} />;
|
||||
export const PlusMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z" {...props} />;
|
||||
export const EditMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM92.69,208H48V163.31l88-88L180.69,120ZM192,108.68,147.31,64l24-24L216,84.68Z" {...props} />;
|
||||
export const DragMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M104,60A12,12,0,1,1,92,48,12,12,0,0,1,104,60Zm60,12a12,12,0,1,0-12-12A12,12,0,0,0,164,72ZM92,116a12,12,0,1,0,12,12A12,12,0,0,0,92,116Zm72,0a12,12,0,1,0,12,12A12,12,0,0,0,164,116ZM92,184a12,12,0,1,0,12,12A12,12,0,0,0,92,184Zm72,0a12,12,0,1,0,12,12A12,12,0,0,0,164,184Z" {...props} />;
|
||||
export const MoreMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M140,128a12,12,0,1,1-12-12A12,12,0,0,1,140,128ZM128,72a12,12,0,1,0-12-12A12,12,0,0,0,128,72Zm0,112a12,12,0,1,0,12,12A12,12,0,0,0,128,184Z" {...props} />;
|
||||
export const VideoMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M251.77,73a8,8,0,0,0-8.21.39L208,97.05V72a16,16,0,0,0-16-16H32A16,16,0,0,0,16,72V184a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V159l35.56,23.71A8,8,0,0,0,248,184a8,8,0,0,0,8-8V80A8,8,0,0,0,251.77,73ZM192,184H32V72H192V184Zm48-22.95-32-21.33V116.28L240,95Z" {...props} />;
|
||||
export const CheckCircleMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z" {...props} />;
|
||||
export const SpinnerMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm88,88H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z" {...props} />;
|
||||
export const WarningCircleMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z" {...props} />;
|
||||
export const SunMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M120,40V16a8,8,0,0,1,16,0V40a8,8,0,0,1-16,0Zm72,88a64,64,0,1,1-64-64A64.07,64.07,0,0,1,192,128Zm-16,0a48,48,0,1,0-48,48A48.05,48.05,0,0,0,176,128ZM58.34,69.66A8,8,0,0,0,69.66,58.34l-16-16A8,8,0,0,0,42.34,53.66Zm0,116.68-16,16a8,8,0,0,0,11.32,11.32l16-16a8,8,0,0,0-11.32-11.32ZM192,72a8,8,0,0,0,5.66-2.34l16-16a8,8,0,0,0-11.32-11.32l-16,16A8,8,0,0,0,192,72Zm5.66,114.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32-11.32ZM48,128a8,8,0,0,0-8-8H16a8,8,0,0,0,0,16H40A8,8,0,0,0,48,128Zm80,80a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V216A8,8,0,0,0,128,208Zm112-88H216a8,8,0,0,0,0,16h24a8,8,0,0,0,0-16Z" {...props} />;
|
||||
export const CompassMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216ZM172.42,72.84l-64,32a8.05,8.05,0,0,0-3.58,3.58l-32,64A8,8,0,0,0,80,184a8.1,8.1,0,0,0,3.58-.84l64-32a8.05,8.05,0,0,0,3.58-3.58l32-64a8,8,0,0,0-10.74-10.74ZM138,138,97.89,158.11,118,118l40.15-20.07Z" {...props} />;
|
||||
export const ChevronDownMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M216.49,104.49l-80,80a12,12,0,0,1-17,0l-80-80a12,12,0,0,1,17-17L128,159l71.51-71.52a12,12,0,0,1,17,17Z" {...props} />;
|
||||
export const PathMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M200,168a32.06,32.06,0,0,0-31,24H72a32,32,0,0,1,0-64h96a40,40,0,0,0,0-80H72a8,8,0,0,0,0,16h96a24,24,0,0,1,0,48H72a48,48,0,0,0,0,96h97a32,32,0,1,0,31-40Zm0,48a16,16,0,1,1,16-16A16,16,0,0,1,200,216Z" {...props} />;
|
||||
export const ChatsMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M232.07,186.76a80,80,0,0,0-62.5-114.17A80,80,0,1,0,23.93,138.76l-7.27,24.71a16,16,0,0,0,19.87,19.87l24.71-7.27a80.39,80.39,0,0,0,25.18,7.35,80,80,0,0,0,108.34,40.65l24.71,7.27a16,16,0,0,0,19.87-19.86ZM62,159.5a8.28,8.28,0,0,0-2.26.32L32,168l8.17-27.76a8,8,0,0,0-.63-6,64,64,0,1,1,26.26,26.26A8,8,0,0,0,62,159.5Zm153.79,28.73L224,216l-27.76-8.17a8,8,0,0,0-6,.63,64.05,64.05,0,0,1-85.87-24.88A79.93,79.93,0,0,0,174.7,89.71a64,64,0,0,1,41.75,92.48A8,8,0,0,0,215.82,188.23Z" {...props} />;
|
||||
export const TeacherMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M216,40H40A16,16,0,0,0,24,56V200a16,16,0,0,0,16,16H53.39a8,8,0,0,0,7.23-4.57,48,48,0,0,1,86.76,0,8,8,0,0,0,7.23,4.57H216a16,16,0,0,0,16-16V56A16,16,0,0,0,216,40ZM80,144a24,24,0,1,1,24,24A24,24,0,0,1,80,144Zm136,56H159.43a64.39,64.39,0,0,0-28.83-26.16,40,40,0,1,0-53.2,0A64.39,64.39,0,0,0,48.57,200H40V56H216ZM56,96V80a8,8,0,0,1,8-8H192a8,8,0,0,1,8,8v96a8,8,0,0,1-8,8H176a8,8,0,0,1,0-16h8V88H72v8a8,8,0,0,1-16,0Z" {...props} />;
|
||||
export const FolderMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M216,72H130.67L102.93,51.2a16.12,16.12,0,0,0-9.6-3.2H40A16,16,0,0,0,24,64V200a16,16,0,0,0,16,16H216.89A15.13,15.13,0,0,0,232,200.89V88A16,16,0,0,0,216,72Zm0,128H40V64H93.33L123.2,86.4A8,8,0,0,0,128,88h88Z" {...props} />;
|
||||
export const TrayMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32Zm0,16V152h-28.7A15.86,15.86,0,0,0,168,156.69L148.69,176H107.31L88,156.69A15.86,15.86,0,0,0,76.69,152H48V48Zm0,160H48V168H76.69L96,187.31A15.86,15.86,0,0,0,107.31,192h41.38A15.86,15.86,0,0,0,160,187.31L179.31,168H208v40ZM90.34,125.66a8,8,0,0,1,11.32-11.32L120,132.69V72a8,8,0,0,1,16,0v60.69l18.34-18.35a8,8,0,0,1,11.32,11.32l-32,32a8,8,0,0,1-11.32,0Z" {...props} />;
|
||||
export const ArrowLeftMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M168.49,199.51a12,12,0,0,1-17,17l-80-80a12,12,0,0,1,0-17l80-80a12,12,0,0,1,17,17L97,128Z" {...props} />;
|
||||
export const PauseMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z" {...props} />;
|
||||
export const MoonMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M233.54,142.23a8,8,0,0,0-8-2,88.08,88.08,0,0,1-109.8-109.8,8,8,0,0,0-10-10,104.84,104.84,0,0,0-52.91,37A104,104,0,0,0,136,224a103.09,103.09,0,0,0,62.52-20.88,104.84,104.84,0,0,0,37-52.91A8,8,0,0,0,233.54,142.23ZM188.9,190.34A88,88,0,0,1,65.66,67.11a89,89,0,0,1,31.4-26A106,106,0,0,0,96,56,104.11,104.11,0,0,0,200,160a106,106,0,0,0,14.92-1.06A89,89,0,0,1,188.9,190.34Z" {...props} />;
|
||||
export const UsersMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M117.25,157.92a60,60,0,1,0-66.5,0A95.83,95.83,0,0,0,3.53,195.63a8,8,0,1,0,13.4,8.74,80,80,0,0,1,134.14,0,8,8,0,0,0,13.4-8.74A95.83,95.83,0,0,0,117.25,157.92ZM40,108a44,44,0,1,1,44,44A44.05,44.05,0,0,1,40,108Zm210.14,98.7a8,8,0,0,1-11.07-2.33A79.83,79.83,0,0,0,172,168a8,8,0,0,1,0-16,44,44,0,1,0-16.34-84.87,8,8,0,1,1-5.94-14.85,60,60,0,0,1,55.53,105.64,95.83,95.83,0,0,1,47.22,37.71A8,8,0,0,1,250.14,206.7Z" {...props} />;
|
||||
export const EyeMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.47,133.47,0,0,1,25,128,133.33,133.33,0,0,1,48.07,97.25C70.33,75.19,97.22,64,128,64s57.67,11.19,79.93,33.25A133.46,133.46,0,0,1,231.05,128C223.84,141.46,192.43,192,128,192Zm0-112a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Z" {...props} />;
|
||||
|
||||
export const PdfMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M224,152a8,8,0,0,1-8,8H192v16h16a8,8,0,0,1,0,16H192v16a8,8,0,0,1-16,0V152a8,8,0,0,1,8-8h32A8,8,0,0,1,224,152ZM92,172a28,28,0,0,1-28,28H56v8a8,8,0,0,1-16,0V152a8,8,0,0,1,8-8H64A28,28,0,0,1,92,172Zm-16,0a12,12,0,0,0-12-12H56v24h8A12,12,0,0,0,76,172Zm88,8a36,36,0,0,1-36,36H112a8,8,0,0,1-8-8V152a8,8,0,0,1,8-8h16A36,36,0,0,1,164,180Zm-16,0a20,20,0,0,0-20-20h-8v40h8A20,20,0,0,0,148,180ZM40,112V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0ZM160,80h28.69L160,51.31Z" {...props} />;
|
||||
export const XlsMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M156,208a8,8,0,0,1-8,8H120a8,8,0,0,1-8-8V152a8,8,0,0,1,16,0v48h20A8,8,0,0,1,156,208ZM92.65,145.49a8,8,0,0,0-11.16,1.86L68,166.24,54.51,147.35a8,8,0,1,0-13,9.3L58.17,180,41.49,203.35a8,8,0,0,0,13,9.3L68,193.76l13.49,18.89a8,8,0,0,0,13-9.3L77.83,180l16.68-23.35A8,8,0,0,0,92.65,145.49Zm98.94,25.82c-4-1.16-8.14-2.35-10.45-3.84-1.25-.82-1.23-1-1.12-1.9a4.54,4.54,0,0,1,2-3.67c4.6-3.12,15.34-1.72,19.82-.56a8,8,0,0,0,4.07-15.48c-2.11-.55-21-5.22-32.83,2.76a20.58,20.58,0,0,0-8.95,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.33-2.15,3.93-4.6,3.06-15.16,1.55-19.54.35A8,8,0,0,0,173.93,214a60.63,60.63,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.81,20.81,0,0,0,9.18-15.23C218,179,201.48,174.17,191.59,171.31ZM40,112V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88v24a8,8,0,1,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0ZM160,80h28.68L160,51.31Z" {...props} />;
|
||||
export const ZipMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M184,144H168a8,8,0,0,0-8,8v56a8,8,0,0,0,16,0v-8h8a28,28,0,0,0,0-56Zm0,40h-8V160h8a12,12,0,0,1,0,24Zm-48-32v56a8,8,0,0,1-16,0V152a8,8,0,0,1,16,0ZM96,208a8,8,0,0,1-8,8H56a8,8,0,0,1-7-12l25.16-44H56a8,8,0,0,1,0-16H88a8,8,0,0,1,7,12L69.79,200H88A8,8,0,0,1,96,208ZM213.66,82.34l-56-56A8,8,0,0,0,152,24H56A16,16,0,0,0,40,40v72a8,8,0,0,0,16,0V40h88V88a8,8,0,0,0,8,8h48v16a8,8,0,0,0,16,0V88A8,8,0,0,0,213.66,82.34ZM160,80V51.31L188.69,80Z" {...props} />;
|
||||
export const DocMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M52,144H36a8,8,0,0,0-8,8v56a8,8,0,0,0,8,8H52a36,36,0,0,0,0-72Zm0,56H44V160h8a20,20,0,0,1,0,40Zm169.53-4.91a8,8,0,0,1,.25,11.31A30.06,30.06,0,0,1,200,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,200,160c-8.82,0-16,9-16,20s7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,221.53,195.09ZM128,144c-17.65,0-32,16.15-32,36s14.35,36,32,36,32-16.15,32-36S145.65,144,128,144Zm0,56c-8.82,0-16-9-16-20s7.18-20,16-20,16,9,16,20S136.82,200,128,200ZM48,120a8,8,0,0,0,8-8V40h88V88a8,8,0,0,0,8,8h48v16a8,8,0,0,0,16,0V88a8,8,0,0,0-2.34-5.66l-56-56A8,8,0,0,0,152,24H56A16,16,0,0,0,40,40v72A8,8,0,0,0,48,120ZM160,51.31,188.69,80H160Z" {...props} />;
|
||||
|
||||
export const ExploreTabMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216ZM172.42,72.84l-64,32a8.05,8.05,0,0,0-3.58,3.58l-32,64A8,8,0,0,0,80,184a8.1,8.1,0,0,0,3.58-.84l64-32a8.05,8.05,0,0,0,3.58-3.58l32-64a8,8,0,0,0-10.74-10.74ZM138,138,97.89,158.11,118,118l40.15-20.07Z" {...props} />;
|
||||
export const ExploreTabFilledMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm51.58,57.79-32,64a4.08,4.08,0,0,1-1.79,1.79l-64,32a4,4,0,0,1-5.37-5.37l32-64a4.08,4.08,0,0,1,1.79-1.79l64-32A4,4,0,0,1,179.58,81.79Z" {...props} />;
|
||||
export const TrailsTabMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M200,168a32.06,32.06,0,0,0-31,24H72a32,32,0,0,1,0-64h96a40,40,0,0,0,0-80H72a8,8,0,0,0,0,16h96a24,24,0,0,1,0,48H72a48,48,0,0,0,0,96h97a32,32,0,1,0,31-40Zm0,48a16,16,0,1,1,16-16A16,16,0,0,1,200,216Z" {...props} />;
|
||||
export const TrailsTabFilledMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M228,200a28,28,0,0,1-54.83,8H72a48,48,0,0,1,0-96h96a24,24,0,0,0,0-48H72a8,8,0,0,1,0-16h96a40,40,0,0,1,0,80H72a32,32,0,0,0,0,64H173.17A28,28,0,0,1,228,200Z" {...props} />;
|
||||
export const SearchTabMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M229.66,218.34l-50.07-50.06a88.11,88.11,0,1,0-11.31,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Z" {...props} />;
|
||||
export const SearchTabFilledMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M168,112a56,56,0,1,1-56-56A56,56,0,0,1,168,112Zm61.66,117.66a8,8,0,0,1-11.32,0l-50.06-50.07a88,88,0,1,1,11.32-11.31l50.06,50.06A8,8,0,0,1,229.66,229.66ZM112,184a72,72,0,1,0-72-72A72.08,72.08,0,0,0,112,184Z" {...props} />;
|
||||
export const CommunityTabMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M232.07,186.76a80,80,0,0,0-62.5-114.17A80,80,0,1,0,23.93,138.76l-7.27,24.71a16,16,0,0,0,19.87,19.87l24.71-7.27a80.39,80.39,0,0,0,25.18,7.35,80,80,0,0,0,108.34,40.65l24.71,7.27a16,16,0,0,0,19.87-19.86ZM62,159.5a8.28,8.28,0,0,0-2.26.32L32,168l8.17-27.76a8,8,0,0,0-.63-6,64,64,0,1,1,26.26,26.26A8,8,0,0,0,62,159.5Zm153.79,28.73L224,216l-27.76-8.17a8,8,0,0,0-6,.63,64.05,64.05,0,0,1-85.87-24.88A79.93,79.93,0,0,0,174.7,89.71a64,64,0,0,1,41.75,92.48A8,8,0,0,0,215.82,188.23Z" {...props} />;
|
||||
export const CommunityTabFilledMockIcon: React.FC<MockIconProps> = (props) => <MockIcon path="M232.07,186.76a80,80,0,0,0-62.5-114.17A80,80,0,1,0,23.93,138.76l-7.27,24.71a16,16,0,0,0,19.87,19.87l24.71-7.27a80.39,80.39,0,0,0,25.18,7.35,80,80,0,0,0,108.34,40.65l24.71,7.27a16,16,0,0,0,19.87-19.86Zm-16.25,1.47L224,216l-27.76-8.17a8,8,0,0,0-6,.63,64.05,64.05,0,0,1-85.87-24.88A79.93,79.93,0,0,0,174.7,89.71a64,64,0,0,1,41.75,92.48A8,8,0,0,0,215.82,188.23Z" {...props} />;
|
||||
77
components/ui/Select.tsx
Normal file
77
components/ui/Select.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { CheckMockIcon, ChevronDownMockIcon } from './MockupIcons';
|
||||
|
||||
export type SelectOption = { value: string; label: string };
|
||||
|
||||
interface SelectProps {
|
||||
value: string;
|
||||
options: SelectOption[];
|
||||
onChange: (value: string) => void;
|
||||
ariaLabel: string;
|
||||
disabled?: boolean;
|
||||
variant?: 'default' | 'field' | 'mobile';
|
||||
}
|
||||
|
||||
/** Custom listbox used instead of the browser's native select. */
|
||||
export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLabel, disabled = false, variant = 'default' }) => {
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [position, setPosition] = useState<{ top: number; left: number; width: number } | null>(null);
|
||||
const selected = options.find((option) => option.value === value);
|
||||
|
||||
const place = () => {
|
||||
const trigger = triggerRef.current;
|
||||
if (!trigger) return;
|
||||
const rect = trigger.getBoundingClientRect();
|
||||
const width = Math.max(rect.width, 160);
|
||||
const height = Math.min(options.length * 40 + 12, 260);
|
||||
setPosition({
|
||||
top: Math.max(12, Math.min(rect.bottom + 6, window.innerHeight - height - 12)),
|
||||
left: Math.max(12, Math.min(rect.left, window.innerWidth - width - 12)),
|
||||
width,
|
||||
});
|
||||
};
|
||||
|
||||
const toggle = () => {
|
||||
if (disabled) return;
|
||||
if (!open) place();
|
||||
setOpen((current) => !current);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const close = () => setOpen(false);
|
||||
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') setOpen(false); };
|
||||
window.addEventListener('resize', close);
|
||||
window.addEventListener('scroll', close, true);
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
window.removeEventListener('resize', close);
|
||||
window.removeEventListener('scroll', close, true);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
return <>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
className={`select-trigger${variant !== 'default' ? ` ${variant}` : ''}`}
|
||||
disabled={disabled}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-label={ariaLabel}
|
||||
onClick={toggle}
|
||||
>
|
||||
<span className="select-value">{selected?.label ?? ''}</span>
|
||||
<ChevronDownMockIcon className="ph" />
|
||||
</button>
|
||||
{open && position && createPortal(<>
|
||||
<button type="button" className="menu-scrim" aria-label="Fechar lista" onClick={() => setOpen(false)} />
|
||||
<div className="select-menu" role="listbox" aria-label={ariaLabel} style={{ top: position.top, left: position.left, width: position.width }}>
|
||||
{options.map((option) => <button key={option.value} type="button" role="option" aria-selected={option.value === value} onClick={() => { onChange(option.value); setOpen(false); }}><span>{option.label}</span>{option.value === value && <CheckMockIcon className="ph" />}</button>)}
|
||||
</div>
|
||||
</>, document.body)}
|
||||
</>;
|
||||
};
|
||||
13
components/ui/Switch.tsx
Normal file
13
components/ui/Switch.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import React from 'react';
|
||||
|
||||
interface SwitchProps {
|
||||
checked: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/** Custom switch matching the mockup, instead of a native checkbox. */
|
||||
export const Switch: React.FC<SwitchProps> = ({ checked, onChange, label, disabled = false }) => (
|
||||
<button type="button" role="switch" aria-checked={checked} aria-label={label} className="sw" disabled={disabled} onClick={() => onChange(!checked)} />
|
||||
);
|
||||
Reference in New Issue
Block a user