feat(design): add AppShell, MobileShell and the notifications drawer

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-01 09:31:12 +08:00
co-authored by Claude Haiku 4.5
parent 32dd42ac79
commit 9ba708ecb7
10 changed files with 482 additions and 311 deletions
+3 -10
View File
@@ -2,7 +2,7 @@ export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import { getSession } from '@/lib/auth/get-session'
import { Sidebar } from '@/components/layout/sidebar'
import { AppShell } from '@/components/layout/app-shell'
export default async function ProtectedLayout({
children,
@@ -13,15 +13,8 @@ export default async function ProtectedLayout({
if (!session) redirect('/login')
return (
<div className="min-h-screen bg-ground">
<Sidebar
role={session.role}
userName={session.name}
userEmail=""
/>
<div className="sm:ml-60 pb-16 sm:pb-0">
<AppShell role={session.role} userName={session.name}>
{children}
</div>
</div>
</AppShell>
)
}
+135
View File
@@ -0,0 +1,135 @@
'use client'
import { useEffect, useRef } from 'react'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { LogOut, Search, ShieldCheck, User } from 'lucide-react'
import { NotificationBell } from '@/components/notifications/bell'
import { Avatar } from '@/components/ui/avatar'
import { cx } from '@/components/ui/cx'
import { MobileShell } from './mobile-shell'
import { isActivePath, navItemsFor, searchHrefFor } from './nav-items'
const ITEM = 'flex items-center gap-2.5 h-8 px-2.5 rounded-md text-[13px] w-full text-left'
const ITEM_ACTIVE = 'bg-surface text-ink font-semibold shadow-chip'
const ITEM_IDLE = 'text-ink-3 hover:bg-rule-2'
export function AppShell({
role,
userName,
children,
}: {
role: string
userName: string
children: React.ReactNode
}) {
const pathname = usePathname()
const router = useRouter()
const items = navItemsFor(role)
const searchHref = searchHrefFor(role)
const searchRef = useRef<HTMLInputElement>(null)
const displayName = userName || 'User'
const roleLabel = role.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault()
searchRef.current?.focus()
}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [])
const logout = async () => {
await fetch('/api/auth/logout', { method: 'POST' })
router.push('/login')
router.refresh()
}
const accountActive = pathname === '/account'
return (
<div className="min-h-screen bg-ground">
<header className="hidden md:flex fixed top-0 left-0 right-0 z-40 h-14 items-center justify-between gap-4 pl-5 pr-4 bg-topbar">
<div className="flex items-center gap-2.5 w-56">
<span className="inline-grid place-items-center w-7 h-7 rounded-md bg-accent text-white">
<ShieldCheck size={16} strokeWidth={2} aria-hidden />
</span>
<span className="text-[15px] font-[650] text-white tracking-tight">IMS</span>
<span className="text-[13px] text-neutral-400">Setia HSE</span>
</div>
{searchHref ? (
<form action={searchHref} method="get" className="flex-1 max-w-[520px]">
<label className="flex items-center gap-2 h-[34px] px-2.5 rounded-[10px] bg-ink-2 shadow-[inset_0_0_0_1px_var(--color-ink-3)] text-neutral-400 text-[13px]">
<Search size={16} strokeWidth={2} aria-hidden />
<input
ref={searchRef}
name="q"
type="search"
placeholder="Search incidents"
aria-label="Search incidents"
className="flex-1 bg-transparent text-white placeholder:text-neutral-400 outline-none"
/>
<kbd className="font-mono text-[11px] text-neutral-400">⌘K</kbd>
</label>
</form>
) : (
<div className="flex-1" />
)}
<div className="flex items-center gap-2 w-56 justify-end">
<NotificationBell />
<div className="flex items-center gap-2 py-1 pl-1 pr-2.5 rounded-md bg-ink-2">
<Avatar name={displayName} />
<span className="text-[13px] text-rule-2 max-w-32 truncate">{displayName}</span>
</div>
</div>
</header>
<aside className="hidden md:flex fixed top-14 left-0 bottom-0 z-30 w-60 flex-col gap-0.5 p-3 bg-rule border-r border-rule-2">
{items.map(item => {
const active = isActivePath(item.href, pathname)
const Icon = item.icon
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={cx(ITEM, active ? ITEM_ACTIVE : ITEM_IDLE)}
>
<Icon size={16} strokeWidth={2} className={active ? 'text-accent' : 'text-ink-3'} aria-hidden />
<span className="flex-1">{item.label}</span>
</Link>
)
})}
<div className="flex-1" />
<div className="flex flex-col gap-0.5 pt-2.5 border-t border-rule-2">
<div className="px-2.5 pb-1">
<p className="text-[13px] font-semibold truncate">{displayName}</p>
<p className="text-xs text-muted truncate">{roleLabel}</p>
</div>
<Link
href="/account"
aria-current={accountActive ? 'page' : undefined}
className={cx(ITEM, accountActive ? ITEM_ACTIVE : ITEM_IDLE)}
>
<User size={16} strokeWidth={2} className={accountActive ? 'text-accent' : 'text-ink-3'} aria-hidden />
Account
</Link>
<button type="button" onClick={logout} className={cx(ITEM, ITEM_IDLE, 'cursor-pointer')}>
<LogOut size={16} strokeWidth={2} className="text-ink-3" aria-hidden />
Log out
</button>
<p className="px-2.5 pt-2 text-xs text-faint">v1.2.2</p>
</div>
</aside>
<main className="md:pl-60 md:pt-14 pb-16 md:pb-0">{children}</main>
<MobileShell items={items} pathname={pathname} onLogout={logout} />
</div>
)
}
+53
View File
@@ -0,0 +1,53 @@
'use client'
import Link from 'next/link'
import { LogOut } from 'lucide-react'
import { isActivePath, type NavItem } from './nav-items'
import { cx } from '@/components/ui/cx'
export function MobileShell({
items,
pathname,
onLogout,
}: {
items: NavItem[]
pathname: string
onLogout: () => void
}) {
const tabs = items.slice(0, 4)
return (
<nav
aria-label="Mobile"
className="md:hidden fixed bottom-0 left-0 right-0 z-40 flex bg-surface border-t border-rule pb-[env(safe-area-inset-bottom)]"
>
{tabs.map(item => {
const active = isActivePath(item.href, pathname)
const Icon = item.icon
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={cx(
'flex-1 flex flex-col items-center gap-1 pt-2 pb-1.5 text-[10.5px] font-medium',
active ? 'text-accent' : 'text-faint',
)}
>
<Icon size={22} strokeWidth={1.8} aria-hidden />
<span className="leading-none">{item.label}</span>
</Link>
)
})}
{items.length <= 4 && (
<button
type="button"
onClick={onLogout}
className="flex-1 flex flex-col items-center gap-1 pt-2 pb-1.5 text-[10.5px] font-medium text-faint cursor-pointer"
>
<LogOut size={22} strokeWidth={1.8} aria-hidden />
<span className="leading-none">Log out</span>
</button>
)}
</nav>
)
}
+59
View File
@@ -0,0 +1,59 @@
import {
AlignLeft,
CircleCheck,
ClipboardList,
LayoutDashboard,
Plus,
Settings,
Users,
type LucideIcon,
} from 'lucide-react'
export interface NavItem {
label: string
href: string
icon: LucideIcon
}
const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [
{ label: 'My Reports', href: '/reporter', icon: ClipboardList },
{ label: 'New Incident', href: '/report', icon: Plus },
],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: AlignLeft },
{ label: 'Incidents', href: '/supervisor/incidents', icon: ClipboardList },
],
hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
{ label: 'CAPA', href: '/hse/capa', icon: CircleCheck },
{ label: 'Settings', href: '/hse/settings', icon: Settings },
],
management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }],
capa_owner: [{ label: 'My CAPAs', href: '/capa-owner', icon: CircleCheck }],
admin: [
{ label: 'Admin', href: '/admin', icon: Users },
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
{ label: 'CAPA', href: '/hse/capa', icon: CircleCheck },
{ label: 'Management', href: '/management', icon: AlignLeft },
{ label: 'Settings', href: '/hse/settings', icon: Settings },
],
}
const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
export function navItemsFor(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
}
export function isActivePath(href: string, pathname: string): boolean {
return EXACT_ROOTS.includes(href) ? pathname === href : pathname.startsWith(href)
}
export function searchHrefFor(role: string): string | null {
if (role === 'hse' || role === 'admin') return '/hse/incidents'
if (role === 'supervisor') return '/supervisor/incidents'
return null
}
-202
View File
@@ -1,202 +0,0 @@
'use client'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import {
AlignLeft,
CircleCheck,
ClipboardList,
LayoutDashboard,
LogOut,
Plus,
Settings,
User,
Users,
} from 'lucide-react'
import { NotificationBell } from '@/components/notifications/bell'
interface NavItem {
label: string
href: string
icon: React.ReactNode
}
interface SidebarProps {
role: string
userName: string
userEmail: string
}
const IconGrid = () => <AlignLeft size={20} aria-hidden />
const IconList = () => <ClipboardList size={20} aria-hidden />
const IconCheck = () => <CircleCheck size={20} aria-hidden />
const IconChart = () => <LayoutDashboard size={20} aria-hidden />
const IconSettings = () => <Settings size={20} aria-hidden />
const IconUsers = () => <Users size={20} aria-hidden />
const IconPlus = () => <Plus size={20} aria-hidden />
const IconLogout = () => <LogOut size={16} aria-hidden />
const IconUser = () => <User size={16} aria-hidden />
const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [
{ label: 'My Reports', href: '/reporter', icon: <IconList /> },
{ label: 'New Incident', href: '/report', icon: <IconPlus /> },
],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: <IconGrid /> },
{ label: 'Incidents', href: '/supervisor/incidents', icon: <IconList /> },
],
hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: <IconChart /> },
{ label: 'Incidents', href: '/hse/incidents', icon: <IconList /> },
{ label: 'CAPA', href: '/hse/capa', icon: <IconCheck /> },
{ label: 'Settings', href: '/hse/settings', icon: <IconSettings /> },
],
management: [
{ label: 'Dashboard', href: '/management', icon: <IconChart /> },
],
capa_owner: [
{ label: 'My CAPAs', href: '/capa-owner', icon: <IconCheck /> },
],
admin: [
{ label: 'Admin', href: '/admin', icon: <IconUsers /> },
{ label: 'Dashboard', href: '/hse/dashboard', icon: <IconChart /> },
{ label: 'Incidents', href: '/hse/incidents', icon: <IconList /> },
{ label: 'CAPA', href: '/hse/capa', icon: <IconCheck /> },
{ label: 'Management', href: '/management', icon: <IconGrid /> },
{ label: 'Settings', href: '/hse/settings', icon: <IconSettings /> },
],
}
const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
function isActivePath(href: string, pathname: string): boolean {
return EXACT_ROOTS.includes(href) ? pathname === href : pathname.startsWith(href)
}
function initials(name: string): string {
return name
.split(' ')
.map(w => w[0] ?? '')
.join('')
.toUpperCase()
.slice(0, 2)
}
function useNavItems(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
}
const LINK_BASE = 'flex items-center gap-3 px-3 py-2 text-sm border-l transition-colors'
const LINK_ACTIVE = 'border-accent text-accent-700 font-extrabold bg-accent-100/50'
const LINK_IDLE = 'border-transparent text-ink/70 font-medium hover:bg-ink/7 hover:text-ink'
function NavLink({ item, pathname }: { item: NavItem; pathname: string }) {
const active = isActivePath(item.href, pathname)
return (
<Link
href={item.href}
aria-current={active ? 'page' : undefined}
className={`${LINK_BASE} ${active ? LINK_ACTIVE : LINK_IDLE}`}
>
<span className={active ? 'text-accent-700' : 'text-ink/50'}>{item.icon}</span>
{item.label}
</Link>
)
}
export function Sidebar({ role, userName, userEmail }: SidebarProps) {
const pathname = usePathname()
const router = useRouter()
const items = useNavItems(role)
const mobileItems = items.slice(0, 4)
const logout = async () => {
await fetch('/api/auth/logout', { method: 'POST' })
router.push('/login')
router.refresh()
}
const displayName = userName || userEmail || 'User'
const roleLabel = role.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
const accountActive = pathname === '/account'
return (
<>
{/* Desktop sidebar */}
<aside className="hidden sm:flex fixed left-0 top-0 h-full w-60 bg-ground border-r border-divider flex-col z-40">
<div className="flex items-center justify-between px-4 py-4 border-b border-divider">
<span className="text-lg font-extrabold tracking-tight text-ink">IMS</span>
<NotificationBell />
</div>
<nav className="flex-1 overflow-y-auto py-3">
{items.map(item => (
<NavLink key={item.href} item={item} pathname={pathname} />
))}
</nav>
<div className="border-t border-divider py-3">
<div className="flex items-center gap-2 px-4 py-2 mb-1">
<div className="w-8 h-8 rounded-full bg-accent flex items-center justify-center text-ground text-xs font-extrabold flex-shrink-0">
{initials(displayName)}
</div>
<div className="min-w-0">
<p className="text-sm font-extrabold text-ink truncate">{displayName}</p>
<p className="text-xs text-ink/60 truncate">{roleLabel}</p>
</div>
</div>
<Link
href="/account"
aria-current={accountActive ? 'page' : undefined}
className={`${LINK_BASE} ${accountActive ? LINK_ACTIVE : LINK_IDLE}`}
>
<span className={accountActive ? 'text-accent-700' : 'text-ink/50'}>
<IconUser />
</span>
Account
</Link>
<button
onClick={logout}
className={`${LINK_BASE} ${LINK_IDLE} w-full text-left cursor-pointer`}
>
<span className="text-ink/50"><IconLogout /></span>
Logout
</button>
<div className="mt-3 pt-3 border-t border-divider px-4">
<p className="text-xs text-ink/50">v1.2.2</p>
</div>
</div>
</aside>
{/* Mobile bottom tab bar */}
<nav className="sm:hidden fixed bottom-0 left-0 right-0 bg-ground border-t border-divider flex z-40 safe-area-pb">
{mobileItems.map(item => {
const active = isActivePath(item.href, pathname)
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={`flex-1 flex flex-col items-center gap-1 py-2 text-[10px] font-extrabold transition-colors ${
active ? 'text-accent-700' : 'text-ink/55'
}`}
>
{item.icon}
<span className="leading-none">{item.label}</span>
</Link>
)
})}
{items.length <= 4 && (
<button
onClick={logout}
className="flex-1 flex flex-col items-center gap-1 py-2 text-[10px] font-extrabold text-ink/55 cursor-pointer"
>
<IconLogout />
<span className="leading-none">Logout</span>
</button>
)}
</nav>
</>
)
}
+66 -37
View File
@@ -1,8 +1,10 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { Bell } from 'lucide-react'
import { Drawer } from '@/components/ui/drawer'
import { cx } from '@/components/ui/cx'
type Notification = {
id: string
@@ -14,11 +16,15 @@ type Notification = {
const POLL_MS = 60_000
function isToday(iso: string): boolean {
return new Date(iso).toDateString() === new Date().toDateString()
}
export function NotificationBell() {
const [notifications, setNotifications] = useState<Notification[]>([])
const [unread, setUnread] = useState(0)
const [open, setOpen] = useState(false)
const panelRef = useRef<HTMLDivElement>(null)
const [tab, setTab] = useState<'all' | 'unread'>('all')
const load = useCallback(() => {
fetch('/api/notifications')
@@ -36,15 +42,6 @@ export function NotificationBell() {
return () => clearInterval(id)
}, [load])
useEffect(() => {
if (!open) return
const onClick = (e: MouseEvent) => {
if (panelRef.current && !panelRef.current.contains(e.target as Node)) setOpen(false)
}
document.addEventListener('mousedown', onClick)
return () => document.removeEventListener('mousedown', onClick)
}, [open])
const markAllRead = () => {
fetch('/api/notifications', {
method: 'POST',
@@ -58,62 +55,94 @@ export function NotificationBell() {
.catch(() => {})
}
const shown = tab === 'unread' ? notifications.filter(n => !n.read_at) : notifications
const groups: Array<{ label: string; items: Notification[] }> = [
{ label: 'Today', items: shown.filter(n => isToday(n.sent_at)) },
{ label: 'Earlier', items: shown.filter(n => !isToday(n.sent_at)) },
].filter(g => g.items.length > 0)
return (
<div ref={panelRef} className="fixed top-3 right-3 z-50">
<>
<button
onClick={() => setOpen(o => !o)}
type="button"
onClick={() => setOpen(true)}
aria-label={`Notifications${unread > 0 ? ` (${unread} unread)` : ''}`}
className="relative bg-surface border border-divider w-10 h-10 flex items-center justify-center text-ink cursor-pointer transition-colors hover:bg-ink/7 active:bg-ink/15"
className="relative inline-grid place-items-center w-8 h-8 rounded-md text-neutral-300 hover:bg-ink-2 cursor-pointer"
>
<Bell size={18} strokeWidth={2} aria-hidden />
<Bell size={16} strokeWidth={2} aria-hidden />
{unread > 0 && (
<span className="absolute -top-1 -right-1 bg-accent text-ground text-[10px] font-extrabold min-w-[18px] h-[18px] px-1 flex items-center justify-center">
<span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-accent text-white text-[10px] font-semibold grid place-items-center">
{unread > 99 ? '99+' : unread}
</span>
)}
</button>
{open && (
<div className="absolute right-0 mt-2 w-80 max-h-96 overflow-y-auto bg-surface shadow-lg border border-divider">
<div className="flex items-center justify-between px-4 py-2 border-b border-divider">
<span className="text-sm font-extrabold text-ink">Notifications</span>
{unread > 0 && (
<button onClick={markAllRead} className="text-xs text-accent-700 hover:underline">
<Drawer
open={open}
onClose={() => setOpen(false)}
title="Notifications"
actions={
unread > 0 ? (
<button
type="button"
onClick={markAllRead}
className="px-2 text-[12.5px] font-[550] text-accent hover:underline cursor-pointer"
>
Mark all read
</button>
) : undefined
}
>
<div className="flex gap-0.5 px-3 pb-2 border-b border-rule">
{(['all', 'unread'] as const).map(t => (
<button
key={t}
type="button"
onClick={() => setTab(t)}
className={cx(
'inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md text-[13px] cursor-pointer',
tab === t ? 'bg-rule-2 font-semibold' : 'font-medium text-ink-3 hover:bg-surface-2',
)}
>
{t === 'all' ? 'All' : 'Unread'}
<span className="text-xs font-medium text-faint">{t === 'all' ? notifications.length : unread}</span>
</button>
))}
</div>
{notifications.length === 0 ? (
<p className="px-4 py-6 text-sm text-gray-400 text-center">No notifications</p>
{groups.length === 0 ? (
<p className="px-4 py-10 text-sm text-faint text-center">No notifications</p>
) : (
groups.map(g => (
<section key={g.label}>
<h3 className="px-4 pt-3 pb-1 text-[11.5px] font-semibold tracking-wide uppercase text-faint">{g.label}</h3>
<ul>
{notifications.map(n => {
const inner = (
{g.items.map(n => {
const body = (
<>
<p className={`text-sm ${n.read_at ? 'text-gray-500' : 'text-gray-900 font-medium'}`}>
<p className={cx('text-[13px]', n.read_at ? 'text-muted' : 'text-ink font-medium')}>
{n.title ?? 'Notification'}
</p>
<p className="text-xs text-gray-400 mt-0.5">
{new Date(n.sent_at).toLocaleString()}
</p>
<p className="text-xs text-faint mt-0.5">{new Date(n.sent_at).toLocaleString()}</p>
</>
)
return (
<li key={n.id} className="border-b border-gray-50 last:border-0">
<li key={n.id} className={cx('border-b border-rule', !n.read_at && 'bg-accent-tint')}>
{n.link ? (
<Link href={n.link} className="block px-4 py-3 hover:bg-gray-50" onClick={() => setOpen(false)}>
{inner}
<Link href={n.link} className="block px-4 py-3" onClick={() => setOpen(false)}>
{body}
</Link>
) : (
<div className="px-4 py-3">{inner}</div>
<div className="px-4 py-3">{body}</div>
)}
</li>
)
})}
</ul>
</section>
))
)}
</div>
)}
</div>
</Drawer>
</>
)
}
@@ -0,0 +1,77 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
const push = vi.fn()
const refresh = vi.fn()
vi.mock('next/navigation', () => ({
usePathname: () => '/hse/capa',
useRouter: () => ({ push, refresh }),
}))
vi.mock('@/components/notifications/bell', () => ({ NotificationBell: () => <button aria-label="Notifications" /> }))
import { AppShell } from '@/components/layout/app-shell'
beforeEach(() => {
push.mockClear()
refresh.mockClear()
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }))
})
describe('AppShell', () => {
it('has a 56px dark top bar, a grey sidebar and the page content', () => {
const { container } = render(<AppShell role="hse" userName="Ada Lovelace"><p>page body</p></AppShell>)
expect(container.querySelector('header')?.className).toContain('h-14')
expect(container.querySelector('header')?.className).toContain('bg-topbar')
expect(container.querySelector('aside')?.className).toContain('bg-rule')
expect(container.querySelector('aside')?.className).toContain('w-60')
expect(screen.getByText('page body')).toBeTruthy()
expect(screen.getByText('Setia HSE')).toBeTruthy()
})
it('marks the active sidebar item with aria-current on a white ringed item', () => {
render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const active = screen.getAllByRole('link', { name: /CAPA/ }).find(a => a.getAttribute('aria-current') === 'page')!
expect(active.className).toContain('bg-surface')
expect(active.className).toContain('shadow-chip')
})
it('shows a GET search form that targets the incident list for HSE roles', () => {
const { container } = render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const form = container.querySelector('header form')!
expect(form.getAttribute('action')).toBe('/hse/incidents')
expect(form.getAttribute('method')).toBe('get')
expect((form.querySelector('input') as HTMLInputElement).name).toBe('q')
})
it('focuses the search box on Cmd-K', () => {
render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
fireEvent.keyDown(document, { key: 'k', metaKey: true })
expect(document.activeElement?.getAttribute('name')).toBe('q')
})
it('hides the search box for roles without an incident list', () => {
const { container } = render(<AppShell role="reporter" userName="Ada"><span /></AppShell>)
expect(container.querySelector('header form')).toBeNull()
})
it('shows the user chip, version label, and logs out', async () => {
render(<AppShell role="hse" userName="Ada Lovelace"><span /></AppShell>)
expect(screen.getAllByText('AL').length).toBeGreaterThan(0)
expect(screen.getByText('v1.2.2')).toBeTruthy()
fireEvent.click(screen.getAllByRole('button', { name: /Log ?out/i })[0])
await Promise.resolve()
expect(fetch).toHaveBeenCalledWith('/api/auth/logout', { method: 'POST' })
})
it('renders a mobile tab bar that is hidden from md up', () => {
const { container } = render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const nav = container.querySelector('nav[aria-label="Mobile"]')!
expect(nav.className).toContain('md:hidden')
expect(nav.className).toContain('border-t')
})
it('has no 2px rules', () => {
const { container } = render(<AppShell role="admin" userName="Ada"><span /></AppShell>)
expect(container.innerHTML).not.toMatch(/border-[a-z]?-?2\b/)
})
})
+24
View File
@@ -0,0 +1,24 @@
import { describe, it, expect } from 'vitest'
import { navItemsFor, isActivePath, searchHrefFor } from '@/components/layout/nav-items'
describe('nav items', () => {
it('returns the role menu and falls back to reporter', () => {
expect(navItemsFor('hse').map(i => i.label)).toEqual(['Dashboard', 'Incidents', 'CAPA', 'Settings'])
expect(navItemsFor('admin')[0].label).toBe('Admin')
expect(navItemsFor('nobody')).toEqual(navItemsFor('reporter'))
})
it('matches root pages exactly and nested pages by prefix', () => {
expect(isActivePath('/reporter', '/reporter')).toBe(true)
expect(isActivePath('/reporter', '/reporter/incidents/1')).toBe(false)
expect(isActivePath('/hse/incidents', '/hse/incidents/abc')).toBe(true)
})
it('offers the search box only to roles that have an incident list', () => {
expect(searchHrefFor('hse')).toBe('/hse/incidents')
expect(searchHrefFor('admin')).toBe('/hse/incidents')
expect(searchHrefFor('supervisor')).toBe('/supervisor/incidents')
expect(searchHrefFor('reporter')).toBeNull()
expect(searchHrefFor('capa_owner')).toBeNull()
})
})
-41
View File
@@ -1,41 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
vi.mock('next/navigation', () => ({
usePathname: () => '/hse/capa',
useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }),
}))
vi.mock('@/components/notifications/bell', () => ({ NotificationBell: () => null }))
import { Sidebar } from '@/components/layout/sidebar'
describe('Sidebar (Modernist shell)', () => {
it('renders the role nav with Lucide icons instead of inline paths', () => {
const { container } = render(<Sidebar role="hse" userName="Ada Lovelace" userEmail="" />)
expect(screen.getAllByText('Dashboard').length).toBeGreaterThan(0)
expect(screen.getAllByText('CAPA').length).toBeGreaterThan(0)
expect(container.querySelectorAll('svg.lucide').length).toBeGreaterThan(4)
})
it('marks the active link in the accent with an aria-current', () => {
render(<Sidebar role="hse" userName="Ada" userEmail="" />)
const active = screen.getAllByRole('link', { name: /CAPA/ }).find(a => a.getAttribute('aria-current') === 'page')
expect(active).toBeTruthy()
expect(active?.className).toContain('text-accent-700')
expect(active?.className).toContain('border-accent')
})
it('is flat: a 2px divider rule, ground fill and no rounded corners except the avatar', () => {
const { container } = render(<Sidebar role="hse" userName="Ada" userEmail="" />)
const aside = container.querySelector('aside')
expect(aside?.className).toContain('border-r')
expect(aside?.className).toContain('bg-ground')
const rounded = container.innerHTML.match(/rounded[\w-]*/g) ?? []
expect(rounded.every(r => r === 'rounded-full')).toBe(true)
})
it('keeps the version label', () => {
render(<Sidebar role="hse" userName="Ada" userEmail="" />)
expect(screen.getByText('v1.2.2')).toBeTruthy()
})
})
@@ -0,0 +1,44 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { NotificationBell } from '@/components/notifications/bell'
const payload = {
unread: 2,
notifications: [
{ id: 'n1', title: 'CAPA overdue', link: '/hse/capa/1', sent_at: new Date().toISOString(), read_at: null },
{ id: 'n2', title: 'New incident', link: null, sent_at: '2020-01-01T08:00:00Z', read_at: '2020-01-01T09:00:00Z' },
],
}
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => payload }))
})
describe('NotificationBell', () => {
it('shows the unread count on the bell', async () => {
render(<NotificationBell />)
await waitFor(() => expect(screen.getByRole('button', { name: 'Notifications (2 unread)' })).toBeTruthy())
expect(screen.getByText('2')).toBeTruthy()
})
it('opens a drawer with grouped notifications and an Unread tab', async () => {
render(<NotificationBell />)
fireEvent.click(await screen.findByRole('button', { name: /Notifications/ }))
expect(screen.getByRole('dialog', { name: 'Notifications' })).toBeTruthy()
expect(screen.getByText('CAPA overdue')).toBeTruthy()
expect(screen.getByText('Today')).toBeTruthy()
expect(screen.getByText('Earlier')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /Unread/ }))
expect(screen.queryByText('New incident')).toBeNull()
expect(screen.getByText('CAPA overdue')).toBeTruthy()
})
it('marks everything read', async () => {
render(<NotificationBell />)
fireEvent.click(await screen.findByRole('button', { name: /Notifications/ }))
fireEvent.click(screen.getByRole('button', { name: 'Mark all read' }))
await waitFor(() =>
expect(fetch).toHaveBeenCalledWith('/api/notifications', expect.objectContaining({ method: 'POST', body: JSON.stringify({ all: true }) })),
)
})
})