Files
ipal-kit/test/blockLibrary.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 29ede3ad4b Block library: fixes from the first visual test on the reference site
- CMSLink: a link that wraps content (a logo, a card) and leads nowhere keeps the
  content — an empty link group ({ type: 'internal' }) no longer hides logos
- entryList: field `collection` → `entryCollection` (Mongoose reserves
  `collection`; unreleased, snapshot updated) + a test against reserved names
- post template starts with a page hero holding the title (the page's h1)
- legal and cookie policy templates set noindex: true (AGENT.md §0c)
- hero background: a full bg-overlay scrim under the text
- MediaValue accepts any object (generated Media types fit without a cast)
- contact: Turnstile renders dark in an inverted section

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:03:39 +01:00

325 lines
17 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 { 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('field names', () => {
// Mongoose (MongoDB adapter — every live site) reserves these path names and warns on every start.
const MONGOOSE_RESERVED = ['collection', 'db', 'emit', 'errors', 'get', 'init', 'isModified', 'isNew', 'listeners', 'modelName', 'on', 'once', 'populated', 'prototype', 'remove', 'removeListener', 'save', 'schema', 'set', 'toObject', 'validate']
test('no block uses a name Mongoose reserves', () => {
const offending = blockLibraryManifest.blocks.flatMap((b) =>
b.fields.filter((f) => f.path.split(/\[\]\.|\./).some((seg) => MONGOOSE_RESERVED.includes(seg))).map((f) => `${b.slug}.${f.path}`),
)
expect(offending).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', 'columns', 'entryCollection', '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('post: the title is the page header (the only h1); legal pages are noindex', () => {
const page = pageTemplates.post({ title: { en: 'Hello', pl: 'Cześć' } })
expect(page.layout[0]).toMatchObject({ blockType: 'hero', header: { heading: { en: 'Hello', pl: 'Cześć' } }, variant: 'page' })
expect(pageTemplates.legal('privacyPolicy').noindex).toBe(true)
expect(pageTemplates.cookiePolicy().noindex).toBe(true)
expect(pageTemplates.home().noindex).toBeUndefined()
})
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('styling: every token utility the blocks use exists in the preset', () => {
test('colours, radii, spacing and widths come from tailwind.css', () => {
const preset = readFileSync(path.join(root, 'src/styles/tailwind.css'), 'utf8')
const theme = (ns: string) => new Set([...preset.matchAll(new RegExp(`--${ns}-([\\w-]+?)(?:--[\\w-]+)?:`, 'g'))].map((m) => m[1]))
const colors = theme('color')
const radii = new Set(['full', 'none', ...theme('radius')])
const spacing = theme('spacing')
const widths = new Set(['full', 'md', 'none', ...theme('container')])
const text = new Set(['center', 'left', 'right', ...theme('text')])
const problems: string[] = []
const classes = libraryFiles().filter((f) => !f.endsWith('thumbnails.ts')).flatMap((file) =>
[...readFileSync(file, 'utf8').matchAll(/'([^'\n]*)'|"([^"\n]*)"/g)].flatMap((m) => (m[1] ?? m[2] ?? '').split(/\s+/).map((c) => [path.relative(root, file), c] as const)),
)
for (const [file, raw] of classes) {
const c = raw.replace(/^(?:[a-z0-9@-]+:)+/, '') // drop variants: hover:, md:, group-open:, after:
let m: null | RegExpMatchArray
if ((m = c.match(/^(?:bg|text|border|from|to|outline|ring|before:text)-([a-z][\w-]*)$/)) && !/^(?:\d|[blrtxy](?:-|$)|offset|linear|transparent|inherit|current)/.test(m[1])) {
const name = m[1]
const known = colors.has(name) || (c.startsWith('text-') && text.has(name)) || (c.startsWith('border-') && /^\d+$/.test(name))
if (!known) {problems.push(`${file}: ${raw} (no --color-${name})`)}
} else if ((m = c.match(/^rounded-([a-z][\w-]*)$/)) && !radii.has(m[1])) {problems.push(`${file}: ${raw}`)}
else if ((m = c.match(/^(?:p[xytblr]?|m[xytblr]?|gap(?:-[xy])?|space-y)-([a-z][a-z-]*)$/)) && !['auto', 'px'].includes(m[1]) && !spacing.has(m[1])) {problems.push(`${file}: ${raw}`)}
else if ((m = c.match(/^max-w-([a-z][\w-]*)$/)) && !widths.has(m[1])) {problems.push(`${file}: ${raw}`)}
}
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)
})
})