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 { 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> = { 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 = SAMPLES[slug], extra: Record = {}) => { 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(' { const html = await render(block(slug, SAMPLES[slug], { isFirst: true })) expect(html.match(/

{ 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('
') }) test('cta without heading and buttons', async () => { expect(await render(block('cta', {}, { header: null }))).toBe('
') }) }) 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(/]*fetchPriority="high"[^>]*loading="eager"|]*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(/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(/]*>]*>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('
Kitchen
') 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(/]*>
Fast<\/a><\/h3>/) const dead = await render(block('featureGrid', { items: [{ heading: 'Gone', link: { type: 'internal', page: null } }] })) expect(dead).toMatch(/]*>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(']*href="\/pl\/acme"[^>]*>]*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(/]*>[\s\S]*]*>Great work\.<\/blockquote>[\s\S]*
Rated 5 out of 5') 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(/]*>[\s\S]*]*>Projects[\s\S]*]*>120\+<\/dd>/) }) test('steps: an ordered list with the step number for screen readers', async () => { const html = await render(block('steps')) expect(html).toContain('Step 1: ') }) 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(' { 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('
') 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(/^