Files
ipal-kit/test/blockLibraryRender.test.ts
Radosław SmolińskiandClaude Opus 5.5 6f56ef4205 Block library: item headings follow the section; the leading block's first image is the LCP image
Found by ipal-doctor live-seo on the reference archive pages (entry list under a
page header without a picture): cards jumped h1 → h3, and the first card image
was lazy.

- itemHeadingLevel: items one below the section heading (h3 under h2, h2 under the
  page h1, h2 when the block shows no heading); createBlockRegistry({ itemHeadings })
  fixes a level per block. featureGrid, entryList, pricing, steps, team.
- blockPosition / blockHasImage (root): createPageRoute and the 404 view pass
  firstImage next to isFirst; leadsWithImage marks the first image of the leading
  block eager + fetchPriority high (hero, textMedia, featureGrid, gallery, team,
  entryList); priorityImage: false turns it off.
- reference/ipal-doctor.json: the two live-seo silences removed; reference skills
  and docs/agent/reference-site/INDEX.md refreshed.
- bin/ipal-blocks.mjs executable like the other bins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:38:04 +01:00

297 lines
18 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { ReactElement, ReactNode } from 'react'
import { Children, cloneElement, createElement as h, isValidElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'
import type { BlockContent, BlockRegistryOptions } from '../src/exports/blocks-rsc.js'
import { createBlockRegistry, LIBRARY_BLOCK_COMPONENTS } from '../src/exports/blocks-rsc.js'
vi.mock('server-only', () => ({}))
/**
* React server components can be async; react-dom/server can't await them. This expands
* the tree first: server components are called (and awaited); a component that uses hooks
* (a client component) throws when called outside React, and stays as an element.
*/
async function expand(node: ReactNode): Promise<ReactNode> {
if (Array.isArray(node)) {return Promise.all(node.map(expand))}
if (!isValidElement(node)) {return node}
const el = node as ReactElement<{ children?: ReactNode }>
if (typeof el.type === 'function') {
let out: unknown
try {
out = (el.type as (p: unknown) => unknown)(el.props)
} catch {
out = undefined
}
if (out !== undefined) {return expand((await Promise.resolve(out)) as ReactNode)}
}
const children = el.props.children
if (children === undefined) {return el}
const kids = await Promise.all(Children.toArray(children).map(expand))
return cloneElement(el, undefined, ...kids)
}
const render = async (node: ReactNode) => renderToStaticMarkup(h('div', null, (await expand(node)) as ReactNode))
const image = (alt = 'Photo') => ({ id: 1, alt, filename: 'a.jpg', height: 600, mimeType: 'image/jpeg', url: '/media/a.jpg', width: 900 })
const link = (label: string) => ({ type: 'internal' as const, appearance: 'primary', label, page: { id: 2, slug: 'kontakt' } })
const links = [{ id: 'l1', link: link('Contact us') }]
const content: BlockContent = {
getEntries: vi.fn(async () => ({ docs: [{ id: 7, slug: 'first', media: image('Cover'), publishedAt: '2026-10-01T00:00:00.000Z', title: 'First post' }, { id: 8, slug: 'second', media: image('Second'), title: 'Second post' }], hasNextPage: false, hasPrevPage: false, page: 1, totalDocs: 1, totalPages: 1 })),
getFormTexts: vi.fn(async () => ({})),
getLinkOptions: vi.fn(async () => ({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }] }, locale: 'pl' }) as never),
resolveLink: (l) => {
const value = l as { label?: string; page?: { relationTo?: string; slug?: string; value?: { slug?: string } } } | null
const slug = value?.page?.slug ?? value?.page?.value?.slug
return slug ? { appearance: (l as { appearance?: string }).appearance, href: `/pl/${slug}`, internal: true, label: value?.label ?? '', newTab: false, targetProps: {} } : null
},
}
const header = { eyebrow: 'Eyebrow', heading: 'Section heading', intro: 'Intro text' }
/** Sample data per block — what an editor would fill in. */
const SAMPLES: Record<string, Record<string, unknown>> = {
contact: { content: null, form: { id: 'f1', confirmationType: 'message', fields: [{ name: 'name', blockType: 'text', label: 'Name', required: true }], submitButtonLabel: 'Send', title: 'Contact form' }, variant: 'formOnly' },
cta: { links, media: image(), variant: 'band' },
entryList: { entryCollection: 'posts', limit: 3, links, mode: 'latest', variant: 'cards' },
faq: { items: [{ id: 'q1', answer: 'Yes, we do.', question: 'Do you ship?' }], links, variant: 'single' },
featureGrid: { columns: 'three', items: [{ id: 'i1', heading: 'Fast', link: { type: 'internal', page: { slug: 'fast' } }, media: image(), text: 'Quick delivery' }], links, variant: 'cards' },
gallery: { columns: 'three', items: [{ id: 'g1', caption: 'Kitchen', media: image('Kitchen') }, { id: 'g2', media: image('Hall') }], variant: 'grid' },
hero: { links, media: image('Hero image'), variant: 'split' },
logos: { items: [{ id: 'o1', heading: 'Acme', media: image('') }], variant: 'row' },
pricing: { highlightLabel: 'Most popular', items: [{ id: 'p1', features: [{ id: 'x', text: 'Support' }], heading: 'Basic', highlighted: true, link: link('Choose'), period: '/ month', price: '$49' }], note: 'Prices without VAT.' },
richText: { content: { root: { type: 'root', children: [{ type: 'heading', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Data controller', version: 1 }], direction: 'ltr', format: '', indent: 0, tag: 'h2', version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 } }, tableOfContents: { label: 'Contents', show: true }, variant: 'narrow' },
stats: { items: [{ id: 's1', heading: 'Projects', value: '120+' }], variant: 'row' },
steps: { items: [{ id: 't1', heading: 'Call us', text: 'We listen.' }], links, variant: 'numbered' },
team: { items: [{ id: 'm1', heading: 'Anna Nowak', media: image('Anna'), text: 'CEO' }], variant: 'grid' },
testimonials: { items: [{ id: 'r1', heading: 'Jan', quote: 'Great work.', rating: 5, text: 'Client' }], variant: 'grid' },
textMedia: { content: null, links, media: image(), variant: 'mediaLeft' },
}
const sendForm = vi.fn(async () => ({ ok: true }) as never)
const registry = (options: BlockRegistryOptions = {}) => createBlockRegistry(content, { sendForm, ...options })
const block = (slug: string, data: Record<string, unknown> = SAMPLES[slug], extra: Record<string, unknown> = {}) => {
const Component = registry()[slug]
return h(Component, { id: 'b1', blockType: slug, header, isFirst: false, locale: 'en', settings: { anchor: 'here', background: 'muted' }, ...data, ...extra })
}
describe('createBlockRegistry', () => {
test('a component for every library block, plus the project’s own', () => {
const own = () => null
const map = createBlockRegistry(content, { extra: { timeline: own }, slugs: { testimonials: 'reviews' } })
expect(Object.keys(map).sort()).toEqual([...Object.keys(LIBRARY_BLOCK_COMPONENTS).filter((s) => s !== 'testimonials'), 'reviews', 'timeline'].sort())
expect(Object.keys(createBlockRegistry(content, { only: ['hero', 'faq'] }))).toEqual(['hero', 'faq'])
})
test('a swapped component gets the same props', async () => {
const Own = (p: { blockType: string; locale: string; ui: unknown }) => h('p', null, `${p.blockType} ${p.locale} ${typeof p.ui}`)
const map = createBlockRegistry(content, { components: { faq: Own as never } })
expect(await render(h(map.faq, { blockType: 'faq', locale: 'pl' }))).toContain('faq pl object')
})
})
describe.each(Object.keys(SAMPLES))('%s block', (slug) => {
test('renders one labelled section with its anchor and token classes', async () => {
const html = await render(block(slug))
expect(html).toContain(`data-ipal-block="${slug}"`)
expect(html).toContain('id="here"')
expect(html).toMatch(new RegExp(`aria-labelledby="${slug}-b1-heading"`))
expect(html).toContain(`id="${slug}-b1-heading"`)
expect(html).toContain('<h2')
expect(html).not.toContain('<h1')
expect(html).not.toMatch(/class="[^"]*#[0-9a-f]{3}/i)
})
test('the first section of the page has the only h1', async () => {
const html = await render(block(slug, SAMPLES[slug], { isFirst: true }))
expect(html.match(/<h1/g)).toHaveLength(1)
})
})
describe('empty blocks render nothing', () => {
test.each(['faq', 'featureGrid', 'gallery', 'logos', 'pricing', 'stats', 'steps', 'team', 'testimonials', 'richText'])('%s without items', async (slug) => {
expect(await render(block(slug, { content: null, items: [] }))).toBe('<div></div>')
})
test('cta without heading and buttons', async () => {
expect(await render(block('cta', {}, { header: null }))).toBe('<div></div>')
})
})
describe('block details', () => {
test('section backgrounds: token classes and data-surface for the token re-map', async () => {
const inverted = await render(block('faq', SAMPLES.faq, { settings: { background: 'inverted' } }))
expect(inverted).toMatch(/class="py-section bg-inverse text-on-inverse"/)
expect(inverted).toContain('data-surface="inverse"')
const own = createBlockRegistry(content, { backgrounds: { brand: 'bg-primary text-on-primary' } })
const html = await render(h(own.faq, { id: 'b1', blockType: 'faq', locale: 'en', ...SAMPLES.faq, settings: { background: 'brand' } }))
expect(html).toContain('bg-primary text-on-primary')
})
test('hero: the LCP image loads eagerly; next/image is used when passed', async () => {
const plain = await render(block('hero', SAMPLES.hero, { isFirst: true }))
expect(plain).toMatch(/<img[^>]*fetchPriority="high"[^>]*loading="eager"|<img[^>]*loading="eager"/)
const Image = (p: { alt: string }) => h('span', { 'data-next-image': p.alt })
const map = createBlockRegistry(content, { Image: Image as never })
expect(await render(h(map.hero, { blockType: 'hero', locale: 'en', ...SAMPLES.hero }))).toContain('data-next-image="Hero image"')
})
test('buttons go through the link resolver and the button classes; next/link for internal links', async () => {
const html = await render(block('cta'))
expect(html).toMatch(/<a class="[^"]*bg-primary text-on-primary[^"]*" href="\/pl\/kontakt">Contact us<\/a>/)
const Link = (p: { children: ReactNode; href: string }) => h('a', { 'data-next-link': p.href }, p.children)
const map = createBlockRegistry(content, { Link: Link as never })
expect(await render(h(map.cta, { blockType: 'cta', header, locale: 'en', ...SAMPLES.cta }))).toContain('data-next-link="/pl/kontakt"')
})
test('faq: native details/summary, the answer inside', async () => {
const html = await render(block('faq'))
expect(html).toMatch(/<details[^>]*><summary[^>]*><span>Do you ship\?<\/span>/)
})
test('gallery: every image opens in the lightbox, one group per gallery, captions as figcaption', async () => {
const html = await render(block('gallery'))
expect(html.match(/data-ipal="lightbox-trigger"/g)).toHaveLength(2)
expect(html).toContain('data-group="gallery-b1"')
expect(html).toContain('<figcaption class="mt-2 text-sm text-fg-muted">Kitchen</figcaption>')
const off = createBlockRegistry(content, { lightbox: false })
expect(await render(h(off.gallery, { blockType: 'gallery', locale: 'en', ...SAMPLES.gallery }))).not.toContain('lightbox-trigger')
})
test('feature card: the heading links and stretches over the card; a dead link stays text', async () => {
const html = await render(block('featureGrid'))
expect(html).toMatch(/<h3[^>]*><a class="after:absolute after:inset-0[^"]*" href="\/pl\/fast">Fast<\/a><\/h3>/)
const dead = await render(block('featureGrid', { items: [{ heading: 'Gone', link: { type: 'internal', page: null } }] }))
expect(dead).toMatch(/<h3[^>]*>Gone<\/h3>/)
})
test('feature icons come from the project’s icon map', async () => {
const Phone = (p: { className?: string }) => h('svg', { className: p.className, 'data-icon': 'phone' })
const map = createBlockRegistry(content, { icons: { phone: Phone } })
const html = await render(h(map.featureGrid, { blockType: 'featureGrid', items: [{ heading: 'Call', icon: 'phone' }], locale: 'en' }))
expect(html).toContain('data-icon="phone"')
})
test('logos: the name is the alt text when the image has none', async () => {
expect(await render(block('logos'))).toContain('alt="Acme"')
})
test('a link that wraps a logo but leads nowhere keeps the logo (an empty link group is stored as { type })', async () => {
const html = await render(block('logos', { items: [{ id: 'o1', heading: 'Acme', link: { type: 'internal' }, media: image('') }] }))
expect(html).toContain('alt="Acme"')
expect(html).not.toContain('<a')
const linked = await render(block('logos', { items: [{ id: 'o1', heading: 'Acme', link: { type: 'internal', page: { slug: 'acme' } }, media: image('') }] }))
expect(linked).toMatch(/<a[^>]*href="\/pl\/acme"[^>]*><img[^>]*alt="Acme"/)
})
test('testimonials: figure/blockquote/figcaption; the rating has a text equivalent per language', async () => {
const en = await render(block('testimonials'))
expect(en).toMatch(/<figure[^>]*>[\s\S]*<blockquote[^>]*>Great work\.<\/blockquote>[\s\S]*<figcaption/)
expect(en).toContain('<span class="sr-only">Rated 5 out of 5</span>')
expect(await render(block('testimonials', SAMPLES.testimonials, { locale: 'pl' }))).toContain('Ocena: 5 na 5')
const own = createBlockRegistry(content, { texts: { de: { rating: '{value} von 5' } } })
expect(await render(h(own.testimonials, { blockType: 'testimonials', locale: 'de', ...SAMPLES.testimonials }))).toContain('5 von 5')
})
test('testimonials from a collection, mapped by default or by the project', async () => {
const data = { entries: [{ id: 9, author: 'Ola', quote: 'Polecam.' }], source: 'collection' }
expect(await render(block('testimonials', data))).toContain('Polecam.')
const map = createBlockRegistry(content, { mapTestimonial: (d) => ({ heading: 'Mapped', quote: String(d.quote) }) })
expect(await render(h(map.testimonials, { blockType: 'testimonials', locale: 'en', ...data }))).toContain('Mapped')
})
test('pricing: the highlighted plan carries its label as text', async () => {
const html = await render(block('pricing'))
expect(html).toContain('Most popular')
expect(html).toContain('border-2 border-primary')
})
test('stats: a description list, no animation', async () => {
expect(await render(block('stats'))).toMatch(/<dl[^>]*>[\s\S]*<dt[^>]*>Projects[\s\S]*<dd[^>]*>120\+<\/dd>/)
})
test('steps: an ordered list with the step number for screen readers', async () => {
const html = await render(block('steps'))
expect(html).toContain('<ol')
expect(html).toContain('<span class="sr-only">Step 1: </span>')
})
test('rich text: headings get ids and a table of contents', async () => {
const html = await render(block('richText'))
expect(html).toContain('id="data-controller"')
expect(html).toContain('href="#data-controller"')
})
test('entry list: the latest entries, each title a link to the entry', async () => {
const html = await render(block('entryList'))
expect(content.getEntries).toHaveBeenCalledWith('posts', 'en', 1, 3)
expect(html).toContain('First post')
expect(html).toContain('<time')
const chosen = await render(block('entryList', { entries: [{ relationTo: 'posts', value: { id: 8, slug: 'chosen', title: 'Chosen one' } }], mode: 'selected' }))
expect(chosen).toContain('Chosen one')
})
test('contact: RenderForm with the form, nothing (and a warning) without sendForm', async () => {
const html = await render(block('contact'))
expect(html).toContain('data-ipal="form"')
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const bare = createBlockRegistry({ resolveLink: content.resolveLink })
expect(await render(h(bare.contact, { blockType: 'contact', locale: 'en', ...SAMPLES.contact }))).toBe('<div></div>')
expect(warn).toHaveBeenCalled()
warn.mockRestore()
})
test('noSnippet keeps a repeated section out of search snippets', async () => {
const map = createBlockRegistry(content, { noSnippet: ['cta'] })
expect(await render(h(map.cta, { blockType: 'cta', header, locale: 'en', ...SAMPLES.cta }))).toMatch(/^<div><div data-nosnippet="">/)
expect(await render(block('cta'))).not.toContain('data-nosnippet')
})
test('item headings follow the section: h3 under a section heading, h2 without one (no h1 → h3 jump)', async () => {
const under = await render(block('entryList'))
expect(under).toMatch(/<h3 class="font-heading text-h4[^"]*"><a /)
const bare = await render(block('entryList', SAMPLES.entryList, { header: null }))
expect(bare).not.toContain('<h3')
expect(bare).toMatch(/<h2 class="font-heading text-h4[^"]*"><a /)
// First section with a heading: section h1, items h2.
const first = await render(block('featureGrid', SAMPLES.featureGrid, { isFirst: true }))
expect(first).toContain('<h1')
expect(first).toMatch(/<h2 class="font-heading text-h4/)
for (const slug of ['featureGrid', 'pricing', 'steps', 'team']) {
expect(await render(block(slug, SAMPLES[slug], { header: null })), slug).not.toContain('<h3')
}
const fixed = createBlockRegistry(content, { itemHeadings: { entryList: 'h4' } })
expect(await render(h(fixed.entryList, { blockType: 'entryList', locale: 'en', ...SAMPLES.entryList }))).toContain('<h4')
})
test('the first image of the block that leads the page loads first (LCP); one per block, can be turned off', async () => {
const eager = /loading="eager"/g
// An entry list under a page header without a picture: firstImage from createPageRoute.
const lead = await render(block('entryList', SAMPLES.entryList, { firstImage: true, header: null }))
expect(lead.match(eager)).toHaveLength(1)
expect(lead).toContain('fetchPriority="high"')
expect(await render(block('entryList'))).not.toMatch(eager)
for (const slug of ['featureGrid', 'gallery', 'team', 'textMedia']) {
expect((await render(block(slug, SAMPLES[slug], { firstImage: true }))).match(eager), slug).toHaveLength(1)
}
const off = createBlockRegistry(content, { priorityImage: false })
expect(await render(h(off.hero, { blockType: 'hero', isFirst: true, locale: 'en', ...SAMPLES.hero }))).not.toMatch(eager)
})
test('classNames replace one part’s classes', async () => {
const map = createBlockRegistry(content, { classNames: { faq: { item: 'my-item' } } })
const html = await render(h(map.faq, { blockType: 'faq', locale: 'en', ...SAMPLES.faq }))
expect(html).toContain('<details class="my-item">')
})
test('ui: a swapped primitive is used by every block', async () => {
const Media = () => h('i', { 'data-own-media': true })
const map = createBlockRegistry(content, { ui: { Media } })
expect(await render(h(map.textMedia, { blockType: 'textMedia', locale: 'en', ...SAMPLES.textMedia }))).toContain('data-own-media')
})
})