Files
corazoncp-landing/scripts/html-partials-plugin.ts
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

162 lines
6.0 KiB
TypeScript

/**
* 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;