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
This commit is contained in:
Andrés Tróchez authored and GitHub committed 2026-11-30 01:56:48 -05:00
1 parent 9b95141933
commit a340121acc
12 files changed
+1275 -81

No files matched your search

+17 -78
View File
@@ -8,6 +8,19 @@
name="description" 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." 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."
/> />
<link rel="canonical" href="https://elcorazoncomoportal.com/" />
<meta property="og:type" content="website" />
<meta property="og:locale" content="es_CO" />
<meta property="og:title" content="El Corazón como Portal — Acompañamiento Consciente en Valledupar" />
<meta
property="og: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."
/>
<meta property="og:url" content="https://elcorazoncomoportal.com/" />
<meta property="og:image" content="https://elcorazoncomoportal.com/img/azu-hero.jpg" />
<meta property="og:image:width" content="529" />
<meta property="og:image:height" content="530" />
<meta property="og:image:alt" content="Azucena Sánchez, facilitadora de El Corazón como Portal" />
<link rel="icon" type="image/png" href="/img/logo.png" /> <link rel="icon" type="image/png" href="/img/logo.png" />
<link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
@@ -18,38 +31,9 @@
<link rel="stylesheet" href="/src/style.css" /> <link rel="stylesheet" href="/src/style.css" />
</head> </head>
<body class="bg-ivory text-forest selection:bg-emerald/20 selection:text-forest"> <body class="bg-ivory text-forest selection:bg-emerald/20 selection:text-forest">
<!-- Floating WhatsApp Action --> <!-- @include src/partials/whatsapp-fab.html -->
<a
href="https://wa.me/573215428972?text=Hola%20Azu,%20visit%C3%A9%20tu%20p%C3%A1gina%20y%20me%20gustar%C3%ADa%20conversar%20sobre%20tus%20sesiones."
target="_blank"
rel="noopener noreferrer"
class="fixed bottom-5 right-5 z-50 flex min-h-[48px] min-w-[48px] items-center gap-2.5 rounded-full bg-[#25D366] px-5 py-3 text-sm font-bold text-white shadow-lg shadow-black/20 transition hover:scale-105 hover:bg-[#20ba59] hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-[#25D366]/40 active:scale-95"
aria-label="Conversar por WhatsApp con Azucena Sánchez"
>
<svg class="h-6 w-6 fill-current shrink-0" viewBox="0 0 24 24" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
<path d="M17.472 14.382c-.301-.15-1.78-.878-2.056-.979-.276-.101-.477-.15-.678.15-.201.301-.778.979-.954 1.18-.176.201-.352.226-.653.075-1.428-.714-2.36-1.272-3.308-2.898-.25-.43.25-.399.715-1.328.075-.15.038-.276-.019-.377-.057-.101-.477-1.155-.653-1.581-.172-.416-.347-.36-.477-.366-.124-.007-.276-.007-.427-.007-.15 0-.395.056-.602.282-.207.226-.791.772-.791 1.884 0 1.112.81 2.186.923 2.337.113.151 1.595 2.435 3.864 3.414.539.233.96.372 1.288.476.541.172 1.034.148 1.423.09.434-.065 1.334-.545 1.522-1.072.188-.528.188-.98.132-1.072-.056-.092-.207-.15-.508-.3zM12.008 2.004c-5.502 0-9.98 4.478-9.98 9.98 0 1.76.459 3.475 1.332 4.992L2.004 22l5.163-1.353a9.948 9.948 0 0 0 4.841 1.337c5.502 0 9.98-4.478 9.98-9.98 0-5.502-4.478-9.98-9.98-9.98zm0 18.293a8.283 8.283 0 0 1-4.226-1.153l-.303-.18-3.141.824.838-3.061-.197-.314a8.275 8.275 0 0 1-1.267-4.409c0-4.573 3.723-8.296 8.296-8.296 4.573 0 8.296 3.723 8.296 8.296 0 4.573-3.723 8.296-8.296 8.296z"/>
</svg>
<span>Conversar con Azu</span>
</a>
<!-- Section 01: Header & Minimal Nav --> <!-- @include src/partials/header.html -->
<header class="sticky top-0 z-40 border-b border-sage/30 bg-sage/15 backdrop-blur-md">
<div class="mx-auto flex max-w-6xl items-center justify-between px-6 py-4">
<a href="#hero" class="flex items-center gap-3">
<img src="/img/logo.png" alt="Logo El Corazón como Portal" class="h-10 w-10 object-contain" />
<span class="font-display text-xl font-bold tracking-wider uppercase text-forest">El Corazón como Portal</span>
</a>
<nav aria-label="Navegación principal">
<ul class="hidden md:flex md:items-center md:gap-8 text-sm font-medium text-forest">
<li><a href="#servicios" class="transition hover:text-emerald">Servicios</a></li>
<li><a href="#otros-espacios" class="transition hover:text-emerald">Otros Espacios</a></li>
<li><a href="#acerca" class="transition hover:text-emerald">Acerca de Azu</a></li>
<li><a href="#filosofia" class="transition hover:text-emerald">Filosofía</a></li>
<li><a href="#contacto" class="transition hover:text-emerald">Contacto</a></li>
</ul>
</nav>
</div>
</header>
<main> <main>
<!-- Section 02: Hero --> <!-- Section 02: Hero -->
@@ -526,52 +510,7 @@
</section> </section>
</main> </main>
<!-- Footer --> <!-- @include src/partials/footer.html -->
<footer class="mt-16 border-t border-sage/20 py-12 text-center text-xs text-forest/60"> <script type="module" src="/src/scripts/nav-menu.js"></script>
<div class="mx-auto max-w-6xl px-6">
<div class="flex items-center justify-center gap-6 mb-4">
<a
href="https://www.facebook.com/elcorazoncomoportal/"
target="_blank"
rel="noopener noreferrer"
class="transition hover:text-emerald font-medium"
aria-label="Facebook Fanpage oficial de El Corazón como Portal"
>
Facebook
</a>
<span>·</span>
<a
href="https://www.instagram.com/elcorazoncomoportal"
target="_blank"
rel="noopener noreferrer"
class="transition hover:text-emerald font-medium"
aria-label="Instagram"
>
Instagram
</a>
<span>·</span>
<a
href="https://www.youtube.com/@Elcoraz%C3%B3ncomoportal"
target="_blank"
rel="noopener noreferrer"
class="transition hover:text-emerald font-medium"
aria-label="YouTube"
>
YouTube
</a>
<span>·</span>
<a
href="https://x.com/Elcorazoncp"
target="_blank"
rel="noopener noreferrer"
class="transition hover:text-emerald font-medium"
aria-label="X Twitter"
>
X (Twitter)
</a>
</div>
<p>© 2026 El Corazón como Portal · Todos los derechos reservados · Valledupar, Colombia</p>
</div>
</footer>
</body> </body>
</html> </html>
+161
View File
@@ -0,0 +1,161 @@
/**
* Build-time HTML partial inclusion and route-aware navigation rewriting.
*
* The plugin emits no runtime JS: it expands `<!-- @include ... -->` 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 = /<!--\s*@include\s+([^\s>]+)\s*-->/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/<name>.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 `<!-- @include src/partials/<name>.html -->` 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;
+47
View File
@@ -0,0 +1,47 @@
<!-- Footer -->
<footer class="mt-16 border-t border-sage/20 py-12 text-center text-xs text-forest/60">
<div class="mx-auto max-w-6xl px-6">
<div class="flex items-center justify-center gap-6 mb-4">
<a
href="https://www.facebook.com/elcorazoncomoportal/"
target="_blank"
rel="noopener noreferrer"
class="transition hover:text-emerald font-medium"
aria-label="Facebook Fanpage oficial de El Corazón como Portal"
>
Facebook
</a>
<span>·</span>
<a
href="https://www.instagram.com/elcorazoncomoportal"
target="_blank"
rel="noopener noreferrer"
class="transition hover:text-emerald font-medium"
aria-label="Instagram"
>
Instagram
</a>
<span>·</span>
<a
href="https://www.youtube.com/@Elcoraz%C3%B3ncomoportal"
target="_blank"
rel="noopener noreferrer"
class="transition hover:text-emerald font-medium"
aria-label="YouTube"
>
YouTube
</a>
<span>·</span>
<a
href="https://x.com/Elcorazoncp"
target="_blank"
rel="noopener noreferrer"
class="transition hover:text-emerald font-medium"
aria-label="X Twitter"
>
X (Twitter)
</a>
</div>
<p>© 2026 El Corazón como Portal · Todos los derechos reservados · Valledupar, Colombia</p>
</div>
</footer>
+33
View File
@@ -0,0 +1,33 @@
<!-- Section 01: Header & Minimal Nav -->
<header class="sticky top-0 z-40 border-b border-sage/30 bg-sage/15 backdrop-blur-md">
<!-- Why: lg (1024px) desktop nav breakpoint + shrink-0 on the brand + gap-4 prevents brand/nav overlap at 768px–1018px. -->
<div class="relative mx-auto flex max-w-6xl items-center justify-between gap-4 px-6 py-4">
<!-- Why: the full brand title stays in the header row at 375px; only the nav collapses. -->
<a href="/" data-nav-current="home" class="flex shrink-0 items-center gap-3">
<img src="/img/logo.png" alt="Logo El Corazón como Portal" class="h-10 w-10 object-contain" />
<span class="font-display text-sm font-bold tracking-wide uppercase whitespace-nowrap text-forest sm:text-xl sm:tracking-wider">El Corazón como Portal</span>
</a>
<nav aria-label="Navegación principal">
<!-- Why: keeping the toggle inside <nav> leaves only two flex children in the header row so the toggle stays flush right on 430px–767px viewports instead of floating between the brand link and a 0px <nav>. -->
<button
type="button"
aria-expanded="false"
aria-controls="site-menu"
aria-label="Abrir menú de navegación"
class="inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-full text-forest transition hover:bg-sage/20 lg:hidden"
>
<svg class="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
<path d="M4 7h16M4 12h16M4 17h16" />
</svg>
</button>
<!-- Why: a single nav tree keeps screen-reader and visual order aligned at every breakpoint. -->
<ul id="site-menu" class="hidden absolute inset-x-0 top-full z-40 flex-col space-y-4 border-b border-sage/30 bg-ivory/95 px-6 py-5 text-sm font-medium text-forest shadow-lg backdrop-blur-md lg:static lg:flex lg:flex-row lg:items-center lg:gap-8 lg:space-y-0 lg:border-b-0 lg:bg-transparent lg:p-0 lg:shadow-none">
<li><a href="/#servicios" class="block transition hover:text-emerald">Servicios</a></li>
<li><a href="/#otros-espacios" class="block transition hover:text-emerald">Otros Espacios</a></li>
<li><a href="/#acerca" class="block transition hover:text-emerald">Acerca de Azu</a></li>
<li><a href="/#filosofia" class="block transition hover:text-emerald">Filosofía</a></li>
<li><a href="/#contacto" class="block transition hover:text-emerald">Contacto</a></li>
</ul>
</nav>
</div>
</header>
+13
View File
@@ -0,0 +1,13 @@
<!-- Floating WhatsApp Action -->
<a
href="https://wa.me/573215428972?text=Hola%20Azu,%20visit%C3%A9%20tu%20p%C3%A1gina%20y%20me%20gustar%C3%ADa%20conversar%20sobre%20tus%20sesiones."
target="_blank"
rel="noopener noreferrer"
class="fixed bottom-5 right-5 z-50 flex min-h-[48px] min-w-[48px] items-center gap-2.5 rounded-full bg-[#25D366] px-5 py-3 text-sm font-bold text-white shadow-lg shadow-black/20 transition hover:scale-105 hover:bg-[#20ba59] hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-[#25D366]/40 active:scale-95"
aria-label="Conversar por WhatsApp con Azucena Sánchez"
>
<svg class="h-6 w-6 fill-current shrink-0" viewBox="0 0 24 24" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
<path d="M17.472 14.382c-.301-.15-1.78-.878-2.056-.979-.276-.101-.477-.15-.678.15-.201.301-.778.979-.954 1.18-.176.201-.352.226-.653.075-1.428-.714-2.36-1.272-3.308-2.898-.25-.43.25-.399.715-1.328.075-.15.038-.276-.019-.377-.057-.101-.477-1.155-.653-1.581-.172-.416-.347-.36-.477-.366-.124-.007-.276-.007-.427-.007-.15 0-.395.056-.602.282-.207.226-.791.772-.791 1.884 0 1.112.81 2.186.923 2.337.113.151 1.595 2.435 3.864 3.414.539.233.96.372 1.288.476.541.172 1.034.148 1.423.09.434-.065 1.334-.545 1.522-1.072.188-.528.188-.98.132-1.072-.056-.092-.207-.15-.508-.3zM12.008 2.004c-5.502 0-9.98 4.478-9.98 9.98 0 1.76.459 3.475 1.332 4.992L2.004 22l5.163-1.353a9.948 9.948 0 0 0 4.841 1.337c5.502 0 9.98-4.478 9.98-9.98 0-5.502-4.478-9.98-9.98-9.98zm0 18.293a8.283 8.283 0 0 1-4.226-1.153l-.303-.18-3.141.824.838-3.061-.197-.314a8.275 8.275 0 0 1-1.267-4.409c0-4.573 3.723-8.296 8.296-8.296 4.573 0 8.296 3.723 8.296 8.296 0 4.573-3.723 8.296-8.296 8.296z"/>
</svg>
<span>Conversar con Azu</span>
</a>
+38
View File
@@ -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();
}
});
}
+42
View File
@@ -20,3 +20,45 @@ body {
font-family: var(--font-sans); font-family: var(--font-sans);
-webkit-font-smoothing: antialiased; -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;
}
+3 -1
View File
@@ -3,7 +3,9 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import test from 'node:test'; 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'); const indexHtml = fs.readFileSync(indexPath, 'utf-8');
test('Slice 2 Acceptance Criteria: Hero and WhatsApp Flow', async (t) => { test('Slice 2 Acceptance Criteria: Hero and WhatsApp Flow', async (t) => {
+336
View File
@@ -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(/<meta\b[^>]*>/gi)]
.map((match) => match[0])
.find((tag) => tag.toLowerCase().includes(`property="${property}"`));
}
function extractHeaderMarkup(html) {
const headerMarkup = html.match(/<header\b[\s\S]*?<\/header>/i)?.[0];
assert.ok(headerMarkup, 'Built HTML must contain an expanded header partial');
return headerMarkup;
}
function findDisclosureButton(headerMarkup) {
const disclosureButton = [...headerMarkup.matchAll(/<button\b[^>]*>/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 <h3> heading and return its enclosing card <div>.
* Why: avoids coupling tests to HTML comments that minification may strip.
*/
function extractCardByHeading(html, headingText) {
const headingMatch = new RegExp(`<h3\\b[^>]*>[^<]*${headingText}[^<]*</h3>`, 'i').exec(html);
if (!headingMatch) {
return undefined;
}
const cardOpenPattern = /<div\b[^>]*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('</') ? -1 : 1;
if (depth === 0) {
return html.slice(cardStart, tagMatch.index + tagMatch[0].length);
}
}
return undefined;
}
test('Issue #5 Acceptance Criteria: built partials, navigation and metadata', async (t) => {
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(/<a\b[^>]*>/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(/<footer\b[\s\S]*?<\/footer>/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(
/<a[^>]*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,
/<!--\s*@include/i,
'Built HTML must not leak any @include markers',
);
});
await t.test('Criterion 1: build strips data-nav-current hints from built HTML', () => {
assert.doesNotMatch(
distHtml,
/data-nav-current(?:="[^"]*")?/i,
'Build-time data-nav-current hints must be stripped from built HTML',
);
});
await t.test('Criterion 4: built HTML carries canonical link to the site root', () => {
const canonicalTag = [...distHtml.matchAll(/<link\b[^>]*>/gi)]
.map((match) => match[0])
.find((tag) => tag.toLowerCase().includes('rel="canonical"'));
assert.ok(canonicalTag, 'Built HTML must include a canonical link tag');
assert.match(
canonicalTag,
/href="https:\/\/elcorazoncomoportal\.com\/"/i,
'Canonical URL must be the site root',
);
});
await t.test('Criterion 4: built HTML carries non-empty og:title metadata', () => {
const ogTitle = findMetaByProperty(distHtml, 'og:title');
assert.ok(ogTitle, 'Built HTML must include og:title');
assert.match(ogTitle, /content="[^"]+"/i, 'og:title must have non-empty content');
});
await t.test('Criterion 4: built HTML carries non-empty og:description metadata', () => {
const ogDescription = findMetaByProperty(distHtml, 'og:description');
assert.ok(ogDescription, 'Built HTML must include og:description');
assert.match(ogDescription, /content="[^"]+"/i, 'og:description must have non-empty content');
});
await t.test('Criterion 4: built HTML carries og:url pointing to the site root', () => {
const ogUrl = findMetaByProperty(distHtml, 'og:url');
assert.ok(ogUrl, 'Built HTML must include og:url');
assert.match(
ogUrl,
/content="https:\/\/elcorazoncomoportal\.com\/"/i,
'og:url must point to the site root',
);
});
await t.test('Criterion 4: built HTML carries og:image using the approved hero asset', () => {
const ogImage = findMetaByProperty(distHtml, 'og:image');
assert.ok(ogImage, 'Built HTML must include og:image');
assert.match(
ogImage,
/content="https:\/\/elcorazoncomoportal\.com\/img\/azu-hero\.jpg"/i,
'og:image must use the approved absolute azu-hero.jpg URL',
);
});
await t.test('Criterion 4: Kundalini service card keeps its live wa.me CTA', () => {
const kundaliniCard = extractCardByHeading(
distHtml,
'Clases de Kundalini Yoga y Acompañamientos',
);
assert.ok(kundaliniCard, 'Service Card 2 (Kundalini Yoga) must exist in built HTML');
assert.match(
kundaliniCard,
/href="https:\/\/wa\.me\/573215428972\?text=[^"]*Kundalini/i,
'Service Card 2 must keep its live wa.me inquiry link in this issue',
);
assert.doesNotMatch(
kundaliniCard,
/href="\/kundalini\//i,
'A local /kundalini/ card link belongs to a later issue',
);
});
});
test('html-partials-plugin unit behavior', async (t) => {
const navSampleHtml =
'<nav><a href="/" data-nav-current="home">Inicio</a><a href="/kundalini/" data-nav-current="kundalini">Kundalini</a></nav>';
await t.test(
'expandHtmlPartials rejects a missing partial path naming the unresolved file',
() => {
assert.throws(
() => expandHtmlPartials('<!-- @include src/partials/does-not-exist.html -->'),
/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(`<!-- @include ${disallowedSpecifier} -->`),
/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);
},
);
});
+573
View File
@@ -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(/<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',
);
});
});
+3 -1
View File
@@ -3,7 +3,9 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import test from 'node:test'; import test from 'node:test';
const indexPath = path.resolve('index.html'); // Why: built HTML is the deployable artifact and the seam where partials are expanded;
// design tokens intentionally remain asserted against the source stylesheet.
const indexPath = path.resolve('dist/index.html');
const indexHtml = fs.readFileSync(indexPath, 'utf-8'); const indexHtml = fs.readFileSync(indexPath, 'utf-8');
const cssPath = path.resolve('src/style.css'); const cssPath = path.resolve('src/style.css');
+9 -1
View File
@@ -1,8 +1,10 @@
import path from 'node:path';
import tailwindcss from '@tailwindcss/vite'; import tailwindcss from '@tailwindcss/vite';
import { defineConfig } from 'vite-plus'; import { defineConfig } from 'vite-plus';
import htmlPartialsPlugin from './scripts/html-partials-plugin.ts';
export default defineConfig({ export default defineConfig({
plugins: [tailwindcss()], plugins: [tailwindcss(), htmlPartialsPlugin()],
server: { server: {
port: 3000, port: 3000,
open: false, open: false,
@@ -10,5 +12,11 @@ export default defineConfig({
build: { build: {
outDir: 'dist', outDir: 'dist',
sourcemap: true, sourcemap: true,
// Why: Phase 1 has one HTML entrypoint; the other routes land with their files.
rollupOptions: {
input: {
main: path.resolve(import.meta.dirname, 'index.html'),
},
},
}, },
}); });