- @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]>
278 lines
13 KiB
TypeScript
278 lines
13 KiB
TypeScript
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)
|
||
})
|
||
})
|