From a340121accd37a10b2b9883faa03dfedf4664433 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Tr=C3=B3chez?= <66706019+kiskaadee@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:56:48 -0500 Subject: [PATCH] feat(nav): add build-time partials, mobile disclosure menu, and dist tests (#9) * test(nav): add Red build-partial contract tests and migrate suites to dist - Point hero-whatsapp and services-catalog HTML assertions at dist/index.html so the deployable artifact is the tested seam; keep stylesheet token assertions on source - Add tests/html-partials.test.js covering partial includes, stripped build hints, root-relative nav, canonical/OG metadata, preserved Kundalini wa.me CTA, and missing-partial error behavior - Rationale: TDD Red checkpoint for issue #5; new assertions fail against the pre-plugin build for the expected reasons while migrated suites remain green * feat(build): add HTML partials plugin and single-entry Vite build - Add scripts/html-partials-plugin.ts to expand src/partials includes, fail loudly on unresolved paths, normalize dev/build route keys, apply/strip data-nav-current markers, and full-reload on partial edits - Register the plugin before Vite transforms and pin rollup input to the root index.html for Phase 1 - Rationale: build-time injection keeps shared markup dependency-free and preserves identical dev/build route keys ahead of the new pages * test(nav): add Red disclosure menu and a11y style contract tests - Assert nav-menu.js class-based toggle, aria-expanded sync, Escape focus return, and same-page hash close without DOM dependencies - Assert source/built module wiring and the header partial's collapsed mobile panel with the brand title preserved - Assert style.css scroll padding, active underline, focus ring, reduced motion, and gated-link/disclaimer touch-target rules - Rationale: Red checkpoint for issue #5 AC #2/#3; all failures are missing files or missing rules * feat(nav): add shared partials, mobile disclosure menu, and home metadata - Extract header, footer and floating WhatsApp button into src/partials and replace inline markup in index.html with build-time @include markers - Add dependency-free src/scripts/nav-menu.js with class-based toggle, aria-expanded sync, Escape focus return and same-page hash close; load it as an ES module - Add root-relative nav, 44px disclosure target and single-tree mobile panel; add sticky-header scroll padding, focus ring, active underline, reduced-motion and gated-link/disclaimer styles - Add canonical and Open Graph tags for / while preserving every section's copy and Service Card 2's live wa.me CTA (route change deferred to a later issue) - Rationale: shared markup stays build-time only, keeping main deployable with zero new runtime dependencies and no broken links * fix(nav): place mobile disclosure toggle inside nav landmark - Move the mobile disclosure button inside the primary nav landmark in src/partials/header.html - Keep the header flex container at two children so the toggle stays flush right at 430px-767px instead of floating beside a 0px nav (CR-04) * test(nav): execute nav-menu and built bundle against DOM double - Execute src/scripts/nav-menu.js and the built bundle against a DOM double for toggle, Escape, and same-page vs cross-page link behavior - Verify built CSS rules and header disclosure structure inside the nav landmark (CR-01, CR-03, CR-04, CR-05, CR-07) * test(partials): add path-guard and route-key boundary tests - Add unit tests for expandHtmlPartials path-guard rejection of disallowed @include specifiers and transformIndexHtml route-key marking - Verify built HTML strips build markers/hints, preserves Open Graph/canonical metadata, and keeps header navigation invariants (CR-02, CR-06, CR-07) * fix(nav): keep mobile brand title on a single line at 375px - Use text-sm tracking-wide whitespace-nowrap on mobile and restore sm:text-xl sm:tracking-wider at >= 640px - Resolves RV-02 375px brand-title wrapping failure while keeping desktop header styling unchanged * fix(nav): switch desktop nav breakpoint to lg and prevent brand overlap - Header layout (src/partials/header.html): move desktop nav expansion from md: to lg: (1024px), add shrink-0 on the brand link, and add gap-4 on the header flex row to prevent brand/nav overlap at 768px-1018px (PR #9 CR-08) - Nav menu tests (tests/nav-menu.test.js): update built-header assertions to check lg:flex/lg:static/lg:hidden, gap-4 on the header inner flex container, and shrink-0 plus lg:hidden exclusion on the brand link --- index.html | 95 +----- scripts/html-partials-plugin.ts | 161 +++++++++ src/partials/footer.html | 47 +++ src/partials/header.html | 33 ++ src/partials/whatsapp-fab.html | 13 + src/scripts/nav-menu.js | 38 +++ src/style.css | 42 +++ tests/hero-whatsapp.test.js | 4 +- tests/html-partials.test.js | 336 +++++++++++++++++++ tests/nav-menu.test.js | 573 ++++++++++++++++++++++++++++++++ tests/services-catalog.test.js | 4 +- vite.config.ts | 10 +- 12 files changed, 1275 insertions(+), 81 deletions(-) create mode 100644 scripts/html-partials-plugin.ts create mode 100644 src/partials/footer.html create mode 100644 src/partials/header.html create mode 100644 src/partials/whatsapp-fab.html create mode 100644 src/scripts/nav-menu.js create mode 100644 tests/html-partials.test.js create mode 100644 tests/nav-menu.test.js diff --git a/index.html b/index.html index c5a171c..f20713c 100644 --- a/index.html +++ b/index.html @@ -8,6 +8,19 @@ name="description" content="Sal del automático. Abre tu corazón, recupera tu soberanía. Barras de Access®, Procesos de Cuerpo y Mentorías de Consciencia en Valledupar." /> + + + + + + + + + + @@ -18,38 +31,9 @@ - - - - Conversar con Azu - + - -
-
- - Logo El Corazón como Portal - El Corazón como Portal - - -
-
+
@@ -526,52 +510,7 @@
- - + + diff --git a/scripts/html-partials-plugin.ts b/scripts/html-partials-plugin.ts new file mode 100644 index 0000000..7b2cc11 --- /dev/null +++ b/scripts/html-partials-plugin.ts @@ -0,0 +1,161 @@ +/** + * Build-time HTML partial inclusion and route-aware navigation rewriting. + * + * The plugin emits no runtime JS: it expands `` markers + * before Vite processes scripts and assets, then converts build-only nav + * hints into `aria-current` for the canonical route. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import type { IndexHtmlTransformContext, Plugin, ViteDevServer } from 'vite-plus'; + +const PARTIALS_DIRECTORY = path.join('src', 'partials'); +const DEFAULT_ROOT = path.resolve(import.meta.dirname, '..'); +const INCLUDE_MARKER = //gi; +// Matches quoted, unquoted, and bare `data-nav-current` attributes. +const NAV_MARKER = + /\s+data-nav-current\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))|\s+data-nav-current(?=\s|\/|>)/gi; + +/** Resolve an include specifier to an absolute path inside `src/partials`. */ +function resolvePartialPath(specifier: string, rootDirectory: string): string { + const normalized = specifier.replaceAll('\\', '/').replace(/^\.\//, ''); + const match = /^src\/partials\/([^/]+\.html)$/i.exec(normalized); + if (!match) { + throw new Error( + `Unsupported @include "${specifier}"; only src/partials/.html is allowed`, + ); + } + + const partialsDirectory = path.resolve(rootDirectory, PARTIALS_DIRECTORY); + const target = path.resolve(partialsDirectory, match[1]); + const relative = path.relative(partialsDirectory, target); + + // Why: an include marker must never read outside the approved partials directory. + if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) { + throw new Error(`Unsafe @include path "${specifier}"`); + } + return target; +} + +/** + * Expand every `` marker in an HTML string. + * + * @param html Source HTML that may contain include markers. + * @param rootDirectory Project root used to resolve partial files. + * @throws Error naming the unresolved partial when a referenced file is missing. + */ +export function expandHtmlPartials(html: string, rootDirectory: string = DEFAULT_ROOT): string { + return html.replace(INCLUDE_MARKER, (_marker, specifier: string) => { + const target = resolvePartialPath(specifier, rootDirectory); + if (!fs.existsSync(target)) { + throw new Error(`Unable to resolve HTML partial "${specifier}" at ${target}`); + } + return fs.readFileSync(target, 'utf8'); + }); +} + +/** Convert a URL pathname into a canonical route key such as `/kundalini/`. */ +function routeKeyFromPathname(pathname: string): string { + const segments = (pathname.split(/[?#]/, 1)[0] ?? '') + .replaceAll('\\', '/') + .replace(/^\/+|\/+$/g, '') + .split('/') + .filter(Boolean); + if (segments.at(-1) === 'index.html') { + segments.pop(); + } + return segments.length === 0 ? '/' : `/${segments.join('/')}/`; +} + +/** Convert an absolute build filename into the same canonical route key. */ +function routeKeyFromFilename(filename: string, rootDirectory: string): string { + const relative = path.relative(rootDirectory, filename).replaceAll('\\', '/'); + return routeKeyFromPathname(`/${relative}`); +} + +/** Pick the reliable route source for a Vite HTML transform context. */ +function resolveRouteKey(ctx: IndexHtmlTransformContext, rootDirectory: string): string { + // Why: dev ctx.filename can point to index.html for every URL, while build + // has no route path; ctx.path wins in dev and the filename wins in build. + if (ctx.server && ctx.path) { + return routeKeyFromPathname(ctx.path); + } + if (ctx.filename) { + return routeKeyFromFilename(ctx.filename, rootDirectory); + } + return routeKeyFromPathname(ctx.path || '/'); +} + +/** Activate the matching nav marker and remove every remaining build hint. */ +function applyNavigationMarkers(html: string, routeKey: string): string { + let activeMarker = ''; + if (routeKey === '/') { + activeMarker = 'home'; + } else if (routeKey === '/kundalini/') { + activeMarker = 'kundalini'; + } + + return html.replace(NAV_MARKER, (_match, quoted, singleQuoted, unquoted) => { + const value = (quoted ?? singleQuoted ?? unquoted ?? '').toLowerCase(); + if (activeMarker && value === activeMarker) { + return ' aria-current="page"'; + } + // Why: build-time hints must never reach clients; only the exact active + // route gets aria-current, so other routes have no current nav item. + return ''; + }); +} + +/** Return true when a changed file is an HTML fragment in `src/partials`. */ +function isPartialFile(file: string, rootDirectory: string): boolean { + const relative = path + .relative(path.resolve(rootDirectory, PARTIALS_DIRECTORY), path.resolve(file)) + .replaceAll('\\', '/'); + return ( + relative !== '' && + !relative.startsWith('..') && + !path.isAbsolute(relative) && + relative.toLowerCase().endsWith('.html') + ); +} + +/** + * Create the Vite plugin that injects partials and marks the active nav item. + * + * Partials are watched for `vp dev`, where a change triggers a full page + * reload because plain HTML fragments are not module-graph entries. + */ +export function htmlPartialsPlugin(): Plugin { + let rootDirectory = DEFAULT_ROOT; + let devServer: ViteDevServer | undefined; + + return { + name: 'corazoncp-html-partials', + configResolved(config) { + rootDirectory = config.root || DEFAULT_ROOT; + }, + configureServer(server) { + devServer = server; + server.watcher.add(path.resolve(rootDirectory, PARTIALS_DIRECTORY)); + }, + handleHotUpdate(ctx) { + if (!isPartialFile(ctx.file, rootDirectory)) { + return undefined; + } + const server = ctx.server ?? devServer; + server?.ws.send({ type: 'full-reload' }); + // Why: each page includes the same fragments, so a partial edit must + // reload the page instead of trying to HMR a non-module file. + return []; + }, + transformIndexHtml: { + order: 'pre', + handler(html, ctx) { + const expanded = expandHtmlPartials(html, rootDirectory); + return applyNavigationMarkers(expanded, resolveRouteKey(ctx, rootDirectory)); + }, + }, + }; +} + +export default htmlPartialsPlugin; diff --git a/src/partials/footer.html b/src/partials/footer.html new file mode 100644 index 0000000..0672fa7 --- /dev/null +++ b/src/partials/footer.html @@ -0,0 +1,47 @@ + + diff --git a/src/partials/header.html b/src/partials/header.html new file mode 100644 index 0000000..1ed3571 --- /dev/null +++ b/src/partials/header.html @@ -0,0 +1,33 @@ + +
+ + +
diff --git a/src/partials/whatsapp-fab.html b/src/partials/whatsapp-fab.html new file mode 100644 index 0000000..de17312 --- /dev/null +++ b/src/partials/whatsapp-fab.html @@ -0,0 +1,13 @@ + + + + Conversar con Azu + diff --git a/src/scripts/nav-menu.js b/src/scripts/nav-menu.js new file mode 100644 index 0000000..c3bee52 --- /dev/null +++ b/src/scripts/nav-menu.js @@ -0,0 +1,38 @@ +// Why: the disclosure toggles Tailwind's .hidden class instead of the HTML +// hidden attribute, so the md:flex desktop override can still show the nav tree. +const toggle = document.querySelector('[aria-controls="site-menu"]'); +const menu = document.getElementById('site-menu'); + +// Why: partials are shared across routes, so pages without the disclosure keep +// their native navigation instead of throwing on module evaluation. +if (toggle && menu) { + function setOpen(open) { + menu.classList.toggle('hidden', !open); + toggle.setAttribute('aria-expanded', String(open)); + } + + function close(returnFocus = false) { + setOpen(false); + if (returnFocus) { + toggle.focus(); + } + } + + toggle.addEventListener('click', () => { + setOpen(toggle.getAttribute('aria-expanded') !== 'true'); + }); + + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && toggle.getAttribute('aria-expanded') === 'true') { + close(true); + } + }); + + menu.addEventListener('click', (event) => { + const link = event.target instanceof Element ? event.target.closest('a') : null; + // Why: only same-page anchors collapse the panel; cross-page links navigate natively. + if (link?.hash && link.pathname === window.location.pathname) { + close(); + } + }); +} diff --git a/src/style.css b/src/style.css index 10abaef..b0194df 100644 --- a/src/style.css +++ b/src/style.css @@ -20,3 +20,45 @@ body { font-family: var(--font-sans); -webkit-font-smoothing: antialiased; } + +html { + /* Why: in-page anchors must land below the sticky header, not underneath it. */ + scroll-padding-top: 5.5rem; +} + +a[aria-current="page"] { + text-decoration: underline; + text-underline-offset: 0.25em; + text-decoration-thickness: 2px; +} + +:focus-visible { + outline: 2px solid var(--color-emerald); + outline-offset: 3px; +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + + *, + *::before, + *::after { + transition-duration: 0.01ms; + animation-duration: 0.01ms; + animation-iteration-count: 1; + } +} + +label[for="accept-disclaimer"] { + display: inline-flex; + align-items: center; + min-height: 44px; + accent-color: var(--color-emerald); +} + +a[aria-disabled="true"] { + opacity: 0.55; + cursor: not-allowed; +} diff --git a/tests/hero-whatsapp.test.js b/tests/hero-whatsapp.test.js index e310fcb..4d60073 100644 --- a/tests/hero-whatsapp.test.js +++ b/tests/hero-whatsapp.test.js @@ -3,7 +3,9 @@ import fs from 'node:fs'; import path from 'node:path'; import test from 'node:test'; -const indexPath = path.resolve('index.html'); +// Why: assertions target the built deployable artifact so partial expansion and +// build-time transformations are covered by the same checks as hero markup. +const indexPath = path.resolve('dist/index.html'); const indexHtml = fs.readFileSync(indexPath, 'utf-8'); test('Slice 2 Acceptance Criteria: Hero and WhatsApp Flow', async (t) => { diff --git a/tests/html-partials.test.js b/tests/html-partials.test.js new file mode 100644 index 0000000..1f50f6b --- /dev/null +++ b/tests/html-partials.test.js @@ -0,0 +1,336 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; +import { expandHtmlPartials, htmlPartialsPlugin } from '../scripts/html-partials-plugin.ts'; + +const distIndexPath = path.resolve('dist/index.html'); + +// Why: the plugin only runs at build time, so these assertions must inspect the +// deployable artifact instead of the source document. +const distHtml = fs.readFileSync(distIndexPath, 'utf-8'); + +function findMetaByProperty(html, property) { + return [...html.matchAll(/]*>/gi)] + .map((match) => match[0]) + .find((tag) => tag.toLowerCase().includes(`property="${property}"`)); +} + +function extractHeaderMarkup(html) { + const headerMarkup = html.match(//i)?.[0]; + assert.ok(headerMarkup, 'Built HTML must contain an expanded header partial'); + return headerMarkup; +} + +function findDisclosureButton(headerMarkup) { + const disclosureButton = [...headerMarkup.matchAll(/]*>/gi)] + .map((match) => match[0]) + .find((tag) => /\baria-controls="site-menu"/i.test(tag)); + assert.ok(disclosureButton, 'Header must have a disclosure button controlling #site-menu'); + return disclosureButton; +} + +/** + * Locate a service card by its

heading and return its enclosing card
. + * Why: avoids coupling tests to HTML comments that minification may strip. + */ +function extractCardByHeading(html, headingText) { + const headingMatch = new RegExp(`]*>[^<]*${headingText}[^<]*

`, 'i').exec(html); + if (!headingMatch) { + return undefined; + } + + const cardOpenPattern = /]*class="[^"]*\brounded-2xl\b[^"]*"[^>]*>/gi; + let cardStart = -1; + for (const match of html.matchAll(cardOpenPattern)) { + if (match.index <= headingMatch.index) { + cardStart = match.index; + } else { + break; + } + } + if (cardStart === -1) { + return undefined; + } + + const divTagPattern = /<\/?div\b[^>]*>/gi; + divTagPattern.lastIndex = cardStart; + let depth = 0; + for (const tagMatch of html.matchAll(divTagPattern)) { + if (tagMatch.index < cardStart) { + continue; + } + depth += tagMatch[0].startsWith(' { + await t.test('Criterion 2: built header uses root-relative navigation links', () => { + const headerMarkup = extractHeaderMarkup(distHtml); + + for (const href of [ + '/', + '/#servicios', + '/#otros-espacios', + '/#acerca', + '/#filosofia', + '/#contacto', + ]) { + assert.ok( + headerMarkup.includes(`href="${href}"`), + `Built header must use the root-relative href="${href}"`, + ); + } + }); + + await t.test('Criterion 2: built header does not expose a /kundalini/ nav link yet', () => { + const headerMarkup = extractHeaderMarkup(distHtml); + + // Why: /kundalini/ belongs to a later issue; this slice only wires the existing sections. + assert.doesNotMatch( + headerMarkup, + /href="\/kundalini\//i, + 'Built header must not expose a /kundalini/ nav link yet', + ); + }); + + await t.test( + 'Criterion 2: built header marks the root brand link with aria-current="page"', + () => { + const headerMarkup = extractHeaderMarkup(distHtml); + const brandLink = [...headerMarkup.matchAll(/]*>/gi)] + .map((match) => match[0]) + .find((tag) => /\bhref="\/"/i.test(tag)); + assert.ok(brandLink, 'Brand link in built header must target "/"'); + assert.match( + brandLink, + /\baria-current="page"/i, + 'Root brand link must carry aria-current="page" on the home route', + ); + }, + ); + + await t.test('Criterion 2: built header contains exactly one #site-menu navigation tree', () => { + const headerMarkup = extractHeaderMarkup(distHtml); + assert.equal( + headerMarkup.match(/id="site-menu"/gi)?.length ?? 0, + 1, + 'Header must contain exactly one #site-menu navigation tree', + ); + }); + + await t.test('Criterion 2: header disclosure button exposes aria-expanded state', () => { + const disclosureButton = findDisclosureButton(extractHeaderMarkup(distHtml)); + assert.match( + disclosureButton, + /\baria-expanded="(?:true|false)"/i, + 'Disclosure button must expose aria-expanded state', + ); + }); + + await t.test('Criterion 2: header disclosure button meets the 44px minimum touch target', () => { + const disclosureButton = findDisclosureButton(extractHeaderMarkup(distHtml)); + // Why: 44px is the minimum touch target; Tailwind h-11/w-11 equal 44px. + assert.match( + disclosureButton, + /(?:min-)?h-(?:\[44px\]|11)|size-11/i, + 'Disclosure button must have at least a 44px height', + ); + assert.match( + disclosureButton, + /(?:min-)?w-(?:\[44px\]|11)|size-11/i, + 'Disclosure button must have at least a 44px width', + ); + }); + + await t.test( + 'Criterion 1: built footer partial is expanded with the official Facebook link', + () => { + const footerMarkup = distHtml.match(//i)?.[0]; + assert.ok(footerMarkup, 'Built HTML must contain an expanded footer partial'); + assert.match( + footerMarkup, + /href="https:\/\/www\.facebook\.com\/elcorazoncomoportal\/"/i, + 'Built footer must retain the official Facebook link from the footer partial', + ); + }, + ); + + await t.test( + 'Criterion 1: built WhatsApp FAB partial is expanded with the approved wa.me link', + () => { + const fabMarkup = distHtml.match( + /]*class="[^"]*fixed[^"]*bottom-[^"]*right-[^"]*z-50[^"]*"[^>]*>[\s\S]*?<\/a>/i, + )?.[0]; + assert.ok(fabMarkup, 'Built HTML must contain the expanded persistent WhatsApp FAB'); + assert.match( + fabMarkup, + /href="https:\/\/wa\.me\/573215428972/i, + 'Expanded FAB must keep the approved wa.me destination', + ); + }, + ); + + await t.test('Criterion 1: build strips @include markers from built HTML', () => { + assert.doesNotMatch( + distHtml, + /'), + /does-not-exist\.html/i, + 'A missing partial include must throw an error naming the unresolved partial', + ); + }, + ); + + for (const disallowedSpecifier of [ + '../package.json', + 'src/partials/../package.json', + 'src/partials/sub/header.html', + 'src/partials/header.txt', + ]) { + await t.test(`expandHtmlPartials rejects disallowed @include "${disallowedSpecifier}"`, () => { + assert.throws( + () => expandHtmlPartials(``), + /Unsupported @include|Unsafe @include/i, + `Disallowed @include "${disallowedSpecifier}" must be rejected`, + ); + }); + } + + await t.test('transformIndexHtml marks kundalini current and strips home hint in dev ctx', () => { + const plugin = htmlPartialsPlugin(); + plugin.configResolved?.({ root: process.cwd() }); + + const result = plugin.transformIndexHtml.handler(navSampleHtml, { + path: '/kundalini/', + filename: path.resolve('index.html'), + server: {}, + }); + + assert.match(result, /href="\/kundalini\/"[^>]*\baria-current="page"/i); + assert.doesNotMatch(result, /href="\/"[^>]*\baria-current="page"/i); + assert.doesNotMatch(result, /\bdata-nav-current\b/i); + }); + + await t.test( + 'transformIndexHtml marks kundalini current and strips home hint in build ctx', + () => { + const plugin = htmlPartialsPlugin(); + plugin.configResolved?.({ root: process.cwd() }); + + const result = plugin.transformIndexHtml.handler(navSampleHtml, { + path: '/index.html', + filename: path.resolve('kundalini/index.html'), + }); + + assert.match(result, /href="\/kundalini\/"[^>]*\baria-current="page"/i); + assert.doesNotMatch(result, /href="\/"[^>]*\baria-current="page"/i); + assert.doesNotMatch(result, /\bdata-nav-current\b/i); + }, + ); + + await t.test( + 'transformIndexHtml strips all data-nav-current attributes without setting aria-current on non-matching routes', + () => { + const plugin = htmlPartialsPlugin(); + plugin.configResolved?.({ root: process.cwd() }); + + const result = plugin.transformIndexHtml.handler(navSampleHtml, { + path: '/unknown/', + filename: path.resolve('index.html'), + server: {}, + }); + + assert.doesNotMatch(result, /\baria-current=/i); + assert.doesNotMatch(result, /\bdata-nav-current\b/i); + }, + ); +}); diff --git a/tests/nav-menu.test.js b/tests/nav-menu.test.js new file mode 100644 index 0000000..10e8518 --- /dev/null +++ b/tests/nav-menu.test.js @@ -0,0 +1,573 @@ +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