Files
corazoncp-landing/tests/html-partials.test.js
T
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

337 lines
12 KiB
JavaScript

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);
},
);
});