Adds the hero contract: golden files for the picture and the preload links, mapping and seed
Model B (wide 3:2 and tall 4:5 variants, focus point), agreed with the CMS session. Pure functions mapHero, heroHtml and heroPreloadHtml, golden files in web/contract/host-injection/hero with a README, and a seed with a first focus estimate per photo. No site change yet. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
import { isSafeBannerUrl } from './offerings.ts';
|
||||
|
||||
// Turns the answer of GET /api/v1/hero (the CMS) into what the site uses. Pure
|
||||
// functions, tested without a network. Anything that is not clearly valid is
|
||||
// dropped; an answer without a usable slide gives null, so the caller keeps
|
||||
// the hero that was baked into the page (fail open).
|
||||
|
||||
export interface HeroButton {
|
||||
label: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface HeroImageVariant {
|
||||
ratio: string;
|
||||
width: number;
|
||||
type: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface HeroSlide {
|
||||
id: string;
|
||||
alt: string;
|
||||
decorative: boolean;
|
||||
image: {
|
||||
width: number;
|
||||
height: number;
|
||||
// Where the subject is, 0..1; the site uses it as object-position
|
||||
focus: { x: number; y: number } | null;
|
||||
src: string;
|
||||
variants: HeroImageVariant[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface HeroData {
|
||||
display: 'single' | 'slideshow';
|
||||
title: string;
|
||||
tagline?: string;
|
||||
buttons: HeroButton[];
|
||||
slides: HeroSlide[];
|
||||
}
|
||||
|
||||
type Raw = Record<string, unknown>;
|
||||
|
||||
const isObject = (value: unknown): value is Raw =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
|
||||
const asText = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
|
||||
|
||||
const asSize = (value: unknown): number | undefined =>
|
||||
typeof value === 'number' && Number.isInteger(value) && value > 0
|
||||
? value
|
||||
: undefined;
|
||||
|
||||
const BACKSLASH = String.fromCharCode(92);
|
||||
|
||||
// An image address of our own host: a path with one leading slash
|
||||
const isOwnPath = (url: string): boolean =>
|
||||
url.startsWith('/') && !url.startsWith('//') && !url.includes(BACKSLASH);
|
||||
|
||||
// A button goes to an anchor, a path or an https address
|
||||
const isSafeTarget = (target: string): boolean =>
|
||||
/^#[A-Za-z][\w-]*$/.test(target) || isSafeBannerUrl(target);
|
||||
|
||||
function toButton(raw: unknown): HeroButton | null {
|
||||
if (!isObject(raw)) return null;
|
||||
const label = asText(raw.label);
|
||||
const target = asText(raw.target);
|
||||
return label && target && isSafeTarget(target) ? { label, target } : null;
|
||||
}
|
||||
|
||||
function toVariant(raw: unknown): HeroImageVariant | null {
|
||||
if (!isObject(raw)) return null;
|
||||
const ratio = asText(raw.ratio);
|
||||
const type = asText(raw.type);
|
||||
const url = asText(raw.url);
|
||||
const width = asSize(raw.width);
|
||||
return ratio && type && url && width && isOwnPath(url)
|
||||
? { ratio, width, type, url }
|
||||
: null;
|
||||
}
|
||||
|
||||
const inUnit = (value: unknown): value is number =>
|
||||
typeof value === 'number' && value >= 0 && value <= 1;
|
||||
|
||||
function toFocus(raw: unknown): { x: number; y: number } | null {
|
||||
if (!isObject(raw) || !inUnit(raw.x) || !inUnit(raw.y)) return null;
|
||||
return { x: raw.x, y: raw.y };
|
||||
}
|
||||
|
||||
function toSlide(raw: unknown): HeroSlide | null {
|
||||
if (!isObject(raw) || !isObject(raw.image)) return null;
|
||||
const id = asText(raw.id);
|
||||
const decorative = raw.decorative === true;
|
||||
// A photo that says something needs its alt text; a decorative one has none
|
||||
const alt = decorative ? '' : asText(raw.alt);
|
||||
const src = asText(raw.image.src);
|
||||
const width = asSize(raw.image.width);
|
||||
const height = asSize(raw.image.height);
|
||||
if (!id || !src || !isOwnPath(src) || !width || !height) return null;
|
||||
if (alt === undefined) return null;
|
||||
const variants = Array.isArray(raw.image.variants)
|
||||
? raw.image.variants.map(toVariant).filter((v) => v !== null)
|
||||
: [];
|
||||
return {
|
||||
id,
|
||||
alt,
|
||||
decorative,
|
||||
image: {
|
||||
width,
|
||||
height,
|
||||
focus: toFocus(raw.image.focus),
|
||||
src,
|
||||
variants,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function mapHero(answer: unknown): HeroData | null {
|
||||
if (!isObject(answer)) return null;
|
||||
const title = asText(answer.title);
|
||||
const slides = Array.isArray(answer.slides)
|
||||
? answer.slides.map(toSlide).filter((slide) => slide !== null)
|
||||
: [];
|
||||
if (!title || slides.length === 0) return null;
|
||||
const buttons = Array.isArray(answer.buttons)
|
||||
? answer.buttons
|
||||
.map(toButton)
|
||||
.filter((button) => button !== null)
|
||||
.slice(0, 2)
|
||||
: [];
|
||||
return {
|
||||
display: answer.display === 'single' ? 'single' : 'slideshow',
|
||||
title,
|
||||
tagline: asText(answer.tagline),
|
||||
buttons,
|
||||
slides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mapHero } from './hero';
|
||||
import { heroHtml, heroPreloadHtml } from './heroHtml';
|
||||
|
||||
// The contract with the CMS host: for every hero-*.input.json in
|
||||
// contract/host-injection/hero there is an *.expected.html (the region between
|
||||
// <!--CMS:HERO-HTML--> markers) and an *.expected-preload.html (the links
|
||||
// between <!--CMS:HERO-PRELOAD--> markers). Regenerate after a deliberate change
|
||||
// with UPDATE_GOLDEN=1 and send the files to the CMS session.
|
||||
const DIR = join(process.cwd(), 'contract', 'host-injection', 'hero');
|
||||
const inputs = readdirSync(DIR).filter((name) => name.endsWith('.input.json'));
|
||||
|
||||
describe('hero golden files', () => {
|
||||
it('has inputs', () => {
|
||||
expect(inputs.length).toBeGreaterThanOrEqual(6);
|
||||
});
|
||||
|
||||
it.each(inputs)('%s gives the expected HTML and preload', (file) => {
|
||||
const name = file.replace('.input.json', '');
|
||||
const hero = mapHero(JSON.parse(readFileSync(join(DIR, file), 'utf8')));
|
||||
const outputs = [
|
||||
[`${name}.expected.html`, heroHtml(hero)],
|
||||
[`${name}.expected-preload.html`, heroPreloadHtml(hero)],
|
||||
];
|
||||
for (const [expectedName, html] of outputs) {
|
||||
const path = join(DIR, expectedName);
|
||||
if (process.env.UPDATE_GOLDEN === '1') {
|
||||
writeFileSync(path, html + '\n');
|
||||
}
|
||||
expect(html + '\n').toBe(readFileSync(path, 'utf8'));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const slide = (image: object, extra: object = {}) => ({
|
||||
id: 's',
|
||||
alt: 'Alt',
|
||||
decorative: false,
|
||||
image: { width: 10, height: 8, src: '/m/a.webp', ...image },
|
||||
...extra,
|
||||
});
|
||||
|
||||
const answer = (slides: unknown[], extra: object = {}) => ({
|
||||
title: 'T',
|
||||
slides,
|
||||
...extra,
|
||||
});
|
||||
|
||||
describe('mapHero', () => {
|
||||
it('rejects what is not a usable hero', () => {
|
||||
expect(mapHero(null)).toBeNull();
|
||||
expect(mapHero([])).toBeNull();
|
||||
expect(mapHero({ title: 'T' })).toBeNull();
|
||||
expect(mapHero(answer([]))).toBeNull();
|
||||
expect(mapHero({ slides: [slide({})] })).toBeNull();
|
||||
expect(mapHero(answer([slide({})], { title: ' ' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('drops slides that cannot be used', () => {
|
||||
const bad = [
|
||||
null,
|
||||
{ id: 's' },
|
||||
slide({}, { id: '' }),
|
||||
slide({ src: '' }),
|
||||
slide({ src: 'https://evil.example/a.webp' }),
|
||||
slide({ src: '//evil.example/a.webp' }),
|
||||
slide({ src: '/a\\b.webp' }),
|
||||
slide({ width: 0 }),
|
||||
slide({ height: 1.5 }),
|
||||
slide({}, { alt: ' ' }),
|
||||
];
|
||||
expect(mapHero(answer(bad))).toBeNull();
|
||||
expect(mapHero(answer([...bad, slide({})]))?.slides).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps a decorative slide with an empty alt', () => {
|
||||
const hero = mapHero(
|
||||
answer([slide({}, { decorative: true, alt: 'ignored' })]),
|
||||
);
|
||||
expect(hero?.slides[0].alt).toBe('');
|
||||
expect(hero?.slides[0].decorative).toBe(true);
|
||||
});
|
||||
|
||||
it('reads the display, the tagline and at most two safe buttons', () => {
|
||||
const hero = mapHero(
|
||||
answer([slide({})], {
|
||||
display: 'single',
|
||||
tagline: ' Label ',
|
||||
buttons: [
|
||||
null,
|
||||
{ label: 'x', target: 'javascript:1' },
|
||||
{ label: '', target: '/a' },
|
||||
{ label: 'A', target: '#contact' },
|
||||
{ label: 'B', target: '/b' },
|
||||
{ label: 'C', target: 'https://a.example/c' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(hero?.display).toBe('single');
|
||||
expect(hero?.tagline).toBe('Label');
|
||||
expect(hero?.buttons.map((b) => b.label)).toEqual(['A', 'B']);
|
||||
expect(mapHero(answer([slide({})]))?.display).toBe('slideshow');
|
||||
expect(
|
||||
mapHero(answer([slide({})], { buttons: 'nope' }))?.buttons,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps only valid variants and a focus point inside the picture', () => {
|
||||
const hero = mapHero(
|
||||
answer([
|
||||
slide({
|
||||
focus: { x: 0.25, y: 1 },
|
||||
variants: [
|
||||
null,
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 100,
|
||||
type: 'image/webp',
|
||||
url: '/a.webp',
|
||||
},
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 0,
|
||||
type: 'image/webp',
|
||||
url: '/b.webp',
|
||||
},
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 100,
|
||||
type: 'image/webp',
|
||||
url: 'https://x.example/c.webp',
|
||||
},
|
||||
],
|
||||
}),
|
||||
slide({ focus: { x: 2, y: 0 } }),
|
||||
slide({ focus: 'middle', variants: 'none' }),
|
||||
]),
|
||||
);
|
||||
expect(hero?.slides[0].image.variants).toHaveLength(1);
|
||||
expect(hero?.slides[0].image.focus).toEqual({ x: 0.25, y: 1 });
|
||||
expect(hero?.slides[1].image.focus).toBeNull();
|
||||
expect(hero?.slides[2].image.focus).toBeNull();
|
||||
expect(hero?.slides[2].image.variants).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('heroHtml and heroPreloadHtml', () => {
|
||||
it('write nothing for no hero', () => {
|
||||
expect(heroHtml(null)).toBe('');
|
||||
expect(heroPreloadHtml(null)).toBe('');
|
||||
});
|
||||
|
||||
it('leave out what is not there', () => {
|
||||
const hero = mapHero(answer([slide({})]));
|
||||
const html = heroHtml(hero);
|
||||
expect(html).not.toContain('<source');
|
||||
expect(html).not.toContain('srcset');
|
||||
expect(html).not.toContain('style=');
|
||||
expect(html).not.toContain('cms-hero-buttons');
|
||||
expect(html).not.toContain('cms-hero-tagline');
|
||||
expect(heroPreloadHtml(hero)).toBe(
|
||||
'<link rel="preload" as="image" href="/m/a.webp" fetchpriority="high">',
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the same srcset, sizes and media in the picture and the preload', () => {
|
||||
const hero = mapHero(
|
||||
answer([
|
||||
slide({
|
||||
variants: [
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 20,
|
||||
type: 'image/webp',
|
||||
url: '/w20.webp',
|
||||
},
|
||||
{
|
||||
ratio: 'tall',
|
||||
width: 8,
|
||||
type: 'image/webp',
|
||||
url: '/t8.webp',
|
||||
},
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const html = heroHtml(hero);
|
||||
const preload = heroPreloadHtml(hero);
|
||||
for (const part of [
|
||||
'srcset="/t8.webp 8w"',
|
||||
'srcset="/w20.webp 20w"',
|
||||
'media="(orientation: portrait)"',
|
||||
]) {
|
||||
expect(html).toContain(part);
|
||||
}
|
||||
expect(preload).toContain('imagesrcset="/t8.webp 8w"');
|
||||
expect(preload).toContain('imagesrcset="/w20.webp 20w"');
|
||||
expect(preload).toContain('media="(orientation: portrait)"');
|
||||
expect(preload).toContain('media="(orientation: landscape)"');
|
||||
});
|
||||
|
||||
it('preloads the plain image for landscape when only a tall variant has a set', () => {
|
||||
const hero = mapHero(
|
||||
answer([
|
||||
slide({
|
||||
variants: [
|
||||
{
|
||||
ratio: 'tall',
|
||||
width: 8,
|
||||
type: 'image/webp',
|
||||
url: '/t8.webp',
|
||||
},
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(heroPreloadHtml(hero)).toContain(
|
||||
'href="/m/a.webp" media="(orientation: landscape)"',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps one preload without media when there is no tall variant', () => {
|
||||
const hero = mapHero(
|
||||
answer([
|
||||
slide({
|
||||
variants: [
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 20,
|
||||
type: 'image/webp',
|
||||
url: '/w20.webp',
|
||||
},
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(heroPreloadHtml(hero)).toBe(
|
||||
'<link rel="preload" as="image" imagesrcset="/w20.webp 20w" imagesizes="100vw" fetchpriority="high">',
|
||||
);
|
||||
});
|
||||
|
||||
it('writes the focus point as object-position', () => {
|
||||
const hero = mapHero(answer([slide({ focus: { x: 0.333333, y: 0 } })]));
|
||||
expect(heroHtml(hero)).toContain('style="object-position:33.33% 0%"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { escapeHtml } from './cmsHtml.ts';
|
||||
import type { HeroData, HeroImageVariant, HeroSlide } from './hero.ts';
|
||||
|
||||
// The neutral HTML of the hero between the CMS markers, and the preload links
|
||||
// in the head. The host (SLP Modular CMS) writes the same markup from live
|
||||
// data; the golden files in contract/host-injection/hero are the contract.
|
||||
//
|
||||
// Only the FIRST slide is written (it is the LCP image); the client takes the
|
||||
// rest from the data block. The picture holds one <source> for portrait
|
||||
// screens (ratio "tall") and the <img> itself is the landscape one (ratio
|
||||
// "wide"). Selection is by orientation, because the hero is as high as the
|
||||
// screen. The preload links repeat exactly the same srcset, sizes and media,
|
||||
// so the browser starts the very file the picture will pick.
|
||||
//
|
||||
// Only WebP is used here: a preload cannot say "AVIF if supported", so a
|
||||
// second format would be fetched twice. Later slides may use AVIF.
|
||||
|
||||
const PORTRAIT = '(orientation: portrait)';
|
||||
const LANDSCAPE = '(orientation: landscape)';
|
||||
const SIZES = '100vw';
|
||||
|
||||
const srcsetOf = (variants: HeroImageVariant[], ratio: string): string =>
|
||||
variants
|
||||
.filter((v) => v.ratio === ratio && v.type === 'image/webp')
|
||||
.sort((a, b) => a.width - b.width)
|
||||
.map((v) => `${escapeHtml(v.url)} ${v.width}w`)
|
||||
.join(', ');
|
||||
|
||||
const percent = (unit: number): string => `${Number((unit * 100).toFixed(2))}%`;
|
||||
|
||||
const focusStyle = (slide: HeroSlide): string => {
|
||||
const { focus } = slide.image;
|
||||
return focus
|
||||
? ` style="object-position:${percent(focus.x)} ${percent(focus.y)}"`
|
||||
: '';
|
||||
};
|
||||
|
||||
function pictureHtml(slide: HeroSlide): string {
|
||||
const { image } = slide;
|
||||
const tall = srcsetOf(image.variants, 'tall');
|
||||
const wide = srcsetOf(image.variants, 'wide');
|
||||
const source = tall
|
||||
? `<source media="${PORTRAIT}" srcset="${tall}" sizes="${SIZES}" type="image/webp">`
|
||||
: '';
|
||||
const img =
|
||||
`<img class="cms-hero-image" src="${escapeHtml(image.src)}"` +
|
||||
(wide ? ` srcset="${wide}" sizes="${SIZES}"` : '') +
|
||||
` width="${image.width}" height="${image.height}"` +
|
||||
` alt="${escapeHtml(slide.alt)}"${focusStyle(slide)}` +
|
||||
' fetchpriority="high">';
|
||||
return `<picture class="cms-hero-picture">${source}${img}</picture>`;
|
||||
}
|
||||
|
||||
function headingHtml(hero: HeroData): string {
|
||||
const tagline = hero.tagline
|
||||
? `<span class="cms-hero-tagline">${escapeHtml(hero.tagline)}</span> `
|
||||
: '';
|
||||
// A new line in the title is a line break
|
||||
const name = escapeHtml(hero.title).replace(/\r?\n/g, '<br>');
|
||||
return `<h1 class="cms-hero-title">${tagline}<span class="cms-hero-name">${name}</span></h1>`;
|
||||
}
|
||||
|
||||
function buttonsHtml(hero: HeroData): string {
|
||||
if (hero.buttons.length === 0) return '';
|
||||
const links = hero.buttons
|
||||
.map(
|
||||
(button) =>
|
||||
`<a class="cms-hero-button" href="${escapeHtml(button.target)}">${escapeHtml(button.label)}</a>`,
|
||||
)
|
||||
.join('');
|
||||
return `<p class="cms-hero-buttons">${links}</p>`;
|
||||
}
|
||||
|
||||
// Between <!--CMS:HERO-HTML--> and <!--/CMS:HERO-HTML-->; nothing for no hero
|
||||
export function heroHtml(hero: HeroData | null): string {
|
||||
if (!hero) return '';
|
||||
return pictureHtml(hero.slides[0]) + headingHtml(hero) + buttonsHtml(hero);
|
||||
}
|
||||
|
||||
// Between <!--CMS:HERO-PRELOAD--> and <!--/CMS:HERO-PRELOAD--> in the head: one
|
||||
// link for portrait screens (when a tall variant exists) and one for the
|
||||
// others. Without a tall variant a single link without media is enough.
|
||||
export function heroPreloadHtml(hero: HeroData | null): string {
|
||||
if (!hero) return '';
|
||||
const { image } = hero.slides[0];
|
||||
const tall = srcsetOf(image.variants, 'tall');
|
||||
const wide = srcsetOf(image.variants, 'wide');
|
||||
const link = (target: string, media: string): string =>
|
||||
`<link rel="preload" as="image" ${target}` +
|
||||
`${media ? ` media="${media}"` : ''} fetchpriority="high">`;
|
||||
const wideTarget = wide
|
||||
? `imagesrcset="${wide}" imagesizes="${SIZES}"`
|
||||
: `href="${escapeHtml(image.src)}"`;
|
||||
if (!tall) return link(wideTarget, '');
|
||||
return (
|
||||
link(`imagesrcset="${tall}" imagesizes="${SIZES}"`, PORTRAIT) +
|
||||
link(wideTarget, LANDSCAPE)
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user