Files
Andrés Tróchez a340121acc 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
2026-11-30 01:56:48 -05:00

574 lines
20 KiB
JavaScript

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(/<script\b[^>]*>/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(/<script\b[^>]*>/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(/<button\b[^>]*>/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 <nav> so the header flex row has two children',
() => {
const distHtml = readRequired(distIndexPath);
const headerInnerTag = distHtml.match(
/<header\b[^>]*>\s*(?:<!--[\s\S]*?-->\s*)*(<div\b[^>]*>)/i,
)?.[1];
assert.ok(headerInnerTag, 'Built index.html must render the header inner flex container');
assert.ok(
classTokens(headerInnerTag).has('gap-4'),
'Header flex container must include gap-4 to keep spacing between brand and nav',
);
const navInner = distHtml.match(/<nav\b[^>]*>([\s\S]*?)<\/nav>/i)?.[1];
assert.ok(navInner, 'Built index.html must render a <nav> element');
assert.match(
navInner,
/<button\b[^>]*\baria-controls="site-menu"/i,
'Disclosure <button aria-controls="site-menu"> must be placed inside <nav>',
);
},
);
await t.test(
'built header keeps the full brand title outside #site-menu without hiding or truncation',
() => {
const distHtml = readRequired(distIndexPath);
const brandLink = distHtml.match(/<a\b[^>]*href="\/"[^>]*>([\s\S]*?)<\/a>/i)?.[0];
assert.ok(brandLink, 'Built index.html must render the root brand link');
const brandText = brandLink
.replace(/<[^>]*>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
assert.match(brandText, /El Corazón como Portal/i, 'Brand title must remain fully authored');
// Why: the 375px menu may expand below the header row, but it must never
// become the only place where the brand title lives.
const menuTag = openingTagById(distHtml, 'site-menu');
assert.ok(menuTag, 'Built index.html must define the #site-menu panel');
assert.ok(
distHtml.indexOf(brandLink) < distHtml.indexOf(menuTag),
'Brand link must stay in the header row, before the collapsible menu',
);
const brandClasses = classTokens(brandLink.match(/<a\b[^>]*>/i)?.[0] ?? '');
assert.ok(
brandClasses.has('shrink-0'),
'Brand link must include shrink-0 so it does not compress at intermediate viewports',
);
for (const className of [
'hidden',
'md:hidden',
'lg:hidden',
'invisible',
'sr-only',
'truncate',
'text-ellipsis',
'overflow-hidden',
]) {
assert.ok(
!brandClasses.has(className),
`Brand link must not hide or truncate its title (found ${className})`,
);
}
},
);
await t.test(
'built CSS sets html scroll-padding-top: 5.5rem for sticky-header hash jumps',
() => {
const css = readBuiltCss();
assert.match(
css,
/html\s*\{[^}]*scroll-padding-top\s*:\s*5\.5rem\s*;?[^}]*\}/i,
'Built CSS must include html { scroll-padding-top: 5.5rem }',
);
},
);
await t.test('built CSS underlines active nav links (a[aria-current=page])', () => {
const css = readBuiltCss();
// Why: an underline keeps the active route distinguishable without relying
// on color alone; >= 3:1 indicator contrast is verified in visual QA.
const currentBody = cssRuleBody(css, /a\[aria-current=["']?page["']?\]\s*\{/i);
assert.match(
currentBody,
/text-decoration\s*:\s*underline/i,
'Active nav link must be underlined',
);
assert.match(currentBody, /text-underline-offset\s*:/i, 'Active underline must be offset');
assert.match(
currentBody,
/text-decoration-thickness\s*:/i,
'Active underline must have thickness',
);
});
await t.test('built CSS defines emerald :focus-visible outline with offset', () => {
const css = readBuiltCss();
const focusBody = cssRuleBody(css, /:focus-visible\s*\{/i);
assert.match(focusBody, /outline\s*:/i, ':focus-visible must define an outline');
assert.match(focusBody, /var\(--color-emerald\)/i, ':focus-visible outline must use emerald');
assert.match(focusBody, /outline-offset\s*:/i, ':focus-visible outline must be offset');
});
await t.test('built CSS disables smooth scrolling under prefers-reduced-motion: reduce', () => {
const css = readBuiltCss();
const mediaIndex = css.search(/@media\s*\(prefers-reduced-motion:\s*reduce\)/i);
assert.notEqual(mediaIndex, -1, 'Built CSS must include a prefers-reduced-motion media query');
assert.match(
cssBlock(css, mediaIndex),
/scroll-behavior\s*:\s*auto/i,
'Reduced-motion users must not get smooth scrolling',
);
});
await t.test(
'built CSS styles disclaimer label as a 44px touch target with emerald accent',
() => {
const css = readBuiltCss();
const labelBody = cssRuleBody(css, /label\[for=["']?accept-disclaimer["']?\]\s*\{/i);
assert.match(
labelBody,
/min-height\s*:\s*44px/i,
'Disclaimer label must be a 44px touch target',
);
assert.match(
labelBody,
/accent-color\s*:/i,
'Disclaimer label must set the emerald accent color',
);
},
);
await t.test('built CSS dims and blocks cursor on aria-disabled="true" links', () => {
const css = readBuiltCss();
const disabledBody = cssRuleBody(css, /a\[aria-disabled=["']?true["']?\]\s*\{/i);
assert.match(disabledBody, /opacity\s*:\s*0?\.55/i, 'Gated links must have locked opacity');
assert.match(
disabledBody,
/cursor\s*:\s*not-allowed/i,
'Gated links must use a blocked cursor',
);
});
});