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.
144 lines
11 KiB
TypeScript
144 lines
11 KiB
TypeScript
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()} />
|
||
</>;
|
||
};
|