Files
FitOS/app/src/components/Layout.tsx

290 lines
11 KiB
TypeScript

import { useState } from 'react';
import { NavLink, Outlet, useNavigate } from 'react-router-dom';
import {
Building2,
CalendarDays,
Dumbbell,
LayoutDashboard,
LogOut,
Mail,
Menu,
MessageSquare,
Play,
User,
Users,
X,
type LucideIcon,
} from 'lucide-react';
import { useAuth } from '../store/auth';
import {
useActiveSession,
useConversations,
useGymInvitations,
useInvitations,
useIsTrainer,
} from '../api/queries';
import { ThemeToggle, Button } from './ui';
import { ToastProvider } from './toast';
import { Topbar } from '../topbar';
import { Brandmark } from './Brandmark';
import { Avatar } from './Avatar';
import { cn } from '../lib/utils';
interface NavItem {
to: string;
label: string;
icon: LucideIcon;
end: boolean;
badge?: number;
}
const NAV: NavItem[] = [
{ to: '/', label: 'Dashboard', icon: LayoutDashboard, end: true },
{ to: '/plans', label: 'Plany', icon: Dumbbell, end: false },
{ to: '/calendar', label: 'Mój kalendarz', icon: CalendarDays, end: false },
{ to: '/profile', label: 'Profil', icon: User, end: false },
];
const GYM_NAV: NavItem = { to: '/gyms', label: 'Siłownie', icon: Building2, end: false };
const TRAINEES_NAV: NavItem = { to: '/trainees', label: 'Podopieczni', icon: Users, end: false };
const INVITATIONS_NAV: NavItem = { to: '/invitations', label: 'Zaproszenia', icon: Mail, end: false };
const MESSAGES_NAV: NavItem = { to: '/messages', label: 'Komunikator', icon: MessageSquare, end: false };
const SIDEBAR_KEY = 'fitos-sidebar-collapsed';
function readCollapsed(): boolean {
try {
return localStorage.getItem(SIDEBAR_KEY) === '1';
} catch {
return false;
}
}
/* Wiersze nawigacji wg Ember: aktywny = tint akcentu + pionowy pasek przy krawędzi. */
function NavLinks({
items,
collapsed,
onNavigate,
}: {
items: NavItem[];
collapsed: boolean;
onNavigate?: () => void;
}) {
return (
<nav className={cn('flex flex-col gap-0.5', collapsed ? 'px-2' : 'px-3')} aria-label="Nawigacja główna">
{items.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.end}
onClick={onNavigate}
title={collapsed ? item.label : undefined}
aria-label={collapsed ? item.label : undefined}
className={({ isActive }) =>
cn(
'relative flex h-[38px] items-center gap-2.5 rounded-[10px] text-[13.5px] font-semibold transition-colors duration-150',
collapsed ? 'justify-center px-0' : 'px-3',
isActive ? 'bg-accent/11 text-accent-text' : 'text-dim hover:bg-line/30 hover:text-ink',
)
}
>
{({ isActive }) => (
<>
{isActive && (
<span
aria-hidden="true"
className={cn(
'absolute bottom-[9px] top-[9px] w-[3px] rounded-full bg-(image:--nav-bar-grad)',
collapsed ? '-left-2' : '-left-3',
)}
/>
)}
<item.icon className="h-[17px] w-[17px] shrink-0" strokeWidth={1.9} />
{!collapsed && <span className="min-w-0 truncate">{item.label}</span>}
{typeof item.badge === 'number' &&
item.badge > 0 &&
(collapsed ? (
<span aria-hidden="true" className="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-accent" />
) : (
<span className="ml-auto flex h-5 min-w-5 items-center justify-center rounded-full bg-accent px-1.5 text-[0.7rem] font-bold text-accent-ink">
{item.badge}
</span>
))}
</>
)}
</NavLink>
))}
</nav>
);
}
export default function Layout() {
const { user, logout } = useAuth();
const navigate = useNavigate();
const [drawerOpen, setDrawerOpen] = useState(false);
const [collapsed, setCollapsed] = useState(readCollapsed);
const toggleCollapsed = () =>
setCollapsed((c) => {
const next = !c;
try {
localStorage.setItem(SIDEBAR_KEY, next ? '1' : '0');
} catch {
// ignore
}
return next;
});
const isTrainer = useIsTrainer();
const { data: invitations } = useInvitations();
const { data: gymInvitations } = useGymInvitations();
const { data: conversations } = useConversations();
// Liczba oczekujących zaproszeń: coaching (trener) + do prywatnych siłowni.
const pendingInvitations =
(invitations?.invitations ?? []).length + (gymInvitations?.invitations ?? []).length;
// Nieprzeczytane wiadomości w komunikatorze (suma per rozmowa).
const unreadMessages = (conversations?.conversations ?? []).reduce((n, c) => n + c.unreadCount, 0);
const { data: activeSessionData } = useActiveSession();
const activeSession = activeSessionData?.session ?? null;
// Aktywna sesja => stały skrót „Trening” w menu (po Kalendarzu), prowadzący do dnia sesji.
const trainingNav: NavItem | null = activeSession
? { to: `/day/${activeSession.dayId}`, label: 'Trening', icon: Play, end: false }
: null;
// „Siłownie” jest zawsze widoczne (wirtualne siłownie są dostępne dla każdego usera).
let navItems: NavItem[] = [...NAV.slice(0, 3), GYM_NAV, NAV[3]];
if (trainingNav) navItems = [...navItems.slice(0, 3), trainingNav, ...navItems.slice(3)];
// „Komunikator” jest zawsze widoczny (dla każdego zalogowanego), badge = nieprzeczytane.
navItems = [
...navItems.slice(0, -1),
{ ...MESSAGES_NAV, badge: unreadMessages },
navItems[navItems.length - 1],
];
if (isTrainer) navItems = [...navItems.slice(0, -1), TRAINEES_NAV, navItems[navItems.length - 1]];
if (pendingInvitations > 0) navItems = [...navItems.slice(0, -1), INVITATIONS_NAV, navItems[navItems.length - 1]];
const fullName = [user?.firstName, user?.lastName].filter(Boolean).join(' ') || user?.email || '?';
const roles = [user?.isAdmin ? 'Admin' : null, isTrainer ? 'Trener' : 'Ćwiczący'].filter(Boolean).join(' · ');
const doLogout = async () => {
await logout();
navigate('/login');
};
/* Stopka usera — pełna (sidebar/desktop i drawer). */
const footerFull = (
<div className="mt-auto border-t border-line px-4 pb-4 pt-3">
<div className="mb-3 flex items-center gap-2.5">
<Avatar name={fullName} size={32} />
<div className="min-w-0">
<div className="truncate text-[13px] font-bold">{user?.firstName || user?.email}</div>
<div className="text-[11.5px] text-dim">{roles}</div>
</div>
</div>
<div className="flex items-center gap-2">
<ThemeToggle />
<Button variant="secondary" size="sm" className="flex-1" onClick={doLogout}>
<LogOut className="w-4 h-4" />
Wyloguj
</Button>
</div>
</div>
);
/* Stopka usera — rail (zwinięty sidebar): avatar + ikony. */
const footerRail = (
<div className="mt-auto flex flex-col items-center gap-2.5 border-t border-line px-2 pb-4 pt-3">
<Avatar name={fullName} size={32} />
<ThemeToggle />
<button
type="button"
onClick={doLogout}
aria-label="Wyloguj"
title="Wyloguj"
className="grid h-8 w-8 cursor-pointer place-items-center rounded-[10px] border border-line bg-card text-dim shadow-card transition-colors hover:border-danger/45 hover:text-danger"
>
<LogOut className="h-4 w-4" />
</button>
</div>
);
return (
<ToastProvider>
<div className="min-h-screen md:flex">
{/* Mobile drawer (telefon): ten sam zestaw pozycji co sidebar, zawsze rozwinięty */}
{drawerOpen && (
<div className="fixed inset-0 z-50 md:hidden">
<div
className="absolute inset-0 animate-in fade-in-0 bg-black/60 duration-150"
onClick={() => setDrawerOpen(false)}
/>
<aside className="absolute left-0 top-0 flex h-full w-72 animate-in slide-in-from-left flex-col border-r border-line bg-card duration-200">
<div className="flex items-center justify-between px-4 py-4">
<div className="flex items-center gap-2.5">
<Brandmark size={26} />
<span className="font-display text-[1.05rem] font-bold tracking-[-0.02em]">FitOS</span>
</div>
<button
type="button"
onClick={() => setDrawerOpen(false)}
aria-label="Zamknij menu"
className="-m-2 cursor-pointer p-2 text-dim hover:text-ink"
>
<X className="h-5 w-5" />
</button>
</div>
<NavLinks items={navItems} collapsed={false} onNavigate={() => setDrawerOpen(false)} />
{footerFull}
</aside>
</div>
)}
{/* Desktop/tablet sidebar: domyślnie rozwinięty, hamburger zwija do raila ~70px */}
<aside
className={cn(
'hidden h-screen flex-col border-r border-line bg-card transition-[width] duration-200 md:sticky md:top-0 md:flex',
collapsed ? 'md:w-[70px]' : 'md:w-60',
)}
>
{/* zwinięty: hamburger zastępuje logotyp (ta sama pozycja u góry raila) */}
<div className={cn('flex items-center py-4', collapsed ? 'justify-center px-2' : 'gap-2.5 px-4')}>
{collapsed ? (
<button
type="button"
onClick={toggleCollapsed}
aria-label="Rozwiń menu"
title="Rozwiń menu"
className="grid h-7 w-7 flex-none cursor-pointer place-items-center rounded-[10px] border border-line bg-card text-dim shadow-card transition-colors hover:text-ink"
>
<Menu className="h-4 w-4" />
</button>
) : (
<>
<div className="flex min-w-0 items-center gap-2.5">
<Brandmark size={26} />
<span className="font-display text-[1.05rem] font-bold tracking-[-0.02em]">FitOS</span>
</div>
<button
type="button"
onClick={toggleCollapsed}
aria-label="Zwiń menu"
title="Zwiń menu"
className="ml-auto grid h-7 w-7 flex-none cursor-pointer place-items-center rounded-[10px] border border-line bg-card text-dim shadow-card transition-colors hover:text-ink"
>
<Menu className="h-4 w-4" />
</button>
</>
)}
</div>
<NavLinks items={navItems} collapsed={collapsed} />
{collapsed ? footerRail : footerFull}
</aside>
<main className="min-w-0 flex-1">
<Topbar onMenuOpen={() => setDrawerOpen(true)} />
<div className="mx-auto max-w-5xl px-4 pb-24 pt-6 md:px-8 md:pb-10 md:pt-8">
<Outlet />
</div>
</main>
</div>
</ToastProvider>
);
}