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
+12
View File
@@ -2,6 +2,7 @@ import type { CollectionConfig, Config, Field, GlobalConfig } from 'payload'
import { describe, expect, test } from 'vitest'
import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js'
import { applyAdminI18n } from '../src/modules/admin-i18n/apply.js'
import { adminTexts } from '../src/modules/admin-i18n/index.js'
import { ipalKit } from '../src/plugin.js'
@@ -195,6 +196,17 @@ describe('admin wording (docs/dev/admin-ux.md)', () => {
expect(problems).toEqual([])
})
test('block library: every block, en + pl, within limits', () => {
const problems: Problem[] = []
const blocks = libraryBlocks({
...Object.fromEntries(LIBRARY_BLOCK_SLUGS.map((slug) => [slug, true])),
featureGrid: { icons: ['phone'] },
testimonials: { collection: 'testimonials' },
})
walk([{ name: 'layout', type: 'blocks', blocks, label: { en: 'Sections', pl: 'Sekcje' } } as Field], 'pages', problems)
expect(problems).toEqual([])
})
test('component texts: same keys in en and pl, none empty, no developer words', () => {
const en = adminTexts.en as Record<string, string>
const pl = adminTexts.pl as Record<string, string>
File diff suppressed because it is too large Load Diff
+277
View File
@@ -0,0 +1,277 @@
import type { Block, Field } from 'payload'
import { execFileSync } from 'node:child_process'
import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterAll, describe, expect, test, vi } from 'vitest'
import {
blockLibraryManifest,
buildFaqBlock,
buildFeatureGridBlock,
buildTestimonialsBlock,
faqItemsFromLayout,
fieldPaths,
isNamed,
LIBRARY_BLOCK_SLUGS,
libraryBlocks,
libraryBlockSlugs,
replaceField,
} from '../src/exports/blocks.js'
import { pageTemplates, systemPageRefs } from '../src/exports/templates.js'
const root = path.resolve(import.meta.dirname, '..')
const names = (b: Block) => b.fields.map((f) => ('name' in f ? f.name : f.type))
const find = (fields: Field[], name: string) => fields.find((f) => isNamed(f, name)) as Record<string, unknown> | undefined
const hasLocalized = (v: unknown): boolean =>
Array.isArray(v) ? v.some(hasLocalized) : !!v && typeof v === 'object' && ((v as { localized?: unknown }).localized === true || Object.values(v).some(hasLocalized))
describe('libraryBlocks — opt in per block', () => {
test('nothing is on by default', () => {
expect(libraryBlocks({})).toEqual([])
})
test('true = the block with defaults, in picker order', () => {
const blocks = libraryBlocks({ faq: true, hero: true })
expect(blocks.map((b) => b.slug)).toEqual(['hero', 'faq'])
expect(names(blocks[1])).toEqual(['header', 'items', 'links', 'variant', 'settings'])
expect(blocks[1].custom).toMatchObject({ ipalLibrary: 'faq' })
})
test('every one of the 15 blocks builds, with a unique slug and interface name', () => {
const all = libraryBlocks(Object.fromEntries(LIBRARY_BLOCK_SLUGS.map((s) => [s, true])))
expect(all).toHaveLength(15)
expect(new Set(all.map((b) => b.interfaceName)).size).toBe(15)
})
test('slug, interface name, labels: the project wins', () => {
const [block] = libraryBlocks({ testimonials: { slug: 'reviews', interfaceName: 'ReviewsBlock', labels: { plural: 'Reviews', singular: 'Review' } } })
expect(block).toMatchObject({ slug: 'reviews', interfaceName: 'ReviewsBlock', labels: { singular: 'Review' } })
expect(block.custom).toMatchObject({ ipalLibrary: 'testimonials' })
expect(libraryBlockSlugs({ faq: true, testimonials: { slug: 'reviews' } })).toEqual({ faq: 'faq', testimonials: 'reviews' })
})
test('fields: add, change and drop through a function', () => {
const extra: Field = { name: 'note', type: 'text' }
const block = buildFaqBlock({
fields: (defaults) => [...replaceField(defaults, 'items', { maxRows: 5 } as Partial<Field>), extra].filter((f) => !isNamed(f, 'links')),
})
expect(names(block)).toEqual(['header', 'items', 'variant', 'settings', 'note'])
expect(find(block.fields, 'items')?.maxRows).toBe(5)
})
test('variants: a subset, the project’s own, or none', () => {
const sub = buildFaqBlock({ variants: ['twoColumn'] })
expect((find(sub.fields, 'variant')?.options as { value: string }[]).map((o) => o.value)).toEqual(['twoColumn'])
const own = buildFaqBlock({ variants: ['single', { label: { en: 'Tabs', pl: 'Zakładki' }, value: 'tabs' }] })
expect((find(own.fields, 'variant')?.options as { value: string }[]).map((o) => o.value)).toEqual(['single', 'tabs'])
expect(names(buildFaqBlock({ variants: false }))).not.toContain('variant')
expect(() => buildFaqBlock({ variants: ['nope'] })).toThrow(/unknown variant/)
})
test('header, links and settings options reach the shared builders', () => {
const block = buildFaqBlock({ header: false, links: false, settings: { anchor: false, backgrounds: [{ label: 'Brand', value: 'brand' }] } })
expect(names(block)).toEqual(['items', 'variant', 'settings'])
const settings = find(block.fields, 'settings') as { fields: Field[] }
expect(settings.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['background'])
})
test('localization: "layout" drops every inner localized flag', () => {
expect(hasLocalized(buildFeatureGridBlock().fields)).toBe(true)
expect(hasLocalized(buildFeatureGridBlock({ localization: 'layout' }).fields)).toBe(false)
const [shared] = libraryBlocks({ faq: true }, { localization: 'layout' })
expect(hasLocalized(shared.fields)).toBe(false)
})
test('a function setting takes the finished block over', () => {
const [block] = libraryBlocks({ cta: (b) => ({ ...b, slug: 'banner' }) })
expect(block.slug).toBe('banner')
})
test('opt-in thumbnail: an inline SVG, or the project’s URL', () => {
expect(buildFaqBlock({ thumbnail: true }).imageURL).toMatch(/^data:image\/svg\+xml,/)
expect(buildFaqBlock({ thumbnail: '/thumbs/faq.png' }).imageURL).toBe('/thumbs/faq.png')
expect(buildFaqBlock().imageURL).toBeUndefined()
})
test('feature icons and a testimonials collection are opt-in fields', () => {
expect(fieldPaths(buildFeatureGridBlock().fields).map((f) => f.path)).not.toContain('items[].icon')
const icons = fieldPaths(buildFeatureGridBlock({ icons: ['phone', 'mail'] }).fields)
expect(icons.find((f) => f.path === 'items[].icon')?.options).toEqual(['phone', 'mail'])
expect(names(buildTestimonialsBlock())).not.toContain('entries')
expect(names(buildTestimonialsBlock({ collection: 'testimonials' }))).toEqual(expect.arrayContaining(['source', 'items', 'entries']))
})
})
describe('faqItemsFromLayout', () => {
test('every FAQ block’s filled questions, for FAQ rich results', () => {
const doc = {
layout: [
{ blockType: 'hero' },
{ blockType: 'faq', items: [{ answer: ' Yes ', question: 'Open?' }, { answer: '', question: 'Empty' }] },
{ blockType: 'questions', items: [{ answer: 'B', question: 'Renamed?' }] },
],
}
expect(faqItemsFromLayout(doc)).toEqual([{ answer: 'Yes', question: 'Open?' }])
expect(faqItemsFromLayout(doc, { slugs: ['questions'] })).toEqual([{ answer: 'B', question: 'Renamed?' }])
expect(faqItemsFromLayout({})).toEqual([])
})
})
describe('blockLibraryManifest', () => {
test('lists every block with its variants and fields, the primitives, builders and templates', () => {
expect(blockLibraryManifest.blocks.map((b) => b.slug)).toEqual(LIBRARY_BLOCK_SLUGS)
const faq = blockLibraryManifest.blocks.find((b) => b.slug === 'faq')!
expect(faq).toMatchObject({ interfaceName: 'FaqBlock', phase: 1, variants: ['single', 'twoColumn'] })
expect(faq.fields.map((f) => f.path)).toEqual(expect.arrayContaining(['header.heading', 'items[].question', 'items[].answer', 'links[].link.type', 'settings.anchor']))
expect(blockLibraryManifest.blocks.filter((b) => b.variants.length === 0).map((b) => b.slug)).toEqual(['pricing'])
expect(blockLibraryManifest.primitives).toEqual(['Section', 'SectionHeader', 'Media', 'CMSLink', 'Button', 'Container', 'Card'])
expect(blockLibraryManifest.fieldBuilders).toContain('buildItemsField')
expect([...blockLibraryManifest.templates].sort()).toEqual(Object.keys(pageTemplates).sort())
})
})
describe('page templates', () => {
const form = { $form: 'Contact form' }
const all = () => [
pageTemplates.home(),
pageTemplates.about(),
pageTemplates.services(),
pageTemplates.service({ form }),
pageTemplates.contact({ form }),
pageTemplates.blogIndex(),
pageTemplates.post(),
pageTemplates.legal('privacyPolicy'),
pageTemplates.legal('termsOfService'),
pageTemplates.cookiePolicy(),
pageTemplates.notFound(),
]
test('every template: title and slug in en + pl, only library blocks', () => {
for (const page of all()) {
expect(page.title).toEqual({ en: expect.any(String), pl: expect.any(String) })
expect(page.slug).toEqual({ en: expect.any(String), pl: expect.any(String) })
for (const block of page.layout) {expect(LIBRARY_BLOCK_SLUGS).toContain(block.blockType)}
}
})
test('every visible text is written in both languages', () => {
const problems: string[] = []
const walk = (v: unknown, where: string) => {
if (Array.isArray(v)) {return v.forEach((x, i) => walk(x, `${where}[${i}]`))}
if (!v || typeof v !== 'object') {return}
const o = v as Record<string, unknown>
if ('en' in o || 'pl' in o) {
if (!o.en || !o.pl) {problems.push(where)}
return
}
for (const [k, x] of Object.entries(o)) {
if (['$form', '$page', 'appearance', 'blockType', 'collection', 'columns', 'limit', 'mode', 'show', 'type', 'variant'].includes(k)) {continue}
if (typeof x === 'string') {problems.push(`${where}.${k} = "${x}"`)}
else {walk(x, `${where}.${k}`)}
}
}
all().forEach((p, i) => walk(p.layout, `page${i}`))
expect(problems).toEqual([])
})
test('buttons link to pages by their slug in the default locale', () => {
const json = JSON.stringify(pageTemplates.home())
expect(json).toContain('{"$page":"kontakt"}')
expect(JSON.stringify(pageTemplates.home({ defaultLocale: 'en' }))).toContain('{"$page":"contact"}')
expect(JSON.stringify(pageTemplates.home({ linkTo: { contact: 'napisz' } }))).toContain('{"$page":"napisz"}')
})
test('options: overrides, layout, renamed and missing blocks', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const page = pageTemplates.home({
slug: { en: 'welcome', pl: 'witaj' },
blocks: { cta: 'cta', faq: 'faq', featureGrid: 'featureGrid', hero: 'hero', testimonials: 'reviews', textMedia: 'textMedia' },
layout: (blocks) => blocks.filter((b) => b.blockType !== 'faq'),
overrides: { hero: { variant: 'centered' } },
})
expect(page.slug).toEqual({ en: 'welcome', pl: 'witaj' })
expect(page.layout.map((b) => b.blockType)).toEqual(['hero', 'featureGrid', 'textMedia', 'reviews', 'cta'])
expect(page.layout[0]).toMatchObject({ variant: 'centered' })
expect(warn.mock.calls[0][0]).toMatch(/left out blocks that are off: logos, stats/)
warn.mockRestore()
})
test('systemPageRefs: Site settings → System pages as $page links', () => {
expect(systemPageRefs({ homepage: 'start', privacyPolicy: 'polityka-prywatnosci' })).toEqual({
homepage: { $page: 'start' },
privacyPolicy: { $page: 'polityka-prywatnosci' },
})
})
})
/** Every class string in the library's source. */
function libraryFiles(dir = path.join(root, 'src/modules/block-library')): string[] {
return readdirSync(dir).flatMap((name) => {
const p = path.join(dir, name)
return statSync(p).isDirectory() ? libraryFiles(p) : /\.tsx?$/.test(name) ? [p] : []
})
}
describe('styling: design tokens only', () => {
test('no hex colours, dark: variants, arbitrary colours or clamp() in the components', () => {
const problems: string[] = []
for (const file of libraryFiles().filter((f) => !f.endsWith('thumbnails.ts'))) {
const src = readFileSync(file, 'utf8')
for (const m of src.matchAll(/'([^'\n]*)'|"([^"\n]*)"|`([^`\n]*)`/g)) {
const s = m[1] ?? m[2] ?? m[3] ?? ''
if (/(?:^|\s)dark:|#[0-9a-f]{3,8}\b|(?:bg|text|border|from|to|ring|outline)-\[#|clamp\(|(?:bg|text|border)-(?:white|black|gray|slate|zinc|neutral|red|blue|green)-?\d*/i.test(s) && /\s|-/.test(s)) {
problems.push(`${path.relative(root, file)}: ${s}`)
}
}
}
expect(problems).toEqual([])
})
})
describe('ipal-blocks eject', () => {
const tmp = mkdtempSync(path.join(os.tmpdir(), 'ipal-eject-'))
afterAll(() => rmSync(tmp, { force: true, recursive: true }))
/** Names an entry file exports. */
const exportsOf = (file: string) => {
const src = readFileSync(path.join(root, file), 'utf8')
return new Set([...src.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)].flatMap((m) => m[1].split(',').map((s) => s.trim().replace(/^type\s+/, '').split(/\s+as\s+/).pop()!)).filter(Boolean))
}
const ENTRIES: Record<string, Set<string>> = {
'@intecion/ipal-kit': exportsOf('src/index.ts'),
'@intecion/ipal-kit/blocks': exportsOf('src/exports/blocks.ts'),
'@intecion/ipal-kit/blocks/rsc': exportsOf('src/exports/blocks-rsc.ts'),
'@intecion/ipal-kit/client': exportsOf('src/exports/client.ts'),
'@intecion/ipal-kit/rsc': exportsOf('src/exports/rsc.ts'),
}
test('every block ejects with imports that exist in the package entries', () => {
const problems: string[] = []
for (const slug of LIBRARY_BLOCK_SLUGS) {
execFileSync('node', [path.join(root, 'bin/ipal-blocks.mjs'), 'eject', slug, '--dest', tmp], { cwd: tmp, stdio: 'pipe' })
const dir = path.join(tmp, slug[0].toUpperCase() + slug.slice(1))
for (const file of readdirSync(dir)) {
const src = readFileSync(path.join(dir, file), 'utf8')
if (/from '\.\.?\//.test(src)) {problems.push(`${slug}/${file}: relative import left`)}
for (const m of src.matchAll(/import (?:type )?\{([^}]*)\} from '(@intecion\/ipal-kit[^']*)'/g)) {
const entry = ENTRIES[m[2]]
if (!entry) {
problems.push(`${slug}/${file}: unknown entry ${m[2]}`)
continue
}
for (const name of m[1].split(',').map((s) => s.trim()).filter(Boolean)) {
if (!entry.has(name)) {problems.push(`${slug}/${file}: ${name} not exported from ${m[2]}`)}
}
}
}
}
expect(problems).toEqual([])
})
test('an existing file is never overwritten', () => {
const out = execFileSync('node', [path.join(root, 'bin/ipal-blocks.mjs'), 'eject', 'faq', '--dest', tmp], { cwd: tmp, encoding: 'utf8', stdio: 'pipe' })
expect(out).not.toMatch(/^write /m)
})
})
+134
View File
@@ -0,0 +1,134 @@
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js'
import { createSeeder } from '../src/exports/seed.js'
import { pageTemplates, systemPageRefs } from '../src/exports/templates.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
/**
* The library in a real Payload: every block in a pages `layout`, every page template
* seeded through createSeeder in both locales (forms by `$form`, pages by `$page`).
*/
describe('block library in Payload', () => {
let payload: Payload
const lines: string[] = []
beforeAll(async () => {
vi.stubEnv('DATABASE_URI', 'file::memory:')
const config = buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{
name: 'layout',
type: 'blocks',
blocks: libraryBlocks({ ...Object.fromEntries(LIBRARY_BLOCK_SLUGS.map((s) => [s, true])), testimonials: { collection: 'testimonials' } }),
},
],
},
{
slug: 'posts',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', localized: true },
],
},
{ slug: 'testimonials', fields: [{ name: 'quote', type: 'textarea' }, { name: 'heading', type: 'text' }] },
{ slug: 'media', fields: [{ name: 'alt', type: 'text' }], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-blocks') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] },
plugins: [
ipalKit({
content: { collections: [{ slug: 'posts' }] },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] },
pages: { slug: 'pages' },
twoFactor: false,
} as never),
],
secret: 'block-library-test',
telemetry: false,
})
payload = await getPayload({ config })
}, 60_000)
afterAll(async () => {
vi.unstubAllEnvs()
await payload?.destroy()
})
test('every template seeds into the schema, with forms and pages linked', async () => {
const seed = createSeeder(payload, { dryRun: false, log: (l) => lines.push(l), update: false })
const formResult = await seed.upsertBy('forms', { title: 'Contact form' }, {
confirmationMessage: { root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Thanks', version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 } },
confirmationType: 'message',
fields: [{ name: 'name', blockType: 'text', label: 'Name', required: true }],
title: 'Contact form',
})
expect(formResult).toMatchObject({ status: 'create' })
const form = { $form: 'Contact form' }
const results = await seed.upsertBySlug('pages', [
pageTemplates.home(),
pageTemplates.about(),
pageTemplates.services(),
pageTemplates.service({ form }),
pageTemplates.contact({ form }),
pageTemplates.blogIndex(),
pageTemplates.legal('privacyPolicy'),
pageTemplates.legal('termsOfService'),
pageTemplates.cookiePolicy(),
pageTemplates.notFound(),
])
expect(results.filter((r) => r.status === 'error')).toEqual([])
expect(results.every((r) => r.status === 'create')).toBe(true)
await seed.fillGlobal('site-settings', { siteName: 'Test site', ...systemPageRefs({ homepage: 'start', notFound: 'nie-znaleziono', privacyPolicy: 'polityka-prywatnosci' }) })
expect(lines.filter((l) => /error/.test(l))).toEqual([])
expect(seed.summary().errors).toBe(0)
const { docs } = await payload.find({ collection: 'pages', depth: 1, locale: 'en', where: { slug: { equals: 'contact' } } })
const contact = docs[0] as unknown as { layout: { blockType: string; form?: { title?: string } }[] }
expect(contact.layout.map((b) => b.blockType)).toEqual(['hero', 'contact', 'faq'])
expect(contact.layout[1].form?.title).toBe('Contact form')
const home = await payload.find({ collection: 'pages', depth: 0, locale: 'pl', where: { slug: { equals: 'start' } } })
const hero = (home.docs[0] as unknown as { layout: { blockType: string; links: { link: { page: unknown } }[] }[] }).layout[0]
const contactId = (await payload.find({ collection: 'pages', depth: 0, where: { slug: { equals: 'kontakt' } } })).docs[0].id
expect(hero.links[0].link.page).toBe(contactId)
const settings = (await payload.findGlobal({ slug: 'site-settings' as never, depth: 0 })) as { homepage?: unknown }
expect(settings.homepage).toBe(home.docs[0].id)
})
test('a template for a block that is off leaves it out instead of failing', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const seed = createSeeder(payload, { dryRun: false, log: () => {}, update: false })
const page = pageTemplates.about({ slug: { en: 'about-short', pl: 'o-nas-krotko' }, blocks: { cta: 'cta', hero: 'hero' } })
const [result] = await seed.upsertBySlug('pages', [page])
expect(result.status).toBe('create')
expect(warn).toHaveBeenCalled()
warn.mockRestore()
})
test('$form that does not exist is an error, not a silent empty relation', async () => {
const seed = createSeeder(payload, { dryRun: false, log: () => {}, update: false })
const [result] = await seed.upsertBySlug('pages', [pageTemplates.contact({ slug: { en: 'contact-2', pl: 'kontakt-2' }, form: { $form: 'Missing form' } })])
expect(result.status).toBe('error')
expect(result.note).toMatch(/\$form "Missing form" not found/)
})
})
+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')
})
})
+66
View File
@@ -0,0 +1,66 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, test } from 'vitest'
import type { ManifestField } from '../src/exports/blocks.js'
import { buildBlockLibraryManifest } from '../src/exports/blocks.js'
/**
* Versioning guard for the block library (docs/block-library.md "Versioning"): stored content
* must survive every minor release. Compared with test/block-library.schema.json:
* - a field path, slug or interface name never disappears or changes type;
* - a select value never disappears; a relation target never disappears;
* - an existing field never becomes required, and a new field is never required.
* Adding is allowed: run `UPDATE_BLOCK_SCHEMA=1 pnpm vitest run test/blockLibrarySchema.test.ts`
* and commit the snapshot with the change.
*/
type Snapshot = Record<string, { fields: Record<string, Omit<ManifestField, 'path'>>; interfaceName: string }>
const file = path.join(import.meta.dirname, 'block-library.schema.json')
const current = (): Snapshot =>
Object.fromEntries(
buildBlockLibraryManifest().blocks.map((b) => [
b.slug,
{ fields: Object.fromEntries(b.fields.map(({ path: p, ...rest }) => [p, rest])), interfaceName: b.interfaceName },
]),
)
describe('block library schema (versioning)', () => {
test('no stored field, value or name is removed, renamed or made required', () => {
const now = current()
const before = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Snapshot) : now
const problems: string[] = []
for (const [slug, block] of Object.entries(before)) {
const after = now[slug]
if (!after) {
problems.push(`${slug}: block removed`)
continue
}
if (after.interfaceName !== block.interfaceName) {problems.push(`${slug}: interface name ${block.interfaceName} → ${after.interfaceName}`)}
for (const [p, field] of Object.entries(block.fields)) {
const next = after.fields[p]
if (!next) {
problems.push(`${slug}.${p}: removed or renamed`)
continue
}
if (next.type !== field.type) {problems.push(`${slug}.${p}: type ${field.type} → ${next.type}`)}
if (next.required && !field.required) {problems.push(`${slug}.${p}: became required`)}
for (const o of field.options ?? []) {
if (!next.options?.includes(o)) {problems.push(`${slug}.${p}: value "${o}" removed`)}
}
}
for (const [p, field] of Object.entries(after.fields)) {
if (!block.fields[p] && field.required) {problems.push(`${slug}.${p}: a new field must not be required`)}
}
}
expect(problems).toEqual([])
// Only a safe change updates the snapshot.
if (process.env.UPDATE_BLOCK_SCHEMA === '1' || !existsSync(file)) {writeFileSync(file, `${JSON.stringify(now, null, 2)}\n`)}
})
test('the snapshot is up to date (additions are committed with the change)', () => {
expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual(current())
})
})
+11 -1
View File
@@ -10,6 +10,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
@@ -54,7 +55,16 @@ const project = (): Omit<Config, 'plugins'> =>
({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text' },
{ name: 'slug', type: 'text', localized: true },
// Every library block — their select values become enum names too.
{ name: 'layout', type: 'blocks', blocks: libraryBlocks({ ...Object.fromEntries(LIBRARY_BLOCK_SLUGS.map((s) => [s, true])), featureGrid: { icons: ['phone', 'mail'] }, testimonials: { collection: 'posts' } }) },
],
versions: { drafts: true },
},
{ slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } },
{ slug: 'media', fields: [], upload: true },
],