import { uid } from '../shared/dom'; import { NAV_COLLAPSE_EVENT, NAV_SELECT_EVENT, NAV_TOGGLE_EVENT, type NavCollapseDetail, type NavOptions, type NavSelectDetail, type NavToggleDetail, } from './nav.types'; const SELECTORS = { group: '[data-c42-nav-group]', trigger: ':scope > [data-c42-nav-trigger]', submenu: ':scope > [data-c42-nav-submenu]', item: '[data-c42-nav-item]', collapse: '[data-c42-nav-collapse]', } as const; interface NavGroup { el: HTMLElement; trigger: HTMLElement; submenu: HTMLElement; value: string; } /** * Headless sidebar/nav controller implementing the WAI-ARIA disclosure * navigation pattern: collapsible groups (`aria-expanded` + hidden submenu), * an active item (`aria-current="page"`), and an optional collapsed/mini mode. * It reflects state on `data-state` / `data-active` / `data-collapsed` and * applies no visual styles. * * Markup: * ```html * * ``` */ export class Nav { private readonly root: HTMLElement; private readonly accordion: boolean; private readonly collapseBtn: HTMLElement | null; private readonly groups: NavGroup[]; private collapsed = false; private activeValue: string | null = null; private cleanups: Array<() => void> = []; constructor(root: HTMLElement, options: NavOptions = {}) { this.root = root; this.accordion = options.accordion ?? false; this.collapseBtn = root.querySelector(SELECTORS.collapse); this.groups = this.collectGroups(); this.init(); this.collapsed = options.collapsed ?? false; this.applyCollapsed(); if (options.defaultActive) { this.setActive(options.defaultActive); } } private collectGroups(): NavGroup[] { const groupEls = Array.from(this.root.querySelectorAll(SELECTORS.group)); const groups: NavGroup[] = []; for (const el of groupEls) { const trigger = el.querySelector(SELECTORS.trigger); const submenu = el.querySelector(SELECTORS.submenu); if (!trigger || !submenu) { continue; } groups.push({ el, trigger, submenu, value: trigger.dataset.value || el.dataset.value || uid('nav-group') }); } return groups; } private init(): void { for (const group of this.groups) { const submenuId = group.submenu.id || uid('nav-submenu'); group.submenu.id = submenuId; group.trigger.setAttribute('aria-controls', submenuId); if (group.trigger instanceof HTMLButtonElement && !group.trigger.hasAttribute('type')) { group.trigger.type = 'button'; } const open = group.el.dataset.state === 'open'; this.reflectGroup(group, open); const onTriggerClick = (): void => this.toggleGroup(group.value); const onSubmenuKeydown = (event: Event): void => { if ((event as KeyboardEvent).key === 'Escape') { this.setGroupOpen(group, false); group.trigger.focus(); } }; group.trigger.addEventListener('click', onTriggerClick); group.submenu.addEventListener('keydown', onSubmenuKeydown); this.cleanups.push( () => group.trigger.removeEventListener('click', onTriggerClick), () => group.submenu.removeEventListener('keydown', onSubmenuKeydown), ); } const onItemClick = (event: Event): void => { const item = (event.target as HTMLElement).closest(SELECTORS.item); if (item && this.root.contains(item)) { const value = item.dataset.value; if (value) { this.setActive(value); const detail: NavSelectDetail = { value }; this.root.dispatchEvent(new CustomEvent(NAV_SELECT_EVENT, { detail, bubbles: true })); } } }; this.root.addEventListener('click', onItemClick); this.cleanups.push(() => this.root.removeEventListener('click', onItemClick)); if (this.collapseBtn) { if (this.collapseBtn instanceof HTMLButtonElement && !this.collapseBtn.hasAttribute('type')) { this.collapseBtn.type = 'button'; } const onCollapseClick = (): void => this.toggleCollapsed(); this.collapseBtn.addEventListener('click', onCollapseClick); this.cleanups.push(() => this.collapseBtn?.removeEventListener('click', onCollapseClick)); } } private reflectGroup(group: NavGroup, open: boolean): void { group.el.dataset.state = open ? 'open' : 'closed'; group.trigger.setAttribute('aria-expanded', String(open)); group.submenu.toggleAttribute('hidden', !open); } private setGroupOpen(group: NavGroup, open: boolean, silent = false): void { const isOpen = group.el.dataset.state === 'open'; if (isOpen === open) { return; } if (open && this.accordion) { for (const other of this.groups) { if (other !== group && other.el.dataset.state === 'open') { this.reflectGroup(other, false); this.emitToggle(other.value, false); } } } this.reflectGroup(group, open); if (!silent) { this.emitToggle(group.value, open); } } private emitToggle(value: string, open: boolean): void { const detail: NavToggleDetail = { value, open }; this.root.dispatchEvent(new CustomEvent(NAV_TOGGLE_EVENT, { detail, bubbles: true })); } private applyCollapsed(): void { this.root.dataset.collapsed = String(this.collapsed); if (this.collapseBtn) { this.collapseBtn.setAttribute('aria-expanded', String(!this.collapsed)); } } /** Toggle a group by its value. */ toggleGroup(value: string): void { const group = this.groups.find((g) => g.value === value); if (group) { this.setGroupOpen(group, group.el.dataset.state !== 'open'); } } /** Open a group by its value. */ openGroup(value: string): void { const group = this.groups.find((g) => g.value === value); if (group) { this.setGroupOpen(group, true); } } /** Close a group by its value. */ closeGroup(value: string): void { const group = this.groups.find((g) => g.value === value); if (group) { this.setGroupOpen(group, false); } } /** Mark an item active (by `data-value`) and expand its ancestor groups. */ setActive(value: string): void { const items = Array.from(this.root.querySelectorAll(SELECTORS.item)); const target = items.find((item) => item.dataset.value === value) ?? null; for (const item of items) { const isActive = item === target; item.toggleAttribute('data-active', isActive); if (isActive) { item.setAttribute('aria-current', 'page'); } else { item.removeAttribute('aria-current'); } } this.activeValue = target ? value : null; if (target) { let ancestor = target.parentElement?.closest(SELECTORS.group) ?? null; while (ancestor) { const group = this.groups.find((g) => g.el === ancestor); if (group) { this.setGroupOpen(group, true, true); } ancestor = ancestor.parentElement?.closest(SELECTORS.group) ?? null; } } } get active(): string | null { return this.activeValue; } /** Toggle the collapsed (mini) state. */ toggleCollapsed(): void { this.setCollapsed(!this.collapsed); } /** Set the collapsed (mini) state. */ setCollapsed(collapsed: boolean): void { if (collapsed === this.collapsed) { return; } this.collapsed = collapsed; this.applyCollapsed(); const detail: NavCollapseDetail = { collapsed }; this.root.dispatchEvent(new CustomEvent(NAV_COLLAPSE_EVENT, { detail, bubbles: true })); } get isCollapsed(): boolean { return this.collapsed; } /** Subscribe to a DOM event on the root element. Returns an unsubscribe fn. */ on(event: string, handler: (event: E) => void): () => void { const listener = handler as EventListener; this.root.addEventListener(event, listener); const off = (): void => this.root.removeEventListener(event, listener); this.cleanups.push(off); return off; } destroy(): void { this.cleanups.forEach((fn) => fn()); this.cleanups = []; } }