218 lines
10 KiB
TypeScript
218 lines
10 KiB
TypeScript
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 { BellIcon, 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';
|
|
import { getNotifications } from '../../services/notifications';
|
|
|
|
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 [unreadNotifications, setUnreadNotifications] = useState(0);
|
|
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]);
|
|
|
|
useEffect(() => {
|
|
if (!user) { setUnreadNotifications(0); return; }
|
|
let cancelled = false;
|
|
const refresh = () => {
|
|
getNotifications().then((feed) => { if (!cancelled) setUnreadNotifications(feed.unread); }).catch(() => undefined);
|
|
};
|
|
refresh();
|
|
window.addEventListener('compor:notifications-updated', refresh);
|
|
return () => {
|
|
cancelled = true;
|
|
window.removeEventListener('compor:notifications-updated', refresh);
|
|
};
|
|
}, [user?.id, 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 = async () => {
|
|
setMenuOpen(false);
|
|
await 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>
|
|
{user && <Link className="iconbtn notif" to={paths.notifications} aria-label={`Notificações${unreadNotifications ? `, ${unreadNotifications} não lidas` : ''}`} title="Notificações">
|
|
<BellIcon className="ph" />
|
|
{unreadNotifications > 0 && <span className="notif-badge">{unreadNotifications > 9 ? '9+' : unreadNotifications}</span>}
|
|
</Link>}
|
|
</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>
|
|
);
|
|
};
|