import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import test from 'node:test'; import { pathToFileURL } from 'node:url'; const navScriptUrl = pathToFileURL(path.resolve('src/scripts/nav-menu.js')).href; const sourceIndexPath = path.resolve('index.html'); const distIndexPath = path.resolve('dist/index.html'); const distAssetsDir = path.resolve('dist/assets'); function readRequired(filePath) { assert.ok(fs.existsSync(filePath), `Expected ${path.relative(process.cwd(), filePath)} to exist`); return fs.readFileSync(filePath, 'utf8'); } function readBuiltCss() { assert.ok(fs.existsSync(distAssetsDir), 'Expected dist/assets directory to exist'); const cssFiles = fs.readdirSync(distAssetsDir).filter((file) => file.endsWith('.css')); assert.ok(cssFiles.length > 0, 'Expected at least one built CSS asset in dist/assets/'); return cssFiles.map((file) => fs.readFileSync(path.join(distAssetsDir, file), 'utf8')).join('\n'); } function openingTagById(html, id) { return html.match(new RegExp(`<([a-z][^>]*)\\bid="${id}"[^>]*>`, 'i'))?.[0]; } function classTokens(openingTag) { const classAttribute = openingTag.match(/\bclass=(["'])(.*?)\1/i)?.[2] ?? ''; return new Set(classAttribute.split(/\s+/).filter(Boolean)); } function cssRuleBody(css, selectorPattern) { const match = css.match(selectorPattern); if (!match || match.index === undefined) { return ''; } const open = css.indexOf('{', match.index); const close = css.indexOf('}', open); if (open === -1 || close === -1) { return ''; } return css.slice(open + 1, close); } function cssBlock(css, start) { const open = css.indexOf('{', start); if (open === -1) { return ''; } let depth = 0; for (let index = open; index < css.length; index += 1) { if (css[index] === '{') { depth += 1; } else if (css[index] === '}') { depth -= 1; if (depth === 0) { return css.slice(open + 1, index); } } } return ''; } function bundledModuleSources(html) { return [...html.matchAll(/]*>/gi)] .map((match) => match[0]) .filter((tag) => /\btype="module"/i.test(tag)) .map((tag) => tag.match(/\bsrc="([^"]+)"/i)?.[1] ?? '') .filter((src) => /(?:^|\/)assets\/[^"']+\.js(?:[?#].*)?$/i.test(src)); } function createDomDouble({ includeToggle = true, includeMenu = true, pathname = '/' } = {}) { class FakeElement { constructor(closestLink = null) { this._closestLink = closestLink; } closest(selector) { return selector === 'a' ? this._closestLink : null; } } function createEmitter() { const listeners = new Map(); return { addEventListener(type, listener) { if (!listeners.has(type)) { listeners.set(type, []); } listeners.get(type).push(listener); }, dispatch(type, event = {}) { for (const listener of listeners.get(type) ?? []) { listener(event); } }, }; } const toggleEmitter = createEmitter(); const toggleAttributes = new Map([['aria-expanded', 'false']]); let focusCalls = 0; const toggle = includeToggle ? { addEventListener: toggleEmitter.addEventListener, dispatch: toggleEmitter.dispatch, getAttribute(name) { return toggleAttributes.get(name) ?? null; }, setAttribute(name, value) { toggleAttributes.set(name, String(value)); }, focus() { focusCalls += 1; }, get focusCalls() { return focusCalls; }, } : null; const menuEmitter = createEmitter(); const classes = new Set(['hidden']); const menu = includeMenu ? { addEventListener: menuEmitter.addEventListener, dispatch: menuEmitter.dispatch, classList: { contains(token) { return classes.has(token); }, toggle(token, force) { if (force === undefined) { if (classes.has(token)) { classes.delete(token); return false; } classes.add(token); return true; } if (force) { classes.add(token); return true; } classes.delete(token); return false; }, }, setAttribute(name) { if (name === 'hidden') { throw new Error('Must not call setAttribute("hidden", ...) on #site-menu'); } }, set hidden(_value) { throw new Error('Must not set .hidden property on #site-menu'); }, } : null; const documentEmitter = createEmitter(); const documentDouble = { // Why: Vite's modulepreload polyfill checks link.relList.supports('modulepreload') // at top level; returning true short-circuits it without needing MutationObserver. createElement() { return { relList: { supports: () => true } }; }, querySelector(selector) { return selector === '[aria-controls="site-menu"]' ? toggle : null; }, getElementById(id) { return id === 'site-menu' ? menu : null; }, addEventListener: documentEmitter.addEventListener, dispatch: documentEmitter.dispatch, }; const windowDouble = { location: { pathname }, }; return { FakeElement, documentDouble, windowDouble, toggle, menu, }; } async function withDomDouble(options, callback) { const prevDocument = Object.getOwnPropertyDescriptor(globalThis, 'document'); const prevWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'); const prevElement = Object.getOwnPropertyDescriptor(globalThis, 'Element'); const env = createDomDouble(options); globalThis.document = env.documentDouble; globalThis.window = env.windowDouble; globalThis.Element = env.FakeElement; try { await callback(env); } finally { for (const [key, descriptor] of [ ['document', prevDocument], ['window', prevWindow], ['Element', prevElement], ]) { if (descriptor) { Object.defineProperty(globalThis, key, descriptor); } else { delete globalThis[key]; } } } } test('Issue #5 AC #2 & #3: disclosure menu behavior and accessibility style contract', async (t) => { await t.test( 'toggle click opens and closes #site-menu via .hidden class and aria-expanded without touching hidden attribute', async () => { await withDomDouble({}, async ({ toggle, menu }) => { await import(`${navScriptUrl}?case=toggle-click`); assert.equal(menu.classList.contains('hidden'), true); assert.equal(toggle.getAttribute('aria-expanded'), 'false'); toggle.dispatch('click'); assert.equal(menu.classList.contains('hidden'), false); assert.equal(toggle.getAttribute('aria-expanded'), 'true'); toggle.dispatch('click'); assert.equal(menu.classList.contains('hidden'), true); assert.equal(toggle.getAttribute('aria-expanded'), 'false'); }); }, ); await t.test( 'Escape keydown closes an open #site-menu and returns focus via toggle.focus()', async () => { await withDomDouble({}, async ({ documentDouble, toggle, menu }) => { await import(`${navScriptUrl}?case=escape-open`); toggle.dispatch('click'); assert.equal(menu.classList.contains('hidden'), false); assert.equal(toggle.getAttribute('aria-expanded'), 'true'); documentDouble.dispatch('keydown', { key: 'Escape' }); assert.equal(menu.classList.contains('hidden'), true); assert.equal(toggle.getAttribute('aria-expanded'), 'false'); assert.equal(toggle.focusCalls, 1); }); }, ); await t.test('Escape keydown when #site-menu is closed is a no-op', async () => { await withDomDouble({}, async ({ documentDouble, toggle, menu }) => { await import(`${navScriptUrl}?case=escape-closed`); documentDouble.dispatch('keydown', { key: 'Escape' }); assert.equal(menu.classList.contains('hidden'), true); assert.equal(toggle.getAttribute('aria-expanded'), 'false'); assert.equal(toggle.focusCalls, 0); }); }); await t.test('clicking a same-page hash link inside #site-menu closes the menu', async () => { await withDomDouble({ pathname: '/' }, async ({ FakeElement, toggle, menu }) => { await import(`${navScriptUrl}?case=same-page-hash`); toggle.dispatch('click'); assert.equal(menu.classList.contains('hidden'), false); const target = new FakeElement({ hash: '#servicios', pathname: '/' }); menu.dispatch('click', { target }); assert.equal(menu.classList.contains('hidden'), true); assert.equal(toggle.getAttribute('aria-expanded'), 'false'); }); }); await t.test('clicking a cross-page link inside #site-menu does not close the menu', async () => { await withDomDouble({ pathname: '/' }, async ({ FakeElement, toggle, menu }) => { await import(`${navScriptUrl}?case=cross-page-link`); toggle.dispatch('click'); assert.equal(menu.classList.contains('hidden'), false); const target = new FakeElement({ hash: '#intro', pathname: '/acerca' }); menu.dispatch('click', { target }); assert.equal(menu.classList.contains('hidden'), false); assert.equal(toggle.getAttribute('aria-expanded'), 'true'); }); }); await t.test( 'clicking a non-link element inside #site-menu does not close the menu', async () => { await withDomDouble({ pathname: '/' }, async ({ FakeElement, toggle, menu }) => { await import(`${navScriptUrl}?case=non-link`); toggle.dispatch('click'); assert.equal(menu.classList.contains('hidden'), false); const target = new FakeElement(null); menu.dispatch('click', { target }); assert.equal(menu.classList.contains('hidden'), false); assert.equal(toggle.getAttribute('aria-expanded'), 'true'); }); }, ); await t.test( 'missing toggle or #site-menu DOM elements is a safe no-op without throwing', async () => { await withDomDouble({ includeToggle: false, includeMenu: true }, async () => { await assert.doesNotReject(() => import(`${navScriptUrl}?case=missing-toggle`)); }); await withDomDouble({ includeToggle: true, includeMenu: false }, async () => { await assert.doesNotReject(() => import(`${navScriptUrl}?case=missing-menu`)); }); }, ); await t.test('source index.html loads /src/scripts/nav-menu.js as an ES module', () => { const sourceHtml = readRequired(sourceIndexPath); const moduleScripts = [...sourceHtml.matchAll(/]*>/gi)].map((match) => match[0]); assert.ok( moduleScripts.some( (tag) => /\btype="module"/i.test(tag) && /\bsrc="\/src\/scripts\/nav-menu\.js"/i.test(tag), ), 'Source index.html must load /src/scripts/nav-menu.js as an ES module', ); }); await t.test( 'built index.html references a bundled /assets/*.js module on disk that wires toggle, aria-expanded, and Escape focus return', async () => { const distHtml = readRequired(distIndexPath); const scriptSources = bundledModuleSources(distHtml); assert.ok( scriptSources.length > 0, 'Built index.html must reference at least one bundled ES module under /assets/', ); const bundlePaths = scriptSources.map((src) => { const bundlePath = path.resolve('dist', src.replace(/^\.?\//, '')); assert.ok(fs.existsSync(bundlePath), `Bundled module ${src} must exist on disk`); return bundlePath; }); await withDomDouble({}, async ({ documentDouble, toggle, menu }) => { for (const [index, bundlePath] of bundlePaths.entries()) { await import(`${pathToFileURL(bundlePath).href}?case=dist-bundle-${index}`); } toggle.dispatch('click'); assert.equal(menu.classList.contains('hidden'), false); assert.equal(toggle.getAttribute('aria-expanded'), 'true'); documentDouble.dispatch('keydown', { key: 'Escape' }); assert.equal(menu.classList.contains('hidden'), true); assert.equal(toggle.getAttribute('aria-expanded'), 'false'); assert.equal(toggle.focusCalls, 1); }); }, ); await t.test( 'built header defines #site-menu with collapsed mobile panel and desktop lg:flex override', () => { const distHtml = readRequired(distIndexPath); const menuTag = openingTagById(distHtml, 'site-menu'); assert.ok(menuTag, 'Built index.html must define the #site-menu panel'); const menuClasses = classTokens(menuTag); assert.ok( menuClasses.has('hidden'), '#site-menu must start collapsed with the .hidden class', ); assert.ok( menuClasses.has('lg:flex') && menuClasses.has('lg:static'), '#site-menu must restore static flex navigation at lg and above', ); assert.ok( menuClasses.has('absolute') && menuClasses.has('top-full'), '#site-menu must open as an absolute panel below the header row', ); assert.ok( menuClasses.has('inset-x-0') || (menuClasses.has('left-0') && menuClasses.has('right-0')), '#site-menu must span the full width of the header row', ); }, ); await t.test( 'built header exposes disclosure button for #site-menu with required ARIA attributes and lg:hidden', () => { const distHtml = readRequired(distIndexPath); const toggleTag = [...distHtml.matchAll(/]*>/gi)] .map((match) => match[0]) .find((tag) => /\baria-controls="site-menu"/i.test(tag)); assert.ok(toggleTag, 'Built index.html must expose a disclosure button for #site-menu'); assert.match(toggleTag, /\btype="button"/i, 'Disclosure button must be type="button"'); assert.match( toggleTag, /\baria-expanded="false"/i, 'Disclosure button must start with aria-expanded="false"', ); assert.match( toggleTag, /\baria-label="Abrir menú de navegación"/i, 'Disclosure button must expose the approved Spanish accessible name', ); assert.ok( classTokens(toggleTag).has('lg:hidden'), 'Disclosure button must be hidden from lg and above, where the nav is always visible', ); }, ); await t.test( 'built header places disclosure button inside