import { heroPreloadHtml } from '../src/lib/heroHtml.ts';
// The preload link of the hero in the head of a prerendered page, between the
// markers the CMS host rewrites (). React cannot write
// a comment into the head, so the build step adds it to the finished HTML,
// from the baked first photo of the page. Pages without a hero stay as they
// are, and so does a page that already has the markers (running twice is fine).
const MARK = '';
const HERO_IMAGE =
/
]*\bclass="cms-hero-image"[^>]*\bsrc="([^"]+)"|
]*\bsrc="([^"]+)"[^>]*\bclass="cms-hero-image"/;
export function injectHeroPreload(html: string): string {
if (html.includes(MARK)) return html;
const found = HERO_IMAGE.exec(html);
const src = found?.[1] ?? found?.[2];
const end = html.indexOf('');
if (src === undefined || end === -1) return html;
// The src is already escaped in the HTML; the link is built from the same
// text, so it is written back unchanged
const link = heroPreloadHtml({
display: 'single',
title: '',
buttons: [],
slides: [
{
id: 'baked',
alt: '',
decorative: false,
image: {
width: 1,
height: 1,
focus: null,
src: '',
variants: [],
},
},
],
}).replace('href=""', `href="${src}"`);
return (
html.slice(0, end) +
`${MARK}${link}` +
html.slice(end)
);
}