Block library: 15 blocks, registry, primitives, templates, manifest, eject

- @intecion/ipal-kit/blocks: libraryBlocks() opt-in, one builder per block, field
  builders, option merging, blockLibraryManifest, faqItemsFromLayout
- @intecion/ipal-kit/blocks/rsc: createBlockRegistry, the block components and UI
  primitives (token utilities only; next/image and next/link passed in)
- @intecion/ipal-kit/templates: 10 page templates as createSeeder data
- createSeeder: { $form: title } references
- ipal-blocks eject <block>
- tests: options, rendering and a11y per block, Payload + seeding, GraphQL, admin
  wording, schema snapshot (versioning), eject imports
- shorter admin labels: link "New tab", table of contents "Show contents"

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-29 14:05:47 +01:00
co-authored by Claude Opus 5.5
parent 7918eaf6d4
commit 2d1cc0e77d
73 changed files with 5091 additions and 9 deletions
+251
View File
@@ -0,0 +1,251 @@
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', publishedAt: '2026-10-01T00:00:00.000Z', title: 'First 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: { collection: '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('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('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')
})
})