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
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env node
// ipal-blocks — the block library's command line.
// pnpm exec ipal-blocks list → the library blocks
// pnpm exec ipal-blocks eject faq → src/blocks/Faq/{config.ts,Component.tsx}
// pnpm exec ipal-blocks eject faq --dest src/blocks --dry-run
// Eject copies one block's source into the project, with its imports pointing at the
// package entries, so the project owns it: same slug and data shape, no migration.
// Then: use the ejected builder in Pages.layout instead of the library one, pass the ejected
// component as createBlockRegistry({ components: { faq: FaqBlock } }), record it in AGENTS.md.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
const [command, slug] = args
const dryRun = args.includes('--dry-run')
const destArg = args.indexOf('--dest')
const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] : 'src/blocks')
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const libRoot = join(pkgRoot, 'src/modules/block-library')
const blocksRoot = join(libRoot, 'blocks')
if (!command || command === '--help' || command === '-h') {
console.log('Usage: ipal-blocks list | ipal-blocks eject <block> [--dest src/blocks] [--dry-run]')
process.exit(0)
}
const slugs = existsSync(blocksRoot) ? readdirSync(blocksRoot).sort() : []
if (command === 'list') {
console.log(slugs.join('\n'))
process.exit(0)
}
if (command !== 'eject' || !slug) {
console.error('Usage: ipal-blocks eject <block>')
process.exit(1)
}
if (!slugs.includes(slug)) {
console.error(`Unknown block "${slug}". Blocks: ${slugs.join(', ')}`)
process.exit(1)
}
/**
* Where an import inside the library goes in a project, by the file it points at.
* Config files (no React) take the Payload-side entries; components take /rsc and /client.
*/
const ROOT = '@intecion/ipal-kit'
const BLOCKS = '@intecion/ipal-kit/blocks'
const RSC = '@intecion/ipal-kit/blocks/rsc'
function target(file, isComponent) {
const rel = relative(join(pkgRoot, 'src/modules'), file).replace(/\\/g, '/').replace(/\.js$/, '')
if (rel.startsWith('block-library/')) {
const inner = rel.slice('block-library/'.length)
if (/^(define|fields|options|shared|types|faq|library|manifest|thumbnails)$/.test(inner)) {return BLOCKS}
return RSC // context, data, texts, ui/*
}
if (rel === 'lightbox/LightboxProvider' || rel === 'richtext/TableOfContents') {return '@intecion/ipal-kit/client'}
if (rel === 'forms/RenderForm' || rel === 'richtext/RenderRichText') {return '@intecion/ipal-kit/rsc'}
if (rel === 'richtext/headings') {return isComponent ? '@intecion/ipal-kit/rsc' : ROOT}
return ROOT
}
/** Rewrites relative imports to package entries and merges imports of the same entry. */
function rewrite(source, file) {
const isComponent = file.endsWith('.tsx')
const merged = new Map()
const body = source.replace(/^import (type )?\{([^}]*)\} from '(\.[^']+)'\n/gm, (_, type, names, spec) => {
const entry = target(resolve(dirname(file), spec), isComponent)
const key = `${type ? 'type ' : ''}${entry}`
const set = merged.get(key) ?? new Set()
for (const n of names.split(',').map((s) => s.trim()).filter(Boolean)) {set.add(n)}
merged.set(key, set)
return ''
})
const lines = [...merged].map(([key, set]) => {
const [type, entry] = key.startsWith('type ') ? ['type ', key.slice(5)] : ['', key]
return `import ${type}{ ${[...set].sort().join(', ')} } from '${entry}'`
})
return body.replace(/^((?:import [^\n]*\n)*)/, (head) => `${head}${lines.join('\n')}\n`).replace(/\n{3,}/g, '\n\n')
}
const folder = slug[0].toUpperCase() + slug.slice(1)
const outDir = join(dest, folder)
const files = readdirSync(join(blocksRoot, slug)).filter((f) => /\.(ts|tsx)$/.test(f))
for (const name of files) {
const from = join(blocksRoot, slug, name)
const to = join(outDir, name)
if (existsSync(to)) {
console.error(`skip ${relative(process.cwd(), to)} (exists — delete it first to eject again)`)
continue
}
const out = `// Ejected from @intecion/ipal-kit (block library: ${slug}). The project owns this file now.\n${rewrite(readFileSync(from, 'utf8'), from)}`
console.log(`${dryRun ? 'would write' : 'write'} ${relative(process.cwd(), to)}`)
if (!dryRun) {
mkdirSync(outDir, { recursive: true })
writeFileSync(to, out)
}
}
console.log(`\nNext: Pages.layout → the ejected build${folder}Block; registry → components: { ${slug}: ${folder}Block }; AGENTS.md → "Project decisions".`)
+1 -1
View File
@@ -86,7 +86,7 @@ const items = block.tableOfContents?.show ? extractHeadings(block.content) : []
(works without JS); in the browser the link of the section being read gets `aria-current="location"` and `classNames.linkActive`.
`classNames`: `nav`, `label`, `list`, `item`, `link`, `linkActive`; `offset` (default 0.3 of the screen height);
`data-ipal="toc"`, `data-level` on items.
- `buildTableOfContentsField({ name = 'tableOfContents' })` — a "Show table of contents" switch + a localized label (type `TableOfContentsSettings`).
- `buildTableOfContentsField({ name = 'tableOfContents' })` — a "Show contents" switch + a localized label (type `TableOfContentsSettings`).
A new field in a block = a migration (`pnpm payload migrate:create`).
## Click-to-enlarge images (lightbox, opt-in)
+19 -2
View File
@@ -34,6 +34,11 @@
"types": "./dist/exports/seed.d.ts",
"default": "./dist/exports/seed.js"
},
"./templates": {
"import": "./dist/exports/templates.js",
"types": "./dist/exports/templates.d.ts",
"default": "./dist/exports/templates.js"
},
"./next/middleware": {
"import": "./dist/exports/next-middleware.js",
"types": "./dist/exports/next-middleware.d.ts",
@@ -44,6 +49,16 @@
"types": "./dist/exports/admin.d.ts",
"default": "./dist/exports/admin.js"
},
"./blocks": {
"import": "./dist/exports/blocks.js",
"types": "./dist/exports/blocks.d.ts",
"default": "./dist/exports/blocks.js"
},
"./blocks/rsc": {
"import": "./dist/exports/blocks-rsc.js",
"types": "./dist/exports/blocks-rsc.d.ts",
"default": "./dist/exports/blocks-rsc.js"
},
"./env": {
"import": "./dist/exports/env.js",
"types": "./dist/exports/env.d.ts",
@@ -55,12 +70,14 @@
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"bin": {
"ipal-skills": "bin/ipal-skills.mjs"
"ipal-skills": "bin/ipal-skills.mjs",
"ipal-blocks": "bin/ipal-blocks.mjs"
},
"files": [
"dist",
"docs",
"bin"
"bin",
"src/modules/block-library"
],
"sideEffects": [
"**/*.css"
+63
View File
@@ -0,0 +1,63 @@
/**
* Entry point: @intecion/ipal-kit/blocks/rsc
*
* The block library's components (React Server Components), its UI primitives and
* createBlockRegistry. Schemas: '@intecion/ipal-kit/blocks'. Docs: docs/block-library.md.
*
* export const blockRegistry = createBlockRegistry(content, { Image, Link, sendForm })
*/
export { CONTACT_PARTS, ContactBlock } from '../modules/block-library/blocks/contact/Component.js'
export type { ContactBlockData } from '../modules/block-library/blocks/contact/Component.js'
export { CTA_PARTS, CtaBlock } from '../modules/block-library/blocks/cta/Component.js'
export type { CtaBlockData } from '../modules/block-library/blocks/cta/Component.js'
export { defaultEntryCard, ENTRY_LIST_PARTS, EntryListBlock } from '../modules/block-library/blocks/entryList/Component.js'
export type { EntryListBlockData } from '../modules/block-library/blocks/entryList/Component.js'
export { FAQ_PARTS, FaqBlock } from '../modules/block-library/blocks/faq/Component.js'
export type { FaqBlockData, FaqItem } from '../modules/block-library/blocks/faq/Component.js'
export { FEATURE_GRID_PARTS, FeatureGridBlock } from '../modules/block-library/blocks/featureGrid/Component.js'
export type { FeatureGridBlockData, FeatureItem } from '../modules/block-library/blocks/featureGrid/Component.js'
export { GALLERY_PARTS, GalleryBlock } from '../modules/block-library/blocks/gallery/Component.js'
export type { GalleryBlockData, GalleryItem } from '../modules/block-library/blocks/gallery/Component.js'
export { HERO_PARTS, HeroBlock } from '../modules/block-library/blocks/hero/Component.js'
export type { HeroBlockData } from '../modules/block-library/blocks/hero/Component.js'
export { LOGOS_PARTS, LogosBlock } from '../modules/block-library/blocks/logos/Component.js'
export type { LogoItem, LogosBlockData } from '../modules/block-library/blocks/logos/Component.js'
export { PRICING_PARTS, PricingBlock } from '../modules/block-library/blocks/pricing/Component.js'
export type { PricingBlockData, PricingPlan } from '../modules/block-library/blocks/pricing/Component.js'
export { RICH_TEXT_PARTS, RichTextBlock } from '../modules/block-library/blocks/richText/Component.js'
export type { RichTextBlockData } from '../modules/block-library/blocks/richText/Component.js'
export { STATS_PARTS, StatsBlock } from '../modules/block-library/blocks/stats/Component.js'
export type { StatItem, StatsBlockData } from '../modules/block-library/blocks/stats/Component.js'
export { STEPS_PARTS, StepsBlock } from '../modules/block-library/blocks/steps/Component.js'
export type { StepItem, StepsBlockData } from '../modules/block-library/blocks/steps/Component.js'
export { TEAM_PARTS, TeamBlock } from '../modules/block-library/blocks/team/Component.js'
export type { TeamBlockData, TeamMember } from '../modules/block-library/blocks/team/Component.js'
export { defaultTestimonial, TESTIMONIALS_PARTS, TestimonialsBlock } from '../modules/block-library/blocks/testimonials/Component.js'
export type { TestimonialsBlockData } from '../modules/block-library/blocks/testimonials/Component.js'
export { TEXT_MEDIA_PARTS, TextMediaBlock } from '../modules/block-library/blocks/textMedia/Component.js'
export type { TextMediaBlockData } from '../modules/block-library/blocks/textMedia/Component.js'
export type { BlockContent, BlockContext, BlockUi, ContactDetail, EntryCard, LibraryBlockProps, TestimonialItem } from '../modules/block-library/context.js'
export type { BaseBlockData, LinkData, LinksData, MediaValue, RichTextData, SectionHeaderData, SectionSettingsData } from '../modules/block-library/data.js'
export { createBlockRegistry, LIBRARY_BLOCK_COMPONENTS } from '../modules/block-library/registry.js'
export type { BlockRegistryOptions } from '../modules/block-library/registry.js'
export { BLOCK_TEXTS, blockTexts, fillText } from '../modules/block-library/texts.js'
export type { BlockTexts } from '../modules/block-library/texts.js'
export { Anchor } from '../modules/block-library/ui/Anchor.js'
export type { LinkComponent } from '../modules/block-library/ui/Anchor.js'
export { BUTTON_CLASSES, buttonClass } from '../modules/block-library/ui/Button.js'
export { Buttons, GRID_COLUMNS, headingId } from '../modules/block-library/ui/Buttons.js'
export { Card, CARD_CLASS, CARD_INTERACTIVE_CLASS } from '../modules/block-library/ui/Card.js'
export type { CardProps } from '../modules/block-library/ui/Card.js'
export { CMSLink } from '../modules/block-library/ui/CMSLink.js'
export type { CMSLinkProps, ResolveLink } from '../modules/block-library/ui/CMSLink.js'
export { Container, CONTAINER_WIDTHS } from '../modules/block-library/ui/Container.js'
export type { ContainerProps, ContainerWidth } from '../modules/block-library/ui/Container.js'
export { cx, parts } from '../modules/block-library/ui/cx.js'
export type { PartClasses } from '../modules/block-library/ui/cx.js'
export { Media } from '../modules/block-library/ui/Media.js'
export type { ImageComponent, MediaProps } from '../modules/block-library/ui/Media.js'
export { Section, SECTION_BACKGROUNDS } from '../modules/block-library/ui/Section.js'
export type { SectionProps } from '../modules/block-library/ui/Section.js'
export { SectionHeader } from '../modules/block-library/ui/SectionHeader.js'
export type { HeadingLevel, SectionHeaderProps } from '../modules/block-library/ui/SectionHeader.js'
export { TitleLink } from '../modules/block-library/ui/TitleLink.js'
+50
View File
@@ -0,0 +1,50 @@
/**
* Entry point: @intecion/ipal-kit/blocks
*
* The block library's Payload side — block configs and field builders, no React
* (safe in payload.config and collections). Components: '@intecion/ipal-kit/blocks/rsc'.
* Docs: docs/block-library.md.
*
* { name: 'layout', type: 'blocks', blocks: [...libraryBlocks({ hero: true, faq: true }), MyBlock] }
*/
export { buildContactBlock } from '../modules/block-library/blocks/contact/config.js'
export type { ContactOptions } from '../modules/block-library/blocks/contact/config.js'
export { buildCtaBlock } from '../modules/block-library/blocks/cta/config.js'
export { buildEntryListBlock } from '../modules/block-library/blocks/entryList/config.js'
export type { EntryListOptions } from '../modules/block-library/blocks/entryList/config.js'
export { buildFaqBlock } from '../modules/block-library/blocks/faq/config.js'
export { buildFeatureGridBlock } from '../modules/block-library/blocks/featureGrid/config.js'
export type { FeatureGridOptions } from '../modules/block-library/blocks/featureGrid/config.js'
export { buildGalleryBlock } from '../modules/block-library/blocks/gallery/config.js'
export { buildHeroBlock } from '../modules/block-library/blocks/hero/config.js'
export { buildLogosBlock } from '../modules/block-library/blocks/logos/config.js'
export { buildPricingBlock } from '../modules/block-library/blocks/pricing/config.js'
export { buildRichTextBlock } from '../modules/block-library/blocks/richText/config.js'
export { buildStatsBlock } from '../modules/block-library/blocks/stats/config.js'
export { buildStepsBlock } from '../modules/block-library/blocks/steps/config.js'
export { buildTeamBlock } from '../modules/block-library/blocks/team/config.js'
export { buildTestimonialsBlock } from '../modules/block-library/blocks/testimonials/config.js'
export type { TestimonialsOptions } from '../modules/block-library/blocks/testimonials/config.js'
export { buildTextMediaBlock } from '../modules/block-library/blocks/textMedia/config.js'
export { adminText, defineLibraryBlock, variantOption } from '../modules/block-library/define.js'
export type { LibraryBlockDefinition } from '../modules/block-library/define.js'
export { faqItemsFromLayout } from '../modules/block-library/faq.js'
export { buildContentField, buildIconField, buildItemsField, buildMediaField, buildVariantField } from '../modules/block-library/fields.js'
export type { IconFieldOptions, ItemsFieldOptions, MediaFieldOptions, VariantFieldOptions } from '../modules/block-library/fields.js'
export { LIBRARY_BLOCK_BUILDERS, LIBRARY_BLOCK_SLUGS, libraryBlocks, libraryBlockSlugs } from '../modules/block-library/library.js'
export type { LibraryBlocksOptions } from '../modules/block-library/library.js'
export { blockLibraryManifest, buildBlockLibraryManifest, fieldPaths } from '../modules/block-library/manifest.js'
export type { BlockLibraryManifest, ManifestBlock, ManifestField } from '../modules/block-library/manifest.js'
export { applyBlockOptions, isNamed, pickVariants, removeField, replaceField, stripLocalized } from '../modules/block-library/options.js'
export { COLUMNS, columnsField } from '../modules/block-library/shared.js'
export type { Columns } from '../modules/block-library/shared.js'
export { blockThumbnail } from '../modules/block-library/thumbnails.js'
export type {
BlockBuilder,
BlockLocalization,
BlockOptions,
LibraryBlockSetting,
LibraryBlockSlug,
LibraryBlocksShared,
VariantOption,
} from '../modules/block-library/types.js'
+8
View File
@@ -0,0 +1,8 @@
/**
* Entry point: @intecion/ipal-kit/templates
*
* Page templates made of library blocks — seed data for createSeeder ('@intecion/ipal-kit/seed').
* Plain data, no React. Docs: docs/block-library.md "Page templates".
*/
export { pageTemplates, systemPageRefs } from '../modules/block-library/templates/index.js'
export type { TemplateBlock, TemplateOptions, TemplatePage, TemplateValue } from '../modules/block-library/templates/index.js'
@@ -0,0 +1,70 @@
import type { BuilderFormTexts } from '../../../forms/builderTypes.js'
import type { ContactDetail, LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, RichTextData } from '../../data.js'
import { RenderForm } from '../../../forms/RenderForm.js'
import { RenderRichText } from '../../../richtext/RenderRichText.js'
import { headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type ContactBlockData = { content?: RichTextData; form?: unknown } & BaseBlockData
export const CONTACT_PARTS = {
aside: 'space-y-6',
content: 'space-y-4 text-fg',
detailLabel: 'text-sm text-fg-muted',
details: 'grid gap-4',
detailValue: 'font-medium text-fg-strong',
form: 'rounded-card border border-border bg-surface p-6 md:p-8',
grid: 'grid gap-gap md:grid-cols-2',
}
/** A form from the form builder (RenderForm) with text and contact details beside it. Needs `sendForm` in createBlockRegistry. */
export async function ContactBlock(props: LibraryBlockProps<ContactBlockData>) {
const { classNames, content, ctx, form, header, isFirst, locale, settings, ui, variant } = props
if (!ctx.sendForm || !ctx.content.getFormTexts) {
console.warn('[ipal] contact block: pass sendForm and content with getFormTexts to createBlockRegistry')
return null
}
const c = parts(CONTACT_PARTS, classNames)
const id = headingId(props)
const withDetails = variant !== 'formOnly'
const [texts, linkOptions, details] = await Promise.all([
ctx.content.getFormTexts(locale),
ctx.content.getLinkOptions?.(locale),
withDetails && ctx.contactDetails ? ctx.contactDetails(locale) : ([] as ContactDetail[]),
])
const formEl = (
<div className={c.form}>
<RenderForm action={ctx.sendForm} classNames={ctx.formClassNames} form={form as never} linkOptions={linkOptions} locale={locale} texts={texts as BuilderFormTexts} />
</div>
)
const aside = withDetails && (content || details.length) ? (
<div className={c.aside}>
{content ? <RenderRichText className={cx(c.content, ctx.richText?.className)} data={content as never} /> : null}
{details.length ? (
<dl className={c.details}>
{details.map((d) => (
<div key={d.label}>
<dt className={c.detailLabel}>{d.label}</dt>
<dd className={c.detailValue}>{d.href ? <a className="text-link hover:text-link-hover" href={d.href}>{d.value}</a> : d.value}</dd>
</div>
))}
</dl>
) : null}
</div>
) : null
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings} width={aside ? 'default' : 'narrow'}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
{aside ? (
<div className={c.grid}>
{aside}
{formEl}
</div>
) : (
formEl
)}
</ui.Section>
)
}
@@ -0,0 +1,30 @@
import type { BlockOptions } from '../../types.js'
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildContentField } from '../../fields.js'
export const CONTACT_VARIANTS = [
variantOption('formWithDetails', 'Form and contact details', 'Formularz i dane kontaktowe'),
variantOption('formOnly', 'Form only', 'Tylko formularz'),
] as const
export type ContactOptions = {
/** The form builder collection. Default 'forms'. */
formsCollection?: string
} & BlockOptions
/** Contact — a form from the form builder, with text and contact details beside it. */
export const buildContactBlock = defineLibraryBlock<ContactOptions>({
slug: 'contact',
fields: ({ formsCollection = 'forms' }) => [
{ name: 'form', type: 'relationship', label: adminText('Form', 'Formularz'), relationTo: formsCollection, required: true },
buildContentField({
description: adminText('Shown beside the form, e.g. office hours.', 'Wyświetlany obok formularza, np. godziny pracy.'),
label: adminText('Side text', 'Tekst obok'),
}),
],
interfaceName: 'ContactBlock',
labels: { plural: adminText('Contact sections', 'Sekcje kontaktu'), singular: adminText('Contact', 'Kontakt') },
links: false,
variants: CONTACT_VARIANTS,
})
@@ -0,0 +1,50 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, MediaValue } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { Buttons, headingId } from '../../ui/Buttons.js'
import { parts } from '../../ui/cx.js'
export type CtaBlockData = { media?: MediaValue } & BaseBlockData
export const CTA_PARTS = {
band: 'flex flex-col items-start justify-between gap-6 md:flex-row md:items-center',
card: 'rounded-card bg-surface-raised p-8 text-center shadow-md md:p-12',
media: 'h-auto w-full rounded-media object-cover',
split: 'grid items-center gap-gap md:grid-cols-2',
}
/** A short heading with buttons: a band, a card, or beside an image. */
export function CtaBlock(props: LibraryBlockProps<CtaBlockData>) {
const { classNames, header, isFirst, links, locale, media, settings, ui, variant } = props
const c = parts(CTA_PARTS, classNames)
const id = headingId(props)
const as = isFirst ? 'h1' : 'h2'
const v = variant ?? 'band'
if (!header?.heading && !links?.length) {return null}
if (v === 'card') {
return (
<ui.Section block={props.blockType} compact labelledBy={id} settings={settings}>
<div className={c.card}>
<ui.SectionHeader align="center" as={as} className="mb-0" header={header} id={id} />
<Buttons className="justify-center" CMSLink={ui.CMSLink} links={links} locale={locale} />
</div>
</ui.Section>
)
}
return (
<ui.Section block={props.blockType} compact={v === 'band'} labelledBy={id} settings={settings}>
<div className={v === 'split' && media ? c.split : c.band}>
<div>
<ui.SectionHeader as={as} className="mb-0" header={header} id={id} />
{v === 'split' ? <Buttons CMSLink={ui.CMSLink} links={links} locale={locale} /> : null}
</div>
{v === 'split' ? (
<ui.Media className={c.media} resource={media} sizes={MEDIA_SIZES.half} />
) : (
<Buttons className="mt-0 shrink-0" CMSLink={ui.CMSLink} links={links} locale={locale} />
)}
</div>
</ui.Section>
)
}
@@ -0,0 +1,17 @@
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildMediaField } from '../../fields.js'
export const CTA_VARIANTS = [
variantOption('band', 'Full-width band', 'Pas na całą szerokość'),
variantOption('card', 'Card', 'Karta'),
variantOption('split', 'Image beside text', 'Obraz obok tekstu'),
] as const
/** Call to action — a short heading with one or two buttons. */
export const buildCtaBlock = defineLibraryBlock({
slug: 'cta',
fields: () => [buildMediaField()],
interfaceName: 'CtaBlock',
labels: { plural: adminText('Calls to action', 'Wezwania do działania'), singular: adminText('Call to action', 'Wezwanie do działania') },
variants: CTA_VARIANTS,
})
@@ -0,0 +1,80 @@
import type { EntryCard, LibraryBlockProps } from '../../context.js'
import type { BaseBlockData } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { Buttons, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
import { TitleLink } from '../../ui/TitleLink.js'
export type EntryListBlockData = {
collection?: null | string
entries?: { relationTo: string; value: unknown }[] | null
limit?: null | number
mode?: null | string
} & BaseBlockData
export const ENTRY_LIST_PARTS = {
card: 'gap-3 overflow-hidden',
cards: 'grid gap-gap sm:grid-cols-2 lg:grid-cols-3',
date: 'text-sm text-fg-muted',
list: 'grid gap-6',
media: 'aspect-[3/2] h-auto w-full object-cover',
text: 'text-fg-muted',
title: 'font-heading text-h4 leading-heading text-fg-strong',
}
const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v : undefined)
/** Default entry card: title, excerpt / description, media / image / cover, publishedAt. */
export function defaultEntryCard(doc: Record<string, unknown>): EntryCard | null {
const title = str(doc.title) ?? str(doc.name)
if (!title) {return null}
return { date: str(doc.publishedAt) ?? null, media: doc.media ?? doc.image ?? doc.cover, text: str(doc.excerpt) ?? str(doc.description) ?? null, title }
}
type Row = { card: EntryCard; collection: string; doc: Record<string, unknown> }
/** The latest entries of a collection, or entries chosen by hand; each card links to its entry. */
export async function EntryListBlock(props: LibraryBlockProps<EntryListBlockData>) {
const { classNames, collection, ctx, entries, header, isFirst, limit, links, locale, mode, settings, ui, variant } = props
const toCard = ctx.entryCard ?? defaultEntryCard
let docs: { collection: string; doc: Record<string, unknown> }[] = []
if (mode === 'selected') {
docs = (entries ?? []).flatMap((e) => (e?.value && typeof e.value === 'object' ? [{ collection: e.relationTo, doc: e.value as Record<string, unknown> }] : []))
} else if (collection && ctx.content.getEntries) {
const result = await ctx.content.getEntries(collection, locale, 1, limit ?? 3)
docs = result.docs.map((doc) => ({ collection, doc }))
}
const rows = docs.flatMap((d): Row[] => {
const card = toCard(d.doc, d.collection)
return card ? [{ ...d, card }] : []
})
if (!rows.length) {return null}
const c = parts(ENTRY_LIST_PARTS, classNames)
const id = headingId(props)
const dates = new Intl.DateTimeFormat(locale, { dateStyle: 'long' })
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<ul className={variant === 'list' ? c.list : c.cards}>
{rows.map(({ card, collection: from, doc }, i) => (
<li className="flex" key={typeof doc.id === 'string' || typeof doc.id === 'number' ? doc.id : i}>
<ui.Card className={cx('w-full', c.card)} interactive>
{variant === 'list' ? null : <ui.Media className={c.media} resource={card.media as never} sizes={MEDIA_SIZES.third} />}
<div className="flex flex-col gap-2 p-6 pt-0 first:pt-6">
{card.date ? <time className={c.date} dateTime={card.date}>{dates.format(new Date(card.date))}</time> : null}
<h3 className={c.title}>
<TitleLink link={{ type: 'internal', page: { relationTo: from, value: doc } }} Link={ctx.Link} locale={locale} resolve={ctx.content.resolveLink}>
{card.title}
</TitleLink>
</h3>
{card.text ? <p className={c.text}>{card.text}</p> : null}
</div>
</ui.Card>
</li>
))}
</ul>
<Buttons CMSLink={ui.CMSLink} links={links} locale={locale} />
</ui.Section>
)
}
@@ -0,0 +1,63 @@
import type { AdminText } from '../../../admin-i18n/define.js'
import type { BlockOptions } from '../../types.js'
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
export const ENTRY_LIST_VARIANTS = [variantOption('cards', 'Cards', 'Karty'), variantOption('list', 'List', 'Lista')] as const
export type EntryListOptions = {
/** Content collections the editor picks from (they need URLs: ipalKit `content`). Default posts. */
collections?: readonly { label: AdminText; value: string }[]
} & BlockOptions
const DEFAULT_COLLECTIONS = [{ label: adminText('Posts', 'Wpisy'), value: 'posts' }]
/** Entry list — the latest or chosen entries of a collection (posts, projects, products). */
export const buildEntryListBlock = defineLibraryBlock<EntryListOptions>({
slug: 'entryList',
fields: ({ collections = DEFAULT_COLLECTIONS, maxItems = 12 }) => {
const latest = (_: unknown, s: { mode?: string } | undefined) => s?.mode !== 'selected'
return [
{
name: 'collection',
type: 'select',
defaultValue: collections[0]?.value,
label: adminText('Show', 'Pokaż'),
options: collections.map((c) => ({ label: c.label, value: c.value })),
required: true,
},
{
name: 'mode',
type: 'radio',
defaultValue: 'latest',
label: adminText('Entries', 'Wpisy'),
options: [
{ label: adminText('The latest', 'Najnowsze'), value: 'latest' },
{ label: adminText('Chosen by hand', 'Wybrane ręcznie'), value: 'selected' },
],
},
{
name: 'limit',
type: 'number',
admin: { condition: latest },
defaultValue: 3,
label: adminText('How many', 'Liczba wpisów'),
max: maxItems,
min: 1,
},
{
name: 'entries',
type: 'relationship',
admin: { condition: (d: unknown, s: { mode?: string } | undefined) => !latest(d, s) },
hasMany: true,
label: adminText('Chosen entries', 'Wybrane wpisy'),
maxRows: maxItems,
relationTo: collections.map((c) => c.value),
},
]
},
interfaceName: 'EntryListBlock',
labels: { plural: adminText('Entry lists', 'Listy wpisów'), singular: adminText('Entry list', 'Lista wpisów') },
links: { maxRows: 1 },
variants: ENTRY_LIST_VARIANTS,
})
@@ -0,0 +1,44 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData } from '../../data.js'
import { Buttons, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type FaqItem = { answer: string; id?: null | string; question: string }
export type FaqBlockData = { items?: FaqItem[] | null } & BaseBlockData
export const FAQ_PARTS = {
answer: 'whitespace-pre-line px-5 pb-5 text-fg-muted',
item: 'group rounded-card border border-border bg-surface',
list: 'grid gap-3',
marker: 'shrink-0 text-fg-muted transition-transform duration-fast ease-out group-open:rotate-45',
question:
'flex cursor-pointer list-none items-center justify-between gap-4 p-5 font-medium text-fg-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus [&::-webkit-details-marker]:hidden',
twoColumn: 'md:grid-cols-2 md:items-start',
}
/** Questions as native <details>: keyboard and screen readers work with no script. */
export function FaqBlock(props: LibraryBlockProps<FaqBlockData>) {
const { classNames, header, isFirst, items, links, locale, settings, ui, variant } = props
const shown = (items ?? []).filter((i) => i.question && i.answer)
if (!shown.length) {return null}
const c = parts(FAQ_PARTS, classNames)
const id = headingId(props)
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<div className={cx(c.list, variant === 'twoColumn' && c.twoColumn)}>
{shown.map((item, i) => (
<details className={c.item} key={item.id ?? i}>
<summary className={c.question}>
<span>{item.question}</span>
<span aria-hidden className={c.marker}>+</span>
</summary>
<p className={c.answer}>{item.answer}</p>
</details>
))}
</div>
<Buttons CMSLink={ui.CMSLink} links={links} locale={locale} />
</ui.Section>
)
}
@@ -0,0 +1,24 @@
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildItemsField } from '../../fields.js'
export const FAQ_VARIANTS = [variantOption('single', 'One column', 'Jedna kolumna'), variantOption('twoColumn', 'Two columns', 'Dwie kolumny')] as const
/** FAQ — questions that open to show the answer; feeds FAQ rich results (faqItemsFromLayout). */
export const buildFaqBlock = defineLibraryBlock({
slug: 'faq',
fields: ({ maxItems = 30 }) => [
buildItemsField({
fields: [
{ name: 'question', type: 'text', label: adminText('Question', 'Pytanie'), localized: true, required: true },
{ name: 'answer', type: 'textarea', admin: { rows: 4 }, label: adminText('Answer', 'Odpowiedź'), localized: true, required: true },
],
labels: { plural: adminText('Questions', 'Pytania'), singular: adminText('Question', 'Pytanie') },
maxRows: maxItems,
rowLabelField: 'question',
}),
],
interfaceName: 'FaqBlock',
labels: { plural: adminText('FAQs', 'Pytania i odpowiedzi'), singular: adminText('FAQ', 'Pytania i odpowiedzi') },
links: { maxRows: 1 },
variants: FAQ_VARIANTS,
})
@@ -0,0 +1,70 @@
import type { BlockContext, BlockUi, LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, LinkData, MediaValue } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { Buttons, GRID_COLUMNS, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
import { TitleLink } from '../../ui/TitleLink.js'
export type FeatureItem = { heading: string; icon?: null | string; id?: null | string; link?: LinkData; media?: MediaValue; text?: null | string }
export type FeatureGridBlockData = { columns?: null | string; items?: FeatureItem[] | null } & BaseBlockData
export const FEATURE_GRID_PARTS = {
card: 'gap-3 p-6',
grid: 'grid gap-gap',
heading: 'font-heading text-h4 leading-heading text-fg-strong',
icon: 'h-8 w-8 text-primary',
list: 'grid gap-gap',
media: 'mb-2 h-auto w-full rounded-media object-cover',
number: 'font-heading text-h3 text-primary',
text: 'text-fg-muted',
}
/** Cards, a plain list or numbered items; a feature with a link makes its whole card clickable. */
export function FeatureGridBlock(props: LibraryBlockProps<FeatureGridBlockData>) {
const { classNames, columns, ctx, header, isFirst, items, links, locale, settings, ui, variant } = props
if (!items?.length) {return null}
const c = parts(FEATURE_GRID_PARTS, classNames)
const id = headingId(props)
const v = variant ?? 'cards'
const List = v === 'numbered' ? 'ol' : 'ul'
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<List className={cx(v === 'list' ? c.list : c.grid, GRID_COLUMNS[columns ?? 'three'])}>
{items.map((item, i) => (
<li className="flex" key={item.id ?? i}>
<FeatureCard c={c} ctx={ctx} index={v === 'numbered' ? i + 1 : undefined} item={item} locale={locale} plain={v === 'list'} ui={ui} />
</li>
))}
</List>
<Buttons CMSLink={ui.CMSLink} links={links} locale={locale} />
</ui.Section>
)
}
function FeatureCard({ c, ctx, index, item, locale, plain, ui }: { c: typeof FEATURE_GRID_PARTS; ctx: BlockContext; index?: number; item: FeatureItem; locale: string; plain: boolean; ui: BlockUi }) {
const Icon = item.icon ? ctx.icons?.[item.icon] : undefined
const heading = item.link ? (
<TitleLink link={item.link} Link={ctx.Link} locale={locale} resolve={ctx.content.resolveLink}>
{item.heading}
</TitleLink>
) : (
item.heading
)
const body = (
<>
{index ? <span aria-hidden className={c.number}>{String(index).padStart(2, '0')}</span> : null}
{Icon ? <Icon aria-hidden className={c.icon} /> : null}
<ui.Media className={c.media} resource={item.media} sizes={MEDIA_SIZES.third} />
<h3 className={c.heading}>{heading}</h3>
{item.text ? <p className={c.text}>{item.text}</p> : null}
</>
)
if (plain) {return <div className={cx('relative flex flex-col', c.card)}>{body}</div>}
return (
<ui.Card className={cx('w-full', c.card)} interactive={Boolean(item.link)}>
{body}
</ui.Card>
)
}
@@ -0,0 +1,42 @@
import type { Field } from 'payload'
import type { BlockOptions } from '../../types.js'
import { buildLinkField } from '../../../links/buildLinkField.js'
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildIconField, buildItemsField, buildMediaField } from '../../fields.js'
import { columnsField } from '../../shared.js'
export const FEATURE_GRID_VARIANTS = [
variantOption('cards', 'Cards', 'Karty'),
variantOption('list', 'List', 'Lista'),
variantOption('numbered', 'Numbered', 'Numerowane'),
] as const
export type FeatureGridOptions = {
/** The project's icon names — adds an icon select to each feature. Default none (images only). */
icons?: readonly string[]
} & BlockOptions
/** Feature grid — cards with an image or icon, heading, text and a link (services, advantages, categories). */
export const buildFeatureGridBlock = defineLibraryBlock<FeatureGridOptions>({
slug: 'featureGrid',
fields: ({ icons, maxItems = 12 }) => [
buildItemsField({
fields: [
...(icons?.length ? [buildIconField({ names: icons })] : []),
buildMediaField(),
{ name: 'heading', type: 'text', label: adminText('Heading', 'Nagłówek'), localized: true, required: true },
{ name: 'text', type: 'textarea', admin: { rows: 3 }, label: adminText('Text', 'Tekst'), localized: true },
buildLinkField({ appearances: false }),
] as Field[],
labels: { plural: adminText('Features', 'Elementy'), singular: adminText('Feature', 'Element') },
maxRows: maxItems,
}),
columnsField(),
],
interfaceName: 'FeatureGridBlock',
labels: { plural: adminText('Feature grids', 'Siatki elementów'), singular: adminText('Feature grid', 'Siatka elementów') },
links: { maxRows: 1 },
variants: FEATURE_GRID_VARIANTS,
})
@@ -0,0 +1,58 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, MediaValue } from '../../data.js'
import { lightboxImage } from '../../../lightbox/lightboxImage.js'
import { LightboxTrigger } from '../../../lightbox/LightboxProvider.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { Buttons, GRID_COLUMNS, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type GalleryItem = { caption?: null | string; id?: null | string; media?: MediaValue }
export type GalleryBlockData = { columns?: null | string; items?: GalleryItem[] | null } & BaseBlockData
export const GALLERY_PARTS = {
caption: 'mt-2 text-sm text-fg-muted',
grid: 'grid gap-4',
image: 'h-full w-full rounded-media object-cover',
item: 'm-0',
masonry: 'columns-1 gap-4 sm:columns-2 lg:columns-3 [&>*]:mb-4 [&>*]:break-inside-avoid',
trigger: 'block w-full overflow-hidden rounded-media focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus',
}
/** Images in a grid or a mosaic; each opens in the site's image viewer (one group per gallery). */
export function GalleryBlock(props: LibraryBlockProps<GalleryBlockData>) {
const { classNames, columns, ctx, header, isFirst, items, links, locale, settings, ui, variant } = props
const shown = (items ?? []).filter((item) => item.media)
if (!shown.length) {return null}
const c = parts(GALLERY_PARTS, classNames)
const id = headingId(props)
const group = `gallery-${props.id ?? 'block'}`
const masonry = variant === 'masonry'
const sizes = columns === 'two' ? MEDIA_SIZES.half : columns === 'four' ? MEDIA_SIZES.quarter : MEDIA_SIZES.third
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings} width="wide">
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<ul className={masonry ? c.masonry : cx(c.grid, GRID_COLUMNS[columns ?? 'three'])}>
{shown.map((item, i) => {
const image = <ui.Media className={c.image} resource={item.media} sizes={sizes} />
const large = ctx.lightbox ? lightboxImage(item.media, item.caption ? { caption: item.caption } : {}) : null
return (
<li key={item.id ?? i}>
<figure className={c.item}>
{large ? (
<LightboxTrigger className={c.trigger} group={group} image={large}>
{image}
</LightboxTrigger>
) : (
image
)}
{item.caption ? <figcaption className={c.caption}>{item.caption}</figcaption> : null}
</figure>
</li>
)
})}
</ul>
<Buttons CMSLink={ui.CMSLink} links={links} locale={locale} />
</ui.Section>
)
}
@@ -0,0 +1,26 @@
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildItemsField, buildMediaField } from '../../fields.js'
import { columnsField } from '../../shared.js'
export const GALLERY_VARIANTS = [variantOption('grid', 'Even grid', 'Równa siatka'), variantOption('masonry', 'Mosaic', 'Mozaika')] as const
/** Gallery — images that open enlarged in the site's image viewer. */
export const buildGalleryBlock = defineLibraryBlock({
slug: 'gallery',
fields: ({ maxItems = 48 }) => [
buildItemsField({
fields: [
buildMediaField({ required: true }),
{ name: 'caption', type: 'text', label: adminText('Caption', 'Podpis'), localized: true },
],
labels: { plural: adminText('Images', 'Obrazy'), singular: adminText('Image', 'Obraz') },
maxRows: maxItems,
rowLabelField: ['caption', 'media.alt', 'media.filename'],
}),
columnsField(),
],
interfaceName: 'GalleryBlock',
labels: { plural: adminText('Galleries', 'Galerie'), singular: adminText('Gallery', 'Galeria') },
links: { maxRows: 1 },
variants: GALLERY_VARIANTS,
})
@@ -0,0 +1,54 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, MediaValue } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { Buttons, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type HeroBlockData = { media?: MediaValue; poster?: MediaValue } & BaseBlockData
export const HERO_PARTS = {
background: 'relative isolate flex min-h-[var(--ipal-hero-min-h)] items-center overflow-hidden',
backgroundMedia: 'absolute inset-0 -z-10 h-full w-full object-cover',
backgroundOverlay: 'absolute inset-0 -z-10 bg-linear-to-t from-overlay to-transparent',
centered: 'mx-auto max-w-narrow text-center',
media: 'h-auto w-full rounded-media object-cover',
page: 'max-w-measure',
split: 'grid items-center gap-gap md:grid-cols-2',
}
/** Hero: split (image beside), background (image behind with a scrim), centered, page (small header). */
export function HeroBlock(props: LibraryBlockProps<HeroBlockData>) {
const { classNames, header, isFirst = true, links, locale, media, poster, settings, ui, variant } = props
const c = parts(HERO_PARTS, classNames)
const v = variant ?? 'split'
const id = headingId(props)
const as = isFirst ? 'h1' : 'h2'
const title = <ui.SectionHeader align={v === 'centered' ? 'center' : 'start'} as={as} className="mb-0" display={v !== 'page'} header={header} id={id} />
const buttons = <Buttons className={v === 'centered' ? 'justify-center' : undefined} CMSLink={ui.CMSLink} links={links} locale={locale} />
if (v === 'background') {
return (
<ui.Section block={props.blockType} className={c.background} labelledBy={id} settings={{ ...settings, background: 'inverted' }}>
<ui.Media alt="" className={c.backgroundMedia} poster={poster} priority={isFirst} resource={media} sizes={MEDIA_SIZES.full} videoMode="background" />
<span aria-hidden className={c.backgroundOverlay} />
<div className={c.page}>
{title}
{buttons}
</div>
</ui.Section>
)
}
const withMedia = v === 'split' && media
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<div className={cx(withMedia ? c.split : v === 'centered' ? c.centered : c.page)}>
<div>
{title}
{buttons}
</div>
{withMedia ? <ui.Media className={c.media} poster={poster} priority={isFirst} resource={media} sizes={MEDIA_SIZES.half} /> : null}
</div>
</ui.Section>
)
}
@@ -0,0 +1,27 @@
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildMediaField } from '../../fields.js'
export const HERO_VARIANTS = [
variantOption('split', 'Image beside text', 'Obraz obok tekstu'),
variantOption('background', 'Image behind text', 'Obraz pod tekstem'),
variantOption('centered', 'Centred text', 'Tekst na środku'),
variantOption('page', 'Small page header', 'Mały nagłówek strony'),
] as const
/** Hero — the first section of a page: heading, image or video, buttons. */
export const buildHeroBlock = defineLibraryBlock({
slug: 'hero',
fields: () => [
buildMediaField({ label: adminText('Image or video', 'Obraz lub wideo') }),
{
name: 'poster',
type: 'upload',
admin: { description: adminText('Shown before a video starts; not needed for an image.', 'Wyświetlana przed startem wideo; zbędna przy obrazie.') },
label: adminText('Video poster', 'Okładka wideo'),
relationTo: 'media',
},
],
interfaceName: 'HeroBlock',
labels: { plural: adminText('Heroes', 'Sekcje główne'), singular: adminText('Hero', 'Sekcja główna') },
variants: HERO_VARIANTS,
})
@@ -0,0 +1,50 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, LinkData, MediaValue } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { headingId } from '../../ui/Buttons.js'
import { parts } from '../../ui/cx.js'
export type LogoItem = { heading: string; id?: null | string; link?: LinkData; media?: MediaValue }
export type LogosBlockData = { items?: LogoItem[] | null } & BaseBlockData
export const LOGOS_PARTS = {
grid: 'grid grid-cols-2 items-center gap-8 sm:grid-cols-3 lg:grid-cols-6',
image: 'mx-auto h-12 w-auto object-contain',
row: 'flex flex-wrap items-center justify-center gap-x-12 gap-y-8',
}
const altOf = (item: LogoItem) => {
const alt = item.media && typeof item.media === 'object' ? (item.media as { alt?: unknown }).alt : undefined
return typeof alt === 'string' && alt.trim() ? alt : item.heading
}
/** Logos in a row or a grid; the name is the alt text when the image has none, and a link's name. */
export function LogosBlock(props: LibraryBlockProps<LogosBlockData>) {
const { classNames, header, isFirst, items, locale, settings, ui, variant } = props
const shown = (items ?? []).filter((i) => i.media)
if (!shown.length) {return null}
const c = parts(LOGOS_PARTS, classNames)
const id = headingId(props)
return (
<ui.Section block={props.blockType} compact labelledBy={id} settings={settings}>
<ui.SectionHeader align="center" as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<ul className={variant === 'grid' ? c.grid : c.row}>
{shown.map((item, i) => {
const logo = <ui.Media alt={altOf(item)} className={c.image} resource={item.media} sizes={MEDIA_SIZES.thumb} />
return (
<li key={item.id ?? i}>
{item.link ? (
<ui.CMSLink className="block" link={item.link} locale={locale}>
{logo}
</ui.CMSLink>
) : (
logo
)}
</li>
)
})}
</ul>
</ui.Section>
)
}
@@ -0,0 +1,27 @@
import type { Field } from 'payload'
import { buildLinkField } from '../../../links/buildLinkField.js'
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildItemsField, buildMediaField } from '../../fields.js'
export const LOGOS_VARIANTS = [variantOption('row', 'One row', 'Jeden rząd'), variantOption('grid', 'Grid', 'Siatka')] as const
/** Logos — clients, partners or certificates; the name is the alt text when the image has none. */
export const buildLogosBlock = defineLibraryBlock({
slug: 'logos',
fields: ({ maxItems = 24 }) => [
buildItemsField({
fields: [
buildMediaField({ label: adminText('Logo', 'Logo'), required: true }),
{ name: 'heading', type: 'text', label: adminText('Name', 'Nazwa'), localized: true, required: true },
buildLinkField({ appearances: false, disableLabel: true }),
] as Field[],
labels: { plural: adminText('Logos', 'Logotypy'), singular: adminText('Logo', 'Logo') },
maxRows: maxItems,
}),
],
interfaceName: 'LogosBlock',
labels: { plural: adminText('Logos', 'Logotypy'), singular: adminText('Logos', 'Logotypy') },
links: false,
variants: LOGOS_VARIANTS,
})
@@ -0,0 +1,72 @@
import type { BlockUi, LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, LinkData } from '../../data.js'
import { headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type PricingPlan = {
features?: { id?: null | string; text: string }[] | null
heading: string
highlighted?: boolean | null
id?: null | string
link?: LinkData
period?: null | string
price: string
text?: null | string
}
export type PricingBlockData = { highlightLabel?: null | string; items?: null | PricingPlan[]; note?: null | string } & BaseBlockData
export const PRICING_PARTS = {
name: 'font-heading text-h4 text-fg-strong',
badge: 'self-start rounded-full bg-accent px-3 py-1 text-xs font-medium text-on-accent',
feature: "flex gap-2 before:text-primary before:content-['✓']",
features: 'grid gap-2 text-sm',
grid: 'grid gap-gap md:grid-cols-2 lg:grid-cols-3',
highlighted: 'border-2 border-primary shadow-md',
note: 'mt-8 text-sm text-fg-muted',
period: 'text-fg-muted',
plan: 'gap-4 p-6',
price: 'font-heading text-h2 text-fg-strong',
}
/** Plans side by side; the highlighted plan carries a text label (not only a colour). */
export function PricingBlock(props: LibraryBlockProps<PricingBlockData>) {
const { classNames, header, highlightLabel, isFirst, items, locale, note, settings, ui } = props
if (!items?.length) {return null}
const c = parts(PRICING_PARTS, classNames)
const id = headingId(props)
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<ul className={c.grid}>
{items.map((plan, i) => (
<li className="flex" key={plan.id ?? i}>
<Plan c={c} highlightLabel={highlightLabel} locale={locale} plan={plan} ui={ui} />
</li>
))}
</ul>
{note ? <p className={c.note}>{note}</p> : null}
</ui.Section>
)
}
function Plan({ c, highlightLabel, locale, plan, ui }: { c: typeof PRICING_PARTS; highlightLabel?: null | string; locale: string; plan: PricingPlan; ui: BlockUi }) {
return (
<ui.Card className={cx('w-full', c.plan, plan.highlighted && c.highlighted)}>
{plan.highlighted && highlightLabel ? <p className={c.badge}>{highlightLabel}</p> : null}
<h3 className={c.name}>{plan.heading}</h3>
<p>
<span className={c.price}>{plan.price}</span> {plan.period ? <span className={c.period}>{plan.period}</span> : null}
</p>
{plan.text ? <p className="text-fg-muted">{plan.text}</p> : null}
{plan.features?.length ? (
<ul className={c.features}>
{plan.features.map((f, i) => (
<li className={c.feature} key={f.id ?? i}>{f.text}</li>
))}
</ul>
) : null}
{plan.link ? <div className="mt-auto pt-4"><ui.CMSLink link={plan.link} locale={locale} /></div> : null}
</ui.Card>
)
}
@@ -0,0 +1,58 @@
import type { Field } from 'payload'
import { buildLinkField } from '../../../links/buildLinkField.js'
import { adminText, defineLibraryBlock } from '../../define.js'
import { buildItemsField } from '../../fields.js'
/** Pricing — plans with a price, what is included and a button; one plan can be highlighted. */
export const buildPricingBlock = defineLibraryBlock({
slug: 'pricing',
fields: ({ maxItems = 6 }) => [
buildItemsField({
fields: [
{ name: 'heading', type: 'text', label: adminText('Plan name', 'Nazwa pakietu'), localized: true, required: true },
{
type: 'row',
fields: [
{ name: 'price', type: 'text', admin: { placeholder: adminText('$49', '199 zł'), width: '50%' }, label: adminText('Price', 'Cena'), localized: true, required: true },
{ name: 'period', type: 'text', admin: { placeholder: adminText('/ month', '/ miesiąc'), width: '50%' }, label: adminText('Period', 'Okres'), localized: true },
],
},
{ name: 'text', type: 'textarea', admin: { rows: 2 }, label: adminText('Short description', 'Krótki opis'), localized: true },
buildItemsField({
name: 'features',
fields: [{ name: 'text', type: 'text', label: adminText('Included', 'W pakiecie'), localized: true, required: true }],
labels: { plural: adminText('Included items', 'Elementy pakietu'), singular: adminText('Included item', 'Element pakietu') },
rowLabelField: 'text',
}),
{
name: 'highlighted',
type: 'checkbox',
admin: { description: adminText('Marks this plan with the highlight label.', 'Oznacza ten pakiet etykietą wyróżnienia.') },
defaultValue: false,
label: adminText('Highlight this plan', 'Wyróżnij ten pakiet'),
},
buildLinkField(),
] as Field[],
labels: { plural: adminText('Plans', 'Pakiety'), singular: adminText('Plan', 'Pakiet') },
maxRows: maxItems,
}),
{
name: 'highlightLabel',
type: 'text',
admin: { placeholder: adminText('Most popular', 'Najczęściej wybierany') },
label: adminText('Highlight label', 'Etykieta wyróżnienia'),
localized: true,
},
{
name: 'note',
type: 'textarea',
admin: { description: adminText('Shown under the plans, e.g. prices without VAT.', 'Wyświetlana pod pakietami, np. ceny netto.'), rows: 2 },
label: adminText('Note', 'Uwaga'),
localized: true,
},
],
interfaceName: 'PricingBlock',
labels: { plural: adminText('Pricing', 'Cenniki'), singular: adminText('Pricing', 'Cennik') },
links: false,
})
@@ -0,0 +1,41 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, RichTextData } from '../../data.js'
import { extractHeadings } from '../../../richtext/headings.js'
import { RenderRichText } from '../../../richtext/RenderRichText.js'
import { TableOfContents } from '../../../richtext/TableOfContents.js'
import { headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type RichTextBlockData = { content?: RichTextData; tableOfContents?: { label?: null | string; show?: boolean | null } | null } & BaseBlockData
export const RICH_TEXT_PARTS = {
content: 'space-y-4 text-fg [&_a]:text-link [&_a:hover]:text-link-hover [&_h2]:mt-10 [&_h2]:font-heading [&_h2]:text-h3 [&_h2]:text-fg-strong [&_h3]:mt-8 [&_h3]:font-heading [&_h3]:text-h4 [&_h3]:text-fg-strong [&_ol]:list-decimal [&_ol]:pl-6 [&_ul]:list-disc [&_ul]:pl-6',
layout: 'grid gap-gap lg:grid-cols-[16rem_1fr]',
toc: 'self-start text-sm lg:sticky lg:top-24',
}
/** A text section; with a table of contents its headings get anchor ids and a list beside the text. */
export function RichTextBlock(props: LibraryBlockProps<RichTextBlockData>) {
const { classNames, content, ctx, header, isFirst, settings, tableOfContents, ui, variant } = props
if (!content) {return null}
const c = parts(RICH_TEXT_PARTS, classNames)
const id = headingId(props)
const toc = tableOfContents?.show ? extractHeadings(content) : []
const text = <RenderRichText className={cx(c.content, ctx.richText?.className)} data={content as never} headingIds={toc.length > 0} />
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings} width={variant === 'wide' || toc.length ? 'default' : 'narrow'}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
{toc.length ? (
<div className={c.layout}>
<div className={c.toc}>
<TableOfContents items={toc} label={tableOfContents?.label ?? undefined} />
</div>
<div className="max-w-measure">{text}</div>
</div>
) : (
text
)}
</ui.Section>
)
}
@@ -0,0 +1,15 @@
import { buildTableOfContentsField } from '../../../richtext/headings.js'
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildContentField } from '../../fields.js'
export const RICH_TEXT_VARIANTS = [variantOption('narrow', 'Narrow column', 'Wąska kolumna'), variantOption('wide', 'Full width', 'Pełna szerokość')] as const
/** Text — a formatted text section (legal pages, articles), with an optional table of contents. */
export const buildRichTextBlock = defineLibraryBlock({
slug: 'richText',
fields: () => [buildContentField({ required: true }), buildTableOfContentsField()],
interfaceName: 'RichTextBlock',
labels: { plural: adminText('Text sections', 'Sekcje tekstu'), singular: adminText('Text', 'Tekst') },
links: false,
variants: RICH_TEXT_VARIANTS,
})
@@ -0,0 +1,42 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData } from '../../data.js'
import { headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type StatItem = { heading: string; id?: null | string; text?: null | string; value: string }
export type StatsBlockData = { items?: null | StatItem[] } & BaseBlockData
export const STATS_PARTS = {
card: 'rounded-card border border-border bg-surface p-6 shadow-sm',
item: 'flex flex-col-reverse gap-1',
label: 'font-medium text-fg-strong',
list: 'grid gap-gap sm:grid-cols-2 lg:grid-cols-4',
text: 'text-sm text-fg-muted',
value: 'm-0 font-heading text-display leading-none text-primary',
}
/** Key figures as a description list (number + label). Static: no count-up animation. */
export function StatsBlock(props: LibraryBlockProps<StatsBlockData>) {
const { classNames, header, isFirst, items, settings, ui, variant } = props
const shown = (items ?? []).filter((i) => i.value && i.heading)
if (!shown.length) {return null}
const c = parts(STATS_PARTS, classNames)
const id = headingId(props)
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<dl className={c.list}>
{shown.map((s, i) => (
<div className={cx(c.item, variant === 'cards' && c.card)} key={s.id ?? i}>
<dt className={c.label}>
{s.heading}
{s.text ? <span className={cx('block font-normal', c.text)}>{s.text}</span> : null}
</dt>
<dd className={c.value}>{s.value}</dd>
</div>
))}
</dl>
</ui.Section>
)
}
@@ -0,0 +1,29 @@
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildItemsField } from '../../fields.js'
export const STATS_VARIANTS = [variantOption('row', 'One row', 'Jeden rząd'), variantOption('cards', 'Cards', 'Karty')] as const
/** Key figures — a few numbers with a label ("120 projects"). Not the site's visit statistics. */
export const buildStatsBlock = defineLibraryBlock({
slug: 'stats',
fields: ({ maxItems = 6 }) => [
buildItemsField({
fields: [
{
type: 'row',
fields: [
{ name: 'value', type: 'text', admin: { placeholder: adminText('120+', '120+'), width: '40%' }, label: adminText('Number', 'Liczba'), localized: true, required: true },
{ name: 'heading', type: 'text', admin: { width: '60%' }, label: adminText('Label', 'Opis liczby'), localized: true, required: true },
],
},
{ name: 'text', type: 'textarea', admin: { rows: 2 }, label: adminText('Extra text', 'Dodatkowy tekst'), localized: true },
],
labels: { plural: adminText('Figures', 'Liczby'), singular: adminText('Figure', 'Liczba') },
maxRows: maxItems,
}),
],
interfaceName: 'StatsBlock',
labels: { plural: adminText('Key figures', 'Liczby'), singular: adminText('Key figures', 'Liczby') },
links: false,
variants: STATS_VARIANTS,
})
@@ -0,0 +1,50 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, MediaValue } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { blockTexts, fillText } from '../../texts.js'
import { Buttons, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type StepItem = { heading: string; id?: null | string; media?: MediaValue; text?: null | string }
export type StepsBlockData = { items?: null | StepItem[] } & BaseBlockData
export const STEPS_PARTS = {
heading: 'font-heading text-h4 leading-heading text-fg-strong',
item: 'grid grid-cols-[3rem_1fr] gap-4',
list: 'grid gap-8',
media: 'mt-3 h-auto w-full max-w-md rounded-media object-cover',
number: 'flex h-12 w-12 items-center justify-center rounded-full bg-primary font-heading text-lg text-on-primary',
text: 'mt-1 text-fg-muted',
timeline: 'relative before:absolute before:top-0 before:bottom-0 before:left-6 before:w-px before:bg-border',
}
/** Steps in an ordered list, numbered or along a line. */
export function StepsBlock(props: LibraryBlockProps<StepsBlockData>) {
const { classNames, ctx, header, isFirst, items, links, locale, settings, ui, variant } = props
if (!items?.length) {return null}
const c = parts(STEPS_PARTS, classNames)
const texts = blockTexts(locale, ctx.texts)
const id = headingId(props)
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<ol className={cx(c.list, variant === 'timeline' && c.timeline)}>
{items.map((s, i) => (
<li className={c.item} key={s.id ?? i}>
<span aria-hidden className={cx(c.number, 'relative')}>{i + 1}</span>
<div>
<h3 className={c.heading}>
<span className="sr-only">{fillText(texts.step, i + 1)}: </span>
{s.heading}
</h3>
{s.text ? <p className={c.text}>{s.text}</p> : null}
<ui.Media className={c.media} resource={s.media} sizes={MEDIA_SIZES.half} />
</div>
</li>
))}
</ol>
<Buttons CMSLink={ui.CMSLink} links={links} locale={locale} />
</ui.Section>
)
}
@@ -0,0 +1,23 @@
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildItemsField, buildMediaField } from '../../fields.js'
export const STEPS_VARIANTS = [variantOption('numbered', 'Numbered', 'Numerowane'), variantOption('timeline', 'Timeline', 'Oś czasu')] as const
/** Steps — a process or timeline in order. */
export const buildStepsBlock = defineLibraryBlock({
slug: 'steps',
fields: ({ maxItems = 10 }) => [
buildItemsField({
fields: [
{ name: 'heading', type: 'text', label: adminText('Heading', 'Nagłówek'), localized: true, required: true },
{ name: 'text', type: 'textarea', admin: { rows: 3 }, label: adminText('Text', 'Tekst'), localized: true },
buildMediaField(),
],
labels: { plural: adminText('Steps', 'Kroki'), singular: adminText('Step', 'Krok') },
maxRows: maxItems,
}),
],
interfaceName: 'StepsBlock',
labels: { plural: adminText('Steps', 'Kroki'), singular: adminText('Steps', 'Kroki') },
variants: STEPS_VARIANTS,
})
@@ -0,0 +1,49 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, LinkData, MediaValue } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { Buttons, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
import { TitleLink } from '../../ui/TitleLink.js'
export type TeamMember = { bio?: null | string; heading: string; id?: null | string; link?: LinkData; media?: MediaValue; text?: null | string }
export type TeamBlockData = { items?: null | TeamMember[] } & BaseBlockData
export const TEAM_PARTS = {
name: 'font-heading text-h4 leading-heading text-fg-strong',
bio: 'text-sm text-fg-muted',
grid: 'grid gap-gap sm:grid-cols-2 lg:grid-cols-3',
list: 'grid gap-6',
listItem: 'grid gap-6 sm:grid-cols-[10rem_1fr] sm:items-start',
photo: 'aspect-square h-auto w-full rounded-media object-cover',
role: 'text-sm text-fg-muted',
}
/** People with a photo, name, role, a short bio and a profile link (the name links to it). */
export function TeamBlock(props: LibraryBlockProps<TeamBlockData>) {
const { classNames, ctx, header, isFirst, items, links, locale, settings, ui, variant } = props
if (!items?.length) {return null}
const c = parts(TEAM_PARTS, classNames)
const id = headingId(props)
const list = variant === 'list'
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<ul className={list ? c.list : c.grid}>
{items.map((m, i) => (
<li className={cx('flex flex-col gap-3', list && c.listItem)} key={m.id ?? i}>
<ui.Media className={c.photo} resource={m.media} sizes={list ? '10rem' : MEDIA_SIZES.third} />
<div className="flex flex-col gap-1">
<h3 className={c.name}><TitleLink link={m.link} Link={ctx.Link} locale={locale} resolve={ctx.content.resolveLink} stretch={false}>
{m.heading}
</TitleLink></h3>
{m.text ? <p className={c.role}>{m.text}</p> : null}
{m.bio ? <p className={c.bio}>{m.bio}</p> : null}
</div>
</li>
))}
</ul>
<Buttons CMSLink={ui.CMSLink} links={links} locale={locale} />
</ui.Section>
)
}
@@ -0,0 +1,34 @@
import type { Field } from 'payload'
import { buildLinkField } from '../../../links/buildLinkField.js'
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildItemsField, buildMediaField } from '../../fields.js'
export const TEAM_VARIANTS = [variantOption('grid', 'Grid', 'Siatka'), variantOption('list', 'List', 'Lista')] as const
/** Team — people with a photo, name, role and a profile link. */
export const buildTeamBlock = defineLibraryBlock({
slug: 'team',
fields: ({ maxItems = 24 }) => [
buildItemsField({
fields: [
buildMediaField({ label: adminText('Photo', 'Zdjęcie') }),
{
type: 'row',
fields: [
{ name: 'heading', type: 'text', admin: { width: '50%' }, label: adminText('Name', 'Imię i nazwisko'), localized: true, required: true },
{ name: 'text', type: 'text', admin: { placeholder: adminText('Co-founder', 'Współzałożycielka'), width: '50%' }, label: adminText('Role', 'Stanowisko'), localized: true },
],
},
{ name: 'bio', type: 'textarea', admin: { rows: 3 }, label: adminText('Short bio', 'Krótki opis'), localized: true },
buildLinkField({ name: 'link', appearances: false }),
] as Field[],
labels: { plural: adminText('People', 'Osoby'), singular: adminText('Person', 'Osoba') },
maxRows: maxItems,
}),
],
interfaceName: 'TeamBlock',
labels: { plural: adminText('Teams', 'Zespoły'), singular: adminText('Team', 'Zespół') },
links: { maxRows: 1 },
variants: TEAM_VARIANTS,
})
@@ -0,0 +1,72 @@
import type { LibraryBlockProps, TestimonialItem } from '../../context.js'
import type { BaseBlockData } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { blockTexts, fillText } from '../../texts.js'
import { Buttons, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type TestimonialsBlockData = { entries?: null | unknown[]; items?: null | TestimonialItem[]; source?: null | string } & BaseBlockData
export const TESTIMONIALS_PARTS = {
author: 'font-medium text-fg-strong',
figure: 'm-0 flex h-full flex-col gap-4 p-6',
grid: 'grid gap-gap md:grid-cols-2 lg:grid-cols-3',
photo: 'h-12 w-12 rounded-full object-cover',
quote: 'text-lead text-fg',
rating: 'text-accent',
role: 'text-sm text-fg-muted',
single: 'mx-auto grid max-w-narrow gap-gap',
}
const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v : undefined)
/** Default mapping of a testimonials-collection document. */
export function defaultTestimonial(doc: Record<string, unknown>): null | TestimonialItem {
const quote = str(doc.quote) ?? str(doc.text)
const heading = str(doc.heading) ?? str(doc.author) ?? str(doc.name)
if (!quote || !heading) {return null}
return { id: str(doc.id), heading, media: doc.media ?? doc.photo, quote, rating: typeof doc.rating === 'number' ? doc.rating : null, text: str(doc.role) ?? str(doc.company) ?? null }
}
/** Quotes as <figure>/<blockquote>/<figcaption>; a rating has a text equivalent for screen readers. */
export function TestimonialsBlock(props: LibraryBlockProps<TestimonialsBlockData>) {
const { classNames, ctx, entries, header, isFirst, items, links, locale, settings, source, ui, variant } = props
const map = ctx.mapTestimonial ?? defaultTestimonial
const list =
source === 'collection'
? (entries ?? []).flatMap((e) => (e && typeof e === 'object' ? [map(e as Record<string, unknown>)] : [])).filter((x): x is TestimonialItem => !!x)
: (items ?? []).filter((i) => i.quote && i.heading)
if (!list.length) {return null}
const c = parts(TESTIMONIALS_PARTS, classNames)
const texts = blockTexts(locale, ctx.texts)
const id = headingId(props)
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<ui.SectionHeader align={variant === 'single' ? 'center' : 'start'} as={isFirst ? 'h1' : 'h2'} header={header} id={id} />
<ul className={variant === 'single' ? c.single : c.grid}>
{list.map((t, i) => (
<li key={t.id ?? i}>
<ui.Card as="figure" className={c.figure}>
{t.rating ? (
<p className={c.rating}>
<span aria-hidden>{'★'.repeat(Math.round(t.rating))}</span>
<span className="sr-only">{fillText(texts.rating, t.rating)}</span>
</p>
) : null}
<blockquote className={cx(c.quote, 'whitespace-pre-line')}>{t.quote}</blockquote>
<figcaption className="mt-auto flex items-center gap-3">
<ui.Media alt="" className={c.photo} resource={t.media as never} sizes={MEDIA_SIZES.thumb} />
<span className="flex flex-col">
<span className={c.author}>{t.heading}</span>
{t.text ? <span className={c.role}>{t.text}</span> : null}
</span>
</figcaption>
</ui.Card>
</li>
))}
</ul>
<Buttons CMSLink={ui.CMSLink} links={links} locale={locale} />
</ui.Section>
)
}
@@ -0,0 +1,70 @@
import type { Field } from 'payload'
import type { BlockOptions } from '../../types.js'
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildItemsField, buildMediaField } from '../../fields.js'
export const TESTIMONIALS_VARIANTS = [variantOption('grid', 'Grid', 'Siatka'), variantOption('single', 'One at a time', 'Pojedyncza opinia')] as const
export type TestimonialsOptions = {
/**
* A collection of testimonials to pick from, e.g. 'testimonials' — adds "From the list" as a source.
* Its documents need `quote` and `heading` (author); `text`, `media`, `rating` are optional
* (or map them with `mapTestimonial` in createBlockRegistry). Default none: inline only.
*/
collection?: string
} & BlockOptions
const ITEM_FIELDS: Field[] = [
{ name: 'quote', type: 'textarea', admin: { rows: 4 }, label: adminText('Quote', 'Cytat'), localized: true, required: true },
{
type: 'row',
fields: [
{ name: 'heading', type: 'text', admin: { width: '50%' }, label: adminText('Author', 'Autor'), localized: true, required: true },
{ name: 'text', type: 'text', admin: { width: '50%' }, label: adminText('Role or company', 'Stanowisko lub firma'), localized: true },
],
},
buildMediaField({ label: adminText('Photo', 'Zdjęcie') }),
{ name: 'rating', type: 'number', admin: { step: 1 }, label: adminText('Rating (1–5)', 'Ocena (1–5)'), max: 5, min: 1 },
]
/** Testimonials — quotes typed into the block, or picked from a testimonials collection. */
export const buildTestimonialsBlock = defineLibraryBlock<TestimonialsOptions>({
slug: 'testimonials',
fields: ({ collection, maxItems = 12 }) => {
const items = buildItemsField({
fields: ITEM_FIELDS,
labels: { plural: adminText('Testimonials', 'Opinie'), singular: adminText('Testimonial', 'Opinia') },
maxRows: maxItems,
})
if (!collection) {return [items]}
const fromList = (_: unknown, s: { source?: string } | undefined) => s?.source === 'collection'
return [
{
name: 'source',
type: 'radio',
defaultValue: 'inline',
label: adminText('Source', 'Źródło'),
options: [
{ label: adminText('Typed here', 'Wpisane tutaj'), value: 'inline' },
{ label: adminText('From the list', 'Z listy opinii'), value: 'collection' },
],
},
{ ...items, admin: { ...items.admin, condition: (d: unknown, s: { source?: string } | undefined) => !fromList(d, s) } },
{
name: 'entries',
type: 'relationship',
admin: { condition: fromList },
hasMany: true,
label: adminText('Testimonials', 'Opinie'),
maxRows: maxItems,
relationTo: collection,
},
]
},
interfaceName: 'TestimonialsBlock',
labels: { plural: adminText('Testimonials', 'Opinie'), singular: adminText('Testimonials', 'Opinie') },
links: { maxRows: 1 },
variants: TESTIMONIALS_VARIANTS,
})
@@ -0,0 +1,39 @@
import type { LibraryBlockProps } from '../../context.js'
import type { BaseBlockData, MediaValue, RichTextData } from '../../data.js'
import { MEDIA_SIZES } from '../../../media/mediaProps.js'
import { RenderRichText } from '../../../richtext/RenderRichText.js'
import { Buttons, headingId } from '../../ui/Buttons.js'
import { cx, parts } from '../../ui/cx.js'
export type TextMediaBlockData = { content?: RichTextData; media?: MediaValue } & BaseBlockData
export const TEXT_MEDIA_PARTS = {
content: 'max-w-measure space-y-4 text-fg',
grid: 'grid items-center gap-gap md:grid-cols-2',
media: 'h-auto w-full rounded-media object-cover',
mediaLeft: 'md:order-first',
}
/** Text and image side by side; the image goes left or right with `variant`. */
export function TextMediaBlock(props: LibraryBlockProps<TextMediaBlockData>) {
const { classNames, content, ctx, header, isFirst, links, locale, media, settings, ui, variant } = props
const c = parts(TEXT_MEDIA_PARTS, classNames)
const id = headingId(props)
return (
<ui.Section block={props.blockType} labelledBy={id} settings={settings}>
<div className={media ? c.grid : undefined}>
<div>
<ui.SectionHeader as={isFirst ? 'h1' : 'h2'} className="mb-6" header={header} id={id} />
{content ? <RenderRichText className={cx(c.content, ctx.richText?.className)} data={content as never} /> : null}
<Buttons CMSLink={ui.CMSLink} links={links} locale={locale} />
</div>
{media ? (
<div className={variant === 'mediaLeft' ? c.mediaLeft : undefined}>
<ui.Media className={c.media} priority={isFirst} resource={media} sizes={MEDIA_SIZES.half} />
</div>
) : null}
</div>
</ui.Section>
)
}
@@ -0,0 +1,16 @@
import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
import { buildContentField, buildMediaField } from '../../fields.js'
export const TEXT_MEDIA_VARIANTS = [
variantOption('mediaRight', 'Image on the right', 'Obraz po prawej'),
variantOption('mediaLeft', 'Image on the left', 'Obraz po lewej'),
] as const
/** Text and image — formatted text beside an image or a video. */
export const buildTextMediaBlock = defineLibraryBlock({
slug: 'textMedia',
fields: () => [buildContentField(), buildMediaField({ label: adminText('Image or video', 'Obraz lub wideo') })],
interfaceName: 'TextMediaBlock',
labels: { plural: adminText('Text and image', 'Tekst i obraz'), singular: adminText('Text and image', 'Tekst i obraz') },
variants: TEXT_MEDIA_VARIANTS,
})
+76
View File
@@ -0,0 +1,76 @@
import type { ComponentType, ReactNode } from 'react'
import type { ArchiveEntries } from '../content/getArchiveEntries.js'
import type { BuilderFormClassNames } from '../forms/BuilderForm.js'
import type { SendFormAction } from '../forms/RenderForm.js'
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
import type { BlockTexts } from './texts.js'
import type { LinkComponent } from './ui/Anchor.js'
import type { CardProps } from './ui/Card.js'
import type { CMSLinkProps, ResolveLink } from './ui/CMSLink.js'
import type { ContainerProps } from './ui/Container.js'
import type { PartClasses } from './ui/cx.js'
import type { ImageComponent, MediaProps } from './ui/Media.js'
import type { SectionProps } from './ui/Section.js'
import type { SectionHeaderProps } from './ui/SectionHeader.js'
/** The UI primitives every library block is built from. Swap any of them with createBlockRegistry({ ui }). */
export type BlockUi = {
buttonClass: (appearance?: null | string) => string
Card: ComponentType<CardProps>
CMSLink: (props: CMSLinkProps) => Promise<ReactNode> | ReactNode
Container: ComponentType<ContainerProps>
Media: ComponentType<MediaProps>
Section: ComponentType<SectionProps>
SectionHeader: ComponentType<SectionHeaderProps>
}
/** One line of contact details beside the contact form. */
export type ContactDetail = { href?: string; label: string; value: string }
/** One testimonial as the component renders it. */
export type TestimonialItem = { heading: string; id?: null | string; media?: unknown; quote: string; rating?: null | number; text?: null | string }
/** One entry card of the entry list. */
export type EntryCard = { date?: null | string; media?: unknown; text?: null | string; title: string }
/** What the blocks may need from lib/content (createContentHelpers). Only resolveLink is required. */
export type BlockContent = {
getEntries?: (collection: string, locale: string, page: number, perPage: number) => Promise<ArchiveEntries>
getFormTexts?: (locale: string) => Promise<unknown>
getLinkOptions?: (locale: string) => Promise<ResolveLinkHrefOptions>
resolveLink: ResolveLink
}
/** Everything a block gets from the registry besides its data. */
export type BlockContext = {
/** Contact details beside the form (from the project's company global). */
contactDetails?: (locale: string) => ContactDetail[] | Promise<ContactDetail[]>
content: BlockContent
/** Turns a collection document into an entry card. Default: title, excerpt/description, media/image, publishedAt. */
entryCard?: (doc: Record<string, unknown>, collection: string) => EntryCard | null
formClassNames?: BuilderFormClassNames
/** The project's icon components by name (the names of buildFeatureGridBlock({ icons })). */
icons?: Record<string, ComponentType<{ 'aria-hidden'?: boolean; className?: string }>>
/** next/image — optimized images with blur-up. Without it: a plain <img>. */
Image?: ImageComponent
/** Lightbox triggers on gallery images. Default true (needs <SiteProviders lightbox>). */
lightbox: boolean
/** next/link — client-side navigation for internal links. Without it: a plain <a>. */
Link?: LinkComponent
/** Turns a testimonials-collection document into an item. Default: quote, heading/author/name, text/role, media, rating. */
mapTestimonial?: (doc: Record<string, unknown>) => null | TestimonialItem
richText?: { className?: string }
/** The project's sendForm server action (createSubmitAction) — the contact block needs it. */
sendForm?: SendFormAction
texts?: Partial<Record<string, Partial<BlockTexts>>>
}
/** Props of every library block component: its data + locale + what the registry binds. */
export type LibraryBlockProps<D> = {
classNames?: PartClasses
ctx: BlockContext
isFirst?: boolean
locale: string
ui: BlockUi
} & D
+31
View File
@@ -0,0 +1,31 @@
import type { LinkValue } from '../links/resolveLinkHref.js'
/**
* The stored shapes the library components read. They match the generated
* payload-types of the library blocks, so a project's own types fit them.
*/
export type SectionHeaderData = { eyebrow?: null | string; heading?: null | string; intro?: null | string }
export type SectionSettingsData = { [key: string]: unknown; anchor?: null | string; background?: null | string }
/** An upload as stored (an id) or populated (a media document). */
export type MediaValue = null | number | Record<string, unknown> | string | undefined
export type LinkData = LinkValue | null | undefined
export type LinksData = { id?: null | string; link?: LinkData }[] | null | undefined
/** Fields every library block has. */
export type BaseBlockData = {
blockName?: null | string
blockType: string
header?: null | SectionHeaderData
id?: null | string
links?: LinksData
settings?: null | SectionSettingsData
variant?: null | string
}
/** Lexical editor state, as stored. */
export type RichTextData = null | Record<string, unknown> | undefined
+49
View File
@@ -0,0 +1,49 @@
import type { Block, Field } from 'payload'
import type { AdminText } from '../admin-i18n/define.js'
import type { BuildLinksFieldOptions } from '../links/buildLinkField.js'
import type { BlockBuilder, BlockOptions, LibraryBlockSlug, VariantOption } from './types.js'
import { buildSectionHeaderField, buildSectionSettingsField } from '../blocks/sectionFields.js'
import { buildLinksField } from '../links/buildLinkField.js'
import { buildVariantField } from './fields.js'
import { applyBlockOptions, pickVariants } from './options.js'
export type LibraryBlockDefinition<O extends BlockOptions> = {
/** The block's own fields, between the header and the buttons. */
fields: (options: O) => Field[]
/** Generated type name, e.g. 'FaqBlock'. */
interfaceName: string
labels: { plural: AdminText; singular: AdminText }
/** The block's default buttons. `false` = the block has none. Default `buildLinksField()`. */
links?: BuildLinksFieldOptions | false
slug: LibraryBlockSlug
/** The looks the editor picks from; the first is the default. None = no variant select. */
variants?: readonly VariantOption[]
}
/**
* Every library block has the same frame, in panel order:
* header → the block's fields → buttons → layout (sidebar) → section settings (sidebar).
*/
export function defineLibraryBlock<O extends BlockOptions = BlockOptions>(def: LibraryBlockDefinition<O>): BlockBuilder<O> {
return (options = {} as O) => {
const variants = def.variants ? pickVariants(def.variants, options.variants) : false
const links = options.links === false || def.links === false ? false : { ...def.links, ...options.links }
const fields: Field[] = [
...(options.header === false ? [] : [buildSectionHeaderField(options.header)]),
...def.fields(options),
...(links ? [buildLinksField(links)] : []),
...(variants && variants.length ? [buildVariantField({ options: variants })] : []),
buildSectionSettingsField(options.settings),
]
const base: Block = { slug: def.slug, fields, interfaceName: def.interfaceName, labels: def.labels }
return applyBlockOptions(base, options)
}
}
/** Shorthand for an { en, pl } text. */
export const adminText = (en: string, pl: string): AdminText => ({ en, pl })
/** Shorthand for a variant option. */
export const variantOption = (value: string, en: string, pl: string): VariantOption => ({ label: { en, pl }, value })
+17
View File
@@ -0,0 +1,17 @@
/**
* FAQ rich results from the page's FAQ blocks — pass it to getPageJsonLd:
*
* getPageJsonLd(locale, slug, { faq: faqItemsFromLayout })
*
* Reads the FAQ blocks by slug (default 'faq'; pass a renamed slug in `slugs`).
* Empty questions and answers are skipped.
*/
export function faqItemsFromLayout(doc: Record<string, unknown>, { field = 'layout', slugs = ['faq'] }: { field?: string; slugs?: string[] } = {}): { answer: string; question: string }[] {
const layout = doc[field]
if (!Array.isArray(layout)) {return []}
return layout
.filter((b): b is { blockType: string; items?: unknown } => !!b && typeof b === 'object' && slugs.includes((b as { blockType?: string }).blockType ?? ''))
.flatMap((b) => (Array.isArray(b.items) ? (b.items as { answer?: unknown; question?: unknown }[]) : []))
.filter((i) => typeof i.question === 'string' && typeof i.answer === 'string' && i.question.trim() && i.answer.trim())
.map((i) => ({ answer: (i.answer as string).trim(), question: (i.question as string).trim() }))
}
+103
View File
@@ -0,0 +1,103 @@
import type { ArrayField, Field, RichTextField, SelectField, UploadField } from 'payload'
import type { AdminText } from '../admin-i18n/define.js'
import type { VariantOption } from './types.js'
import { rowLabel } from '../admin-ui/rowLabel.js'
/**
* Field builders the library blocks are made of — exported so a project's own blocks
* get the same panel. Every label is { en, pl } (docs/dev/admin-ux.md).
*/
export type ItemsFieldOptions = {
/** The fields of one item. */
fields: Field[]
/** What one item is called in the panel: "Add <singular>". */
labels: { plural: AdminText; singular: AdminText }
maxRows?: number
minRows?: number
/** Default 'items'. */
name?: string
/** The item field shown as the collapsed row's name. Default 'heading'. */
rowLabelField?: string | string[]
}
/** `items` — repeated things as one "+ Add …" array with collapsed, readable rows. */
export function buildItemsField({ name = 'items', fields, labels, maxRows, minRows, rowLabelField = 'heading' }: ItemsFieldOptions): ArrayField {
return {
name,
type: 'array',
admin: { components: rowLabel(rowLabelField, labels.singular), initCollapsed: true },
fields,
label: labels.plural,
labels,
...(maxRows ? { maxRows } : {}),
...(minRows ? { minRows } : {}),
}
}
export type MediaFieldOptions = {
label?: AdminText
/** Localize the file itself (a different image per language). Default false — the alt text is localized in Media. */
localized?: boolean
/** Default 'media'. */
name?: string
/** Default 'media'. */
relationTo?: string
required?: boolean
}
/** `media` — an image or a video from the media collection. */
export function buildMediaField({ name = 'media', label = { en: 'Image', pl: 'Obraz' }, localized = false, relationTo = 'media', required = false }: MediaFieldOptions = {}): UploadField {
return { name, type: 'upload', label, relationTo, ...(localized ? { localized } : {}), ...(required ? { required } : {}) }
}
export type VariantFieldOptions = {
/** Default: the first option. */
defaultValue?: string
label?: AdminText
/** Default 'variant'. */
name?: string
options: readonly VariantOption[]
}
/** `variant` — a different look of the same block, in the sidebar. */
export function buildVariantField({ name = 'variant', defaultValue, label = { en: 'Layout', pl: 'Układ' }, options }: VariantFieldOptions): SelectField {
return {
name,
type: 'select',
admin: { position: 'sidebar' },
defaultValue: defaultValue ?? options[0]?.value,
label,
options: options.map((o) => ({ label: o.label, value: o.value })),
}
}
export type IconFieldOptions = {
label?: AdminText
/** Default 'icon'. */
name?: string
/** The project's icon names (its own icon map renders them). Labels default to the names. */
names: readonly ({ label: AdminText; value: string } | string)[]
}
/** `icon` — a select of the project's icon names. The plugin ships no icon set. */
export function buildIconField({ name = 'icon', label = { en: 'Icon', pl: 'Ikona' }, names }: IconFieldOptions): SelectField {
return {
name,
type: 'select',
label,
options: names.map((n) => (typeof n === 'string' ? { label: { en: n, pl: n }, value: n } : n)),
}
}
/** `content` — formatted text (rich text) with the project's default editor. */
export function buildContentField({
name = 'content',
description,
label = { en: 'Text', pl: 'Treść' },
required = false,
}: { description?: AdminText; label?: AdminText; name?: string; required?: boolean } = {}): RichTextField {
return { name, type: 'richText', label, localized: true, ...(description ? { admin: { description } } : {}), ...(required ? { required } : {}) }
}
+92
View File
@@ -0,0 +1,92 @@
import type { Block } from 'payload'
import type { ContactOptions } from './blocks/contact/config.js'
import type { EntryListOptions } from './blocks/entryList/config.js'
import type { FeatureGridOptions } from './blocks/featureGrid/config.js'
import type { TestimonialsOptions } from './blocks/testimonials/config.js'
import type { BlockBuilder, BlockOptions, LibraryBlockSetting, LibraryBlockSlug, LibraryBlocksShared } from './types.js'
import { buildContactBlock } from './blocks/contact/config.js'
import { buildCtaBlock } from './blocks/cta/config.js'
import { buildEntryListBlock } from './blocks/entryList/config.js'
import { buildFaqBlock } from './blocks/faq/config.js'
import { buildFeatureGridBlock } from './blocks/featureGrid/config.js'
import { buildGalleryBlock } from './blocks/gallery/config.js'
import { buildHeroBlock } from './blocks/hero/config.js'
import { buildLogosBlock } from './blocks/logos/config.js'
import { buildPricingBlock } from './blocks/pricing/config.js'
import { buildRichTextBlock } from './blocks/richText/config.js'
import { buildStatsBlock } from './blocks/stats/config.js'
import { buildStepsBlock } from './blocks/steps/config.js'
import { buildTeamBlock } from './blocks/team/config.js'
import { buildTestimonialsBlock } from './blocks/testimonials/config.js'
import { buildTextMediaBlock } from './blocks/textMedia/config.js'
/** Every library block builder, by default slug, in the order of the block picker. */
export const LIBRARY_BLOCK_BUILDERS = {
contact: buildContactBlock,
cta: buildCtaBlock,
entryList: buildEntryListBlock,
faq: buildFaqBlock,
featureGrid: buildFeatureGridBlock,
gallery: buildGalleryBlock,
hero: buildHeroBlock,
logos: buildLogosBlock,
pricing: buildPricingBlock,
richText: buildRichTextBlock,
stats: buildStatsBlock,
steps: buildStepsBlock,
team: buildTeamBlock,
testimonials: buildTestimonialsBlock,
textMedia: buildTextMediaBlock,
} satisfies Record<LibraryBlockSlug, BlockBuilder<never>>
export const LIBRARY_BLOCK_SLUGS = Object.keys(LIBRARY_BLOCK_BUILDERS) as LibraryBlockSlug[]
/** What `libraryBlocks` takes: a setting per block. Blocks not listed are off. */
export type LibraryBlocksOptions = {
contact?: LibraryBlockSetting<ContactOptions>
cta?: LibraryBlockSetting
entryList?: LibraryBlockSetting<EntryListOptions>
faq?: LibraryBlockSetting
featureGrid?: LibraryBlockSetting<FeatureGridOptions>
gallery?: LibraryBlockSetting
hero?: LibraryBlockSetting
logos?: LibraryBlockSetting
pricing?: LibraryBlockSetting
richText?: LibraryBlockSetting
stats?: LibraryBlockSetting
steps?: LibraryBlockSetting
team?: LibraryBlockSetting
testimonials?: LibraryBlockSetting<TestimonialsOptions>
textMedia?: LibraryBlockSetting
}
/**
* The library blocks the project turned on, ready for a `blocks` field:
*
* { name: 'layout', type: 'blocks', blocks: [...libraryBlocks({ hero: true, faq: { maxItems: 10 } }), MyBlock] }
*
* Nothing is on by default. `shared` applies to every block (a block's own options win).
*/
export function libraryBlocks(options: LibraryBlocksOptions, shared: LibraryBlocksShared = {}): Block[] {
return LIBRARY_BLOCK_SLUGS.flatMap((slug) => {
const setting = options[slug] as LibraryBlockSetting | undefined
if (!setting) {return []}
const build = LIBRARY_BLOCK_BUILDERS[slug] as BlockBuilder
if (typeof setting === 'function') {return [setting(build(shared))]}
const own: BlockOptions = setting === true ? {} : setting
return [build({ ...shared, ...own, settings: own.settings ?? shared.settings })]
})
}
/** The block slugs `libraryBlocks(options)` turns on, with the project's renames — for templates and the registry. */
export function libraryBlockSlugs(options: LibraryBlocksOptions): Partial<Record<LibraryBlockSlug, string>> {
const out: Partial<Record<LibraryBlockSlug, string>> = {}
for (const slug of LIBRARY_BLOCK_SLUGS) {
const setting = options[slug]
if (!setting) {continue}
out[slug] = typeof setting === 'object' && setting.slug ? setting.slug : slug
}
return out
}
+87
View File
@@ -0,0 +1,87 @@
import type { Field } from 'payload'
import type { LibraryBlockSlug } from './types.js'
import { LIBRARY_BLOCK_BUILDERS, LIBRARY_BLOCK_SLUGS } from './library.js'
/** One stored field of a block: its data path, type, required flag and select values. */
export type ManifestField = { options?: string[]; path: string; required?: boolean; type: string }
export type ManifestBlock = {
fields: ManifestField[]
interfaceName: string
phase: 1 | 2
slug: LibraryBlockSlug
variants: string[]
}
export type BlockLibraryManifest = {
blocks: ManifestBlock[]
/** Exported field builders a project block should use instead of its own copy. */
fieldBuilders: string[]
/** UI primitives (`/blocks/rsc`) a project can swap through `createBlockRegistry({ ui })`, by file name. */
primitives: string[]
/** Page templates (`/templates`). */
templates: string[]
}
/** Data paths of stored fields — rows, collapsibles and tabs without a name add no path segment. */
export function fieldPaths(fields: Field[], prefix = ''): ManifestField[] {
return fields.flatMap((field): ManifestField[] => {
if (field.type === 'tabs') {return field.tabs.flatMap((tab) => fieldPaths(tab.fields, 'name' in tab && tab.name ? `${prefix}${tab.name}.` : prefix))}
if (field.type === 'ui') {return []}
if (!('name' in field) || !field.name) {return 'fields' in field ? fieldPaths(field.fields, prefix) : []}
const path = `${prefix}${field.name}`
const own: ManifestField = { type: field.type, path }
if ('required' in field && field.required) {own.required = true}
if ((field.type === 'select' || field.type === 'radio') && Array.isArray(field.options)) {
own.options = field.options.map((o) => (typeof o === 'string' ? o : o.value))
}
if (field.type === 'upload' || field.type === 'relationship') {own.options = ([] as string[]).concat(field.relationTo)}
const nested = 'fields' in field && Array.isArray(field.fields) ? fieldPaths(field.fields, field.type === 'array' ? `${path}[].` : `${path}.`) : []
return [own, ...nested]
})
}
export const BLOCK_PRIMITIVES = ['Section', 'SectionHeader', 'Media', 'CMSLink', 'Button', 'Container', 'Card'] as const
export const FIELD_BUILDERS = [
'buildItemsField',
'buildMediaField',
'buildVariantField',
'buildIconField',
'buildContentField',
'buildSectionHeaderField',
'buildSectionSettingsField',
'buildLinkField',
'buildLinksField',
'buildTableOfContentsField',
] as const
export const PAGE_TEMPLATE_NAMES = ['home', 'about', 'services', 'service', 'contact', 'blogIndex', 'post', 'legal', 'cookiePolicy', 'notFound'] as const
/** Builds the manifest from the default block configs, so it cannot drift from the code. */
export function buildBlockLibraryManifest(): BlockLibraryManifest {
return {
blocks: LIBRARY_BLOCK_SLUGS.map((slug) => {
const block = LIBRARY_BLOCK_BUILDERS[slug]({ collection: 'testimonials' } as never)
const fields = fieldPaths(block.fields)
return {
slug,
fields,
interfaceName: block.interfaceName ?? '',
phase: 1,
variants: fields.find((f) => f.path === 'variant')?.options ?? [],
}
}),
fieldBuilders: [...FIELD_BUILDERS],
primitives: [...BLOCK_PRIMITIVES],
templates: [...PAGE_TEMPLATE_NAMES],
}
}
/**
* Names of the library's blocks, variants, primitives, field builders and templates —
* plain data for checks such as ipal-doctor. Built from the block configs themselves.
*/
export const blockLibraryManifest: BlockLibraryManifest = buildBlockLibraryManifest()
+73
View File
@@ -0,0 +1,73 @@
import type { Block, Field } from 'payload'
import type { BlockOptions, VariantOption } from './types.js'
import { blockThumbnail } from './thumbnails.js'
/** True when `field` is a named field called `name`. */
export function isNamed(field: Field, name: string): boolean {
return 'name' in field && field.name === name
}
/** A copy of `fields` with the field `name` patched (shallow merge, or a function). Searches rows, groups, tabs and collapsibles. */
export function replaceField(fields: Field[], name: string, patch: ((field: Field) => Field) | Partial<Field>): Field[] {
return fields.map((field) => {
if (isNamed(field, name)) {return typeof patch === 'function' ? patch(field) : ({ ...field, ...patch } as Field)}
if (field.type === 'tabs') {
return { ...field, tabs: field.tabs.map((tab) => ({ ...tab, fields: replaceField(tab.fields, name, patch) })) }
}
if ((field.type === 'row' || field.type === 'collapsible') && !('name' in field && field.name)) {
return { ...field, fields: replaceField(field.fields, name, patch) } as Field
}
return field
})
}
/** A copy of `fields` without the field `name` (top level only). */
export function removeField(fields: Field[], name: string): Field[] {
return fields.filter((field) => !isNamed(field, name))
}
/** Drops `localized` everywhere inside the fields — for projects that localize the whole `layout` field. */
export function stripLocalized(fields: Field[]): Field[] {
return fields.map((field) => {
const { localized: _localized, ...rest } = field as { localized?: boolean } & Field
const copy = rest as Field
if (copy.type === 'tabs') {return { ...copy, tabs: copy.tabs.map((tab) => ({ ...tab, fields: stripLocalized(tab.fields) })) }}
if (copy.type === 'blocks') {return { ...copy, blocks: copy.blocks.map((b) => ({ ...b, fields: stripLocalized(b.fields) })) }}
if ('fields' in copy && Array.isArray(copy.fields)) {return { ...copy, fields: stripLocalized(copy.fields) } as Field}
return copy
})
}
/** Keeps the variants the project chose, in its order; a value the block doesn't know needs `{ label, value }`. */
export function pickVariants(defaults: readonly VariantOption[], chosen: BlockOptions['variants']): false | VariantOption[] {
if (chosen === false) {return false}
if (!chosen) {return [...defaults]}
return chosen.map((v) => {
if (typeof v !== 'string') {return v}
const known = defaults.find((d) => d.value === v)
if (!known) {throw new Error(`[ipal] unknown variant "${v}" — pass { label, value } for a variant of your own`)}
return known
})
}
/**
* The block as the project wants it: slug, labels, admin, fields, localization.
* `base` comes from the block's builder; `options` from the project.
*/
export function applyBlockOptions(base: Block, options: BlockOptions = {}): Block {
const fields = typeof options.fields === 'function' ? options.fields(base.fields) : (options.fields ?? base.fields)
const block: Block = {
...base,
slug: options.slug ?? base.slug,
admin: { ...base.admin, ...options.admin },
custom: { ...base.custom, ...options.custom, ipalLibrary: base.slug },
fields: options.localization === 'layout' ? stripLocalized(fields) : fields,
interfaceName: options.interfaceName ?? base.interfaceName,
labels: options.labels ?? base.labels,
}
if (typeof options.thumbnail === 'string') {block.imageURL = options.thumbnail}
else if (options.thumbnail) {block.imageURL = blockThumbnail(base.slug)}
return block
}
+109
View File
@@ -0,0 +1,109 @@
import type { ComponentType } from 'react'
import type { BlockComponentMap } from '../blocks/types.js'
import type { BlockContent, BlockContext, BlockUi } from './context.js'
import type { LibraryBlockSlug } from './types.js'
import type { CMSLinkProps } from './ui/CMSLink.js'
import type { PartClasses } from './ui/cx.js'
import type { MediaProps } from './ui/Media.js'
import type { SectionProps } from './ui/Section.js'
import { ContactBlock } from './blocks/contact/Component.js'
import { CtaBlock } from './blocks/cta/Component.js'
import { EntryListBlock } from './blocks/entryList/Component.js'
import { FaqBlock } from './blocks/faq/Component.js'
import { FeatureGridBlock } from './blocks/featureGrid/Component.js'
import { GalleryBlock } from './blocks/gallery/Component.js'
import { HeroBlock } from './blocks/hero/Component.js'
import { LogosBlock } from './blocks/logos/Component.js'
import { PricingBlock } from './blocks/pricing/Component.js'
import { RichTextBlock } from './blocks/richText/Component.js'
import { StatsBlock } from './blocks/stats/Component.js'
import { StepsBlock } from './blocks/steps/Component.js'
import { TeamBlock } from './blocks/team/Component.js'
import { TestimonialsBlock } from './blocks/testimonials/Component.js'
import { TextMediaBlock } from './blocks/textMedia/Component.js'
import { buttonClass } from './ui/Button.js'
import { Card } from './ui/Card.js'
import { CMSLink } from './ui/CMSLink.js'
import { Container } from './ui/Container.js'
import { Media } from './ui/Media.js'
import { Section, SECTION_BACKGROUNDS } from './ui/Section.js'
import { SectionHeader } from './ui/SectionHeader.js'
/** The plugin's component for each library block, by default slug. */
export const LIBRARY_BLOCK_COMPONENTS = {
contact: ContactBlock,
cta: CtaBlock,
entryList: EntryListBlock,
faq: FaqBlock,
featureGrid: FeatureGridBlock,
gallery: GalleryBlock,
hero: HeroBlock,
logos: LogosBlock,
pricing: PricingBlock,
richText: RichTextBlock,
stats: StatsBlock,
steps: StepsBlock,
team: TeamBlock,
testimonials: TestimonialsBlock,
textMedia: TextMediaBlock,
} as const
export type BlockRegistryOptions = {
/** Section backgrounds (`settings.background` values) → classes, merged over the defaults. */
backgrounds?: Record<string, string>
/** Classes per block part, replacing that part's defaults: `{ faq: { item: 'border-b border-border' } }`. */
classNames?: Partial<Record<LibraryBlockSlug, PartClasses>>
/** Replace a block's component. It gets the same props (data, locale, isFirst, ui, ctx, classNames). */
components?: Partial<Record<LibraryBlockSlug, ComponentType<never>>>
/** The project's own blocks, in the same registry. */
extra?: BlockComponentMap
/** Turn on only these library blocks. Default: all 15 (an unused entry costs nothing). */
only?: readonly LibraryBlockSlug[]
/** Renamed slugs (BlockOptions `slug`), so the registry key matches the stored blockType. */
slugs?: Partial<Record<LibraryBlockSlug, string>>
/** Swap UI primitives for every library block (e.g. the project's own Media). */
ui?: Partial<BlockUi>
} & Omit<BlockContext, 'content' | 'lightbox'> & Partial<Pick<BlockContext, 'lightbox'>>
/**
* The `blockType → component` map for RenderBlocks / createPageRoute, with the library
* blocks bound to the project's lib/content and options:
*
* // src/blocks/registry.ts
* export const blockRegistry = createBlockRegistry(content, { sendForm, extra: { timeline: Timeline } })
*
* Everything is bound on the server, so no function crosses to the client.
*/
export function createBlockRegistry(content: BlockContent, options: BlockRegistryOptions = {}): BlockComponentMap {
const { backgrounds, classNames = {}, components = {}, extra = {}, only, slugs = {}, ui: own = {}, ...rest } = options
const ctx: BlockContext = { ...rest, content, lightbox: rest.lightbox ?? true }
const ui = buildUi(ctx, own, backgrounds)
const map: BlockComponentMap = {}
for (const slug of only ?? (Object.keys(LIBRARY_BLOCK_COMPONENTS) as LibraryBlockSlug[])) {
const Block = (components[slug] ?? LIBRARY_BLOCK_COMPONENTS[slug]) as ComponentType<Record<string, unknown>>
const bound = (props: Record<string, unknown>) => <Block {...props} classNames={classNames[slug]} ctx={ctx} ui={ui} />
bound.displayName = `Library(${slug})`
map[slugs[slug] ?? slug] = bound
}
return { ...map, ...extra }
}
/** The plugin's primitives, with lib/content's resolveLink and the project's buttons and backgrounds bound in. */
function buildUi(ctx: BlockContext, own: Partial<BlockUi>, backgrounds?: Record<string, string>): BlockUi {
const buttons = own.buttonClass ?? buttonClass
const sectionBackgrounds = { ...SECTION_BACKGROUNDS, ...backgrounds }
const BoundLink = (props: CMSLinkProps) => <CMSLink {...props} buttonClass={buttons} Link={ctx.Link} resolve={ctx.content.resolveLink} />
const BoundMedia = (props: MediaProps) => <Media {...props} Image={ctx.Image} />
const BoundSection = (props: SectionProps) => <Section backgrounds={sectionBackgrounds} {...props} />
return {
buttonClass: buttons,
Card: own.Card ?? Card,
CMSLink: own.CMSLink ?? BoundLink,
Container: own.Container ?? Container,
Media: own.Media ?? BoundMedia,
Section: own.Section ?? BoundSection,
SectionHeader: own.SectionHeader ?? SectionHeader,
}
}
+22
View File
@@ -0,0 +1,22 @@
import type { SelectField } from 'payload'
import { adminText } from './define.js'
/** Column count for grids, in the sidebar. Values are words, so they are valid GraphQL enum names. */
export const COLUMNS = ['two', 'three', 'four'] as const
export type Columns = (typeof COLUMNS)[number]
export function columnsField(defaultValue: Columns = 'three'): SelectField {
return {
name: 'columns',
type: 'select',
admin: { position: 'sidebar' },
defaultValue,
label: adminText('Columns', 'Kolumny'),
options: [
{ label: adminText('Two', 'Dwie'), value: 'two' },
{ label: adminText('Three', 'Trzy'), value: 'three' },
{ label: adminText('Four', 'Cztery'), value: 'four' },
],
}
}
@@ -0,0 +1,101 @@
import type { LibraryBlockSlug } from '../types.js'
/** A seed value: the same in every locale, or `{ pl, en }` per locale (createSeeder). */
export type TemplateValue = Record<string, unknown> | string
/** One block of a template: its library slug and its seed data. */
export type TemplateBlock = { blockType: LibraryBlockSlug } & Record<string, unknown>
export type TemplateOptions = {
/**
* The library blocks the project turned on, with renamed slugs — `libraryBlockSlugs(options)`.
* A block that is off is left out (and named in a warning). Default: every block, default slugs.
*/
blocks?: Partial<Record<LibraryBlockSlug, string>>
/** The project's default locale — buttons link to pages by their slug in it. Default 'pl'. */
defaultLocale?: string
/** Reorder, drop or add sections: `(blocks) => blocks`. Runs after `overrides`. */
layout?: (blocks: TemplateBlock[]) => TemplateBlock[]
/** Default-locale slugs of the pages the buttons link to, when they differ from the templates' own. */
linkTo?: Partial<Record<'about' | 'contact' | 'home', string>>
/** Data merged over a block's template data, by library slug: `{ hero: { header: { heading: { pl, en } } } }`. */
overrides?: Partial<Record<LibraryBlockSlug, Record<string, unknown>>>
/** The page address per locale. */
slug?: TemplateValue
/** The page title per locale. */
title?: TemplateValue
}
/** A page for `seed.upsertBySlug('pages', [...])`. */
export type TemplatePage = { layout: Record<string, unknown>[]; slug: TemplateValue; title: TemplateValue }
/** The templates' own page slugs, by page. */
export const TEMPLATE_SLUGS = {
about: { en: 'about', pl: 'o-nas' },
contact: { en: 'contact', pl: 'kontakt' },
home: { en: 'home', pl: 'start' },
}
/** A `{ $page }` reference to another template page, in the project's default locale. */
export function pageRef(target: keyof typeof TEMPLATE_SLUGS, options: TemplateOptions = {}): { $page: string } {
const locale = options.defaultLocale ?? 'pl'
const own = TEMPLATE_SLUGS[target] as Record<string, string>
return { $page: options.linkTo?.[target] ?? own[locale] ?? own.en }
}
/** Text in both languages the templates ship. */
export const tx = (en: string, pl: string) => ({ en, pl })
/** A placeholder only the client can fill — it shows up in the seed's [TO FILL] list. */
export const fill = (en: string, pl: string) => tx(`[TO FILL: ${en}]`, `[TO FILL: ${pl}]`)
export const header = (heading: Record<string, string>, intro?: Record<string, string>, eyebrow?: Record<string, string>) => ({
...(eyebrow ? { eyebrow } : {}),
heading,
...(intro ? { intro } : {}),
})
/** A rich text value with one paragraph per locale. */
export function richText(text: Record<string, string>): Record<string, unknown> {
const doc = (t: string) => ({
root: {
type: 'root',
children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: t, version: 1 }], direction: 'ltr', format: '', indent: 0, textFormat: 0, version: 1 }],
direction: 'ltr',
format: '',
indent: 0,
version: 1,
},
})
return Object.fromEntries(Object.entries(text).map(([locale, t]) => [locale, doc(t)]))
}
/** A rich text value with h2 headings and paragraphs, per locale: [[heading, paragraph], …]. */
export function sections(parts: { en: [string, string][]; pl: [string, string][] }): Record<string, unknown> {
const text = (t: string) => ({ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: t, version: 1 })
const node = (type: 'heading' | 'paragraph', t: string) =>
type === 'heading'
? { type, children: [text(t)], direction: 'ltr', format: '', indent: 0, tag: 'h2', version: 1 }
: { type, children: [text(t)], direction: 'ltr', format: '', indent: 0, textFormat: 0, version: 1 }
const doc = (rows: [string, string][]) => ({
root: { type: 'root', children: rows.flatMap(([h, p]) => [node('heading', h), node('paragraph', p)]), direction: 'ltr', format: '', indent: 0, version: 1 },
})
return { en: doc(parts.en), pl: doc(parts.pl) }
}
/** Applies the options: overrides, renamed slugs, blocks that are off, the project's layout function. */
export function buildTemplate(name: string, defaults: { slug: TemplateValue; title: TemplateValue }, blocks: TemplateBlock[], options: TemplateOptions = {}): TemplatePage {
const merged = blocks.map((b) => ({ ...b, ...options.overrides?.[b.blockType] }) as TemplateBlock)
const arranged = options.layout ? options.layout(merged) : merged
const missing: string[] = []
const layout = arranged.flatMap((b) => {
const slug = options.blocks ? options.blocks[b.blockType] : b.blockType
if (!slug) {
missing.push(b.blockType)
return []
}
return [{ ...b, blockType: slug }]
})
if (missing.length) {console.warn(`[ipal] template ${name}: left out blocks that are off: ${missing.join(', ')}`)}
return { slug: options.slug ?? defaults.slug, layout, title: options.title ?? defaults.title }
}
@@ -0,0 +1,21 @@
import { about, blogIndex, contact, cookiePolicy, home, legal, notFound, post, service, services } from './pages.js'
/**
* Page templates: pages made of library blocks, with every text in English and Polish and
* [TO FILL: …] where only the client can write. Data for createSeeder:
*
* await seed.upsertBySlug('pages', [pageTemplates.home(), pageTemplates.contact({ form: { $form: 'Contact form' } })])
*
* After launch, seed only the pages you name — never every template.
*/
export const pageTemplates = { about, blogIndex, contact, cookiePolicy, home, legal, notFound, post, service, services }
/**
* Site settings → System pages, for `seed.fillGlobal('site-settings', systemPageRefs({ homepage: 'start' }))`
* (empty fields only). Values are default-locale page slugs.
*/
export function systemPageRefs(roles: Partial<Record<'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService', string>>): Record<string, { $page: string }> {
return Object.fromEntries(Object.entries(roles).flatMap(([role, slug]) => (slug ? [[role, { $page: slug }]] : [])))
}
export type { TemplateBlock, TemplateOptions, TemplatePage, TemplateValue } from './build.js'
@@ -0,0 +1,128 @@
import type { TemplateOptions, TemplatePage } from './build.js'
import { buildTemplate, fill, header, pageRef, richText, sections, TEMPLATE_SLUGS, tx } from './build.js'
const button = (label: Record<string, string>, page: { $page: string }, appearance = 'primary') => ({
link: { type: 'internal', appearance, label, page },
})
const pageHero = (heading: Record<string, string>, intro?: Record<string, string>) => ({ blockType: 'hero' as const, header: header(heading, intro), variant: 'page' })
const cta = (options?: TemplateOptions) => ({
blockType: 'cta' as const,
header: header(tx('Ready to talk about your project?', 'Porozmawiajmy o Twoim projekcie'), fill('one sentence why to get in touch', 'jedno zdanie, dlaczego warto się skontaktować')),
links: [button(tx('Contact us', 'Skontaktuj się'), pageRef('contact', options))],
variant: 'band',
})
const items = (n: number, make: (i: number) => Record<string, unknown>) => Array.from({ length: n }, (_, i) => make(i + 1))
/** Home: hero, logos, features, text and image, key figures, testimonials, FAQ, call to action. */
export function home(options?: TemplateOptions): TemplatePage {
return buildTemplate('home', { slug: TEMPLATE_SLUGS.home, title: tx('Home', 'Strona główna') }, [
{ blockType: 'hero', header: header(fill('main promise of the company', 'główna obietnica firmy'), fill('one or two sentences for whom and what', 'jedno–dwa zdania: dla kogo i co')), links: [button(tx('Contact us', 'Skontaktuj się'), pageRef('contact', options))], variant: 'split' },
{ blockType: 'logos', header: header(tx('They trust us', 'Zaufali nam')), variant: 'row' },
{ blockType: 'featureGrid', columns: 'three', header: header(tx('What we do', 'Czym się zajmujemy')), items: items(3, (i) => ({ heading: fill(`service ${i}`, `usługa ${i}`), text: fill('one sentence about it', 'jedno zdanie o niej') })), variant: 'cards' },
{ blockType: 'textMedia', content: richText(fill('who we are and how we work', 'kim jesteśmy i jak pracujemy')), header: header(tx('About us', 'O nas')), links: [button(tx('More about us', 'Więcej o nas'), pageRef('about', options), 'secondary')], variant: 'mediaRight' },
{ blockType: 'stats', items: items(3, (i) => ({ heading: fill(`figure ${i} label`, `opis liczby ${i}`), value: fill('number', 'liczba') })), variant: 'row' },
{ blockType: 'testimonials', header: header(tx('What our clients say', 'Co mówią klienci')), items: items(3, () => ({ heading: fill('client name', 'imię klienta'), quote: fill('real quote from a client', 'prawdziwy cytat od klienta') })), variant: 'grid' },
{ blockType: 'faq', header: header(tx('Frequently asked questions', 'Najczęstsze pytania')), items: items(4, (i) => ({ answer: fill(`answer ${i}`, `odpowiedź ${i}`), question: fill(`question ${i}`, `pytanie ${i}`) })), variant: 'single' },
cta(options),
], options)
}
/** About: page header, story, key figures, team, how we work, call to action. */
export function about(options?: TemplateOptions): TemplatePage {
return buildTemplate('about', { slug: TEMPLATE_SLUGS.about, title: tx('About us', 'O nas') }, [
pageHero(tx('About us', 'O nas'), fill('one sentence about the company', 'jedno zdanie o firmie')),
{ blockType: 'textMedia', content: richText(fill('the company story', 'historia firmy')), header: header(tx('Our story', 'Nasza historia')), variant: 'mediaLeft' },
{ blockType: 'stats', items: items(3, (i) => ({ heading: fill(`figure ${i} label`, `opis liczby ${i}`), value: fill('number', 'liczba') })), variant: 'cards' },
{ blockType: 'team', header: header(tx('Our team', 'Nasz zespół')), items: items(3, () => ({ heading: fill('name', 'imię i nazwisko'), text: fill('role', 'stanowisko') })), variant: 'grid' },
{ blockType: 'steps', header: header(tx('How we work', 'Jak pracujemy')), items: items(4, (i) => ({ heading: fill(`step ${i}`, `krok ${i}`), text: fill('what happens in it', 'co się w nim dzieje') })), variant: 'numbered' },
cta(options),
], options)
}
/** Services: page header, service cards, process, pricing, FAQ, call to action. */
export function services(options?: TemplateOptions): TemplatePage {
return buildTemplate('services', { slug: tx('services', 'uslugi'), title: tx('Services', 'Usługi') }, [
pageHero(tx('Services', 'Usługi'), fill('one sentence about the offer', 'jedno zdanie o ofercie')),
{ blockType: 'featureGrid', columns: 'three', items: items(6, (i) => ({ heading: fill(`service ${i}`, `usługa ${i}`), text: fill('one sentence about it', 'jedno zdanie o niej') })), variant: 'cards' },
{ blockType: 'steps', header: header(tx('How it works', 'Jak to działa')), items: items(3, (i) => ({ heading: fill(`step ${i}`, `krok ${i}`) })), variant: 'numbered' },
{ blockType: 'pricing', header: header(tx('Pricing', 'Cennik')), items: items(3, (i) => ({ heading: fill(`plan ${i}`, `pakiet ${i}`), price: fill('price', 'cena') })) },
{ blockType: 'faq', header: header(tx('Questions about our services', 'Pytania o usługi')), items: items(3, (i) => ({ answer: fill(`answer ${i}`, `odpowiedź ${i}`), question: fill(`question ${i}`, `pytanie ${i}`) })), variant: 'single' },
cta(options),
], options)
}
/** One service: hero, description, benefits, gallery, FAQ, contact. Pass `slug` and `title`. */
export function service(options?: { form?: unknown } & TemplateOptions): TemplatePage {
return buildTemplate('service', { slug: tx('service', 'usluga'), title: fill('service name', 'nazwa usługi') }, [
{ blockType: 'hero', header: header(fill('service name', 'nazwa usługi'), fill('what the client gets', 'co dostaje klient')), links: [button(tx('Ask for a quote', 'Zapytaj o wycenę'), pageRef('contact', options))], variant: 'split' },
{ blockType: 'textMedia', content: richText(fill('description of the service', 'opis usługi')), variant: 'mediaRight' },
{ blockType: 'featureGrid', columns: 'two', header: header(tx('What you get', 'Co zyskujesz')), items: items(4, (i) => ({ heading: fill(`benefit ${i}`, `korzyść ${i}`) })), variant: 'list' },
{ blockType: 'gallery', columns: 'three', header: header(tx('Our work', 'Nasze realizacje')), variant: 'grid' },
{ blockType: 'faq', items: items(3, (i) => ({ answer: fill(`answer ${i}`, `odpowiedź ${i}`), question: fill(`question ${i}`, `pytanie ${i}`) })), variant: 'single' },
...(options?.form ? [{ blockType: 'contact' as const, form: options.form, header: header(tx('Ask about this service', 'Zapytaj o tę usługę')), variant: 'formOnly' }] : []),
], options)
}
/** Contact: page header, the form with contact details, FAQ. `form`: `{ $form: 'Contact form' }`. */
export function contact(options: { form: unknown } & TemplateOptions): TemplatePage {
return buildTemplate('contact', { slug: TEMPLATE_SLUGS.contact, title: tx('Contact', 'Kontakt') }, [
pageHero(tx('Contact', 'Kontakt'), fill('how fast you answer', 'jak szybko odpowiadacie')),
{ blockType: 'contact', content: richText(fill('who to contact and when', 'z kim i kiedy się kontaktować')), form: options.form, variant: 'formWithDetails' },
{ blockType: 'faq', header: header(tx('Before you write', 'Zanim napiszesz')), items: items(3, (i) => ({ answer: fill(`answer ${i}`, `odpowiedź ${i}`), question: fill(`question ${i}`, `pytanie ${i}`) })), variant: 'single' },
], options)
}
/** Blog index: the archive page (its entries come from createPageRoute) with a header and a call to action. */
export function blogIndex(options?: TemplateOptions): TemplatePage {
return buildTemplate('blogIndex', { slug: tx('blog', 'blog'), title: tx('Blog', 'Blog') }, [pageHero(tx('Blog', 'Blog'), fill('what the posts are about', 'o czym są wpisy')), cta(options)], options)
}
/** Post body for a posts collection with a `layout` field: text with a table of contents, more posts, call to action. */
export function post(options?: TemplateOptions): TemplatePage {
return buildTemplate('post', { slug: fill('post-address', 'adres-wpisu'), title: fill('post title', 'tytuł wpisu') }, [
{ blockType: 'richText', content: richText(fill('post text', 'treść wpisu')), tableOfContents: { label: tx('Contents', 'Spis treści'), show: true }, variant: 'narrow' },
{ blockType: 'entryList', collection: 'posts', header: header(tx('Read also', 'Przeczytaj też')), limit: 3, mode: 'latest', variant: 'cards' },
cta(options),
], options)
}
const LEGAL = {
privacyPolicy: { slug: tx('privacy-policy', 'polityka-prywatnosci'), title: tx('Privacy policy', 'Polityka prywatności') },
termsOfService: { slug: tx('terms', 'regulamin'), title: tx('Terms of service', 'Regulamin') },
}
/** A legal page (privacy policy, terms): header and text with a table of contents. Structure only — the wording comes from the client. */
export function legal(role: keyof typeof LEGAL, options?: TemplateOptions): TemplatePage {
const { slug, title } = LEGAL[role]
return buildTemplate(role, { slug, title }, [
pageHero(title),
{
blockType: 'richText',
content: sections({
en: [['[TO FILL: section heading]', '[TO FILL: text provided by the client or their lawyer]']],
pl: [['[TO FILL: nagłówek sekcji]', '[TO FILL: treść od klienta lub prawnika]']],
}),
tableOfContents: { label: tx('Contents', 'Spis treści'), show: true },
variant: 'narrow',
},
], options)
}
/** Cookie policy: header and text; put the cookie table (CookieTable) on it in your page view or own block. */
export function cookiePolicy(options?: TemplateOptions): TemplatePage {
return buildTemplate('cookiePolicy', { slug: tx('cookie-policy', 'polityka-cookies'), title: tx('Cookie policy', 'Polityka cookies') }, [
pageHero(tx('Cookie policy', 'Polityka cookies')),
{ blockType: 'richText', content: richText(fill('cookie policy text from the client', 'treść polityki cookies od klienta')), tableOfContents: { show: false }, variant: 'narrow' },
], options)
}
/** 404: a small header with a button home. */
export function notFound(options?: TemplateOptions): TemplatePage {
return buildTemplate('notFound', { slug: tx('page-not-found', 'nie-znaleziono'), title: tx('Page not found', 'Nie znaleziono strony') }, [
{ blockType: 'hero', header: header(tx('Page not found', 'Nie znaleziono strony'), tx('The address may be mistyped or the page was moved.', 'Adres może być błędny albo strona została przeniesiona.')), links: [button(tx('Go to the home page', 'Przejdź na stronę główną'), pageRef('home', options))], variant: 'page' },
], options)
}
+23
View File
@@ -0,0 +1,23 @@
/**
* Visitor-facing texts the library blocks render themselves (everything else comes from the panel).
* English and Polish ship; another language, or other words: createBlockRegistry({ texts }).
*/
export type BlockTexts = {
/** Screen-reader text for a star rating. {value} = the rating. */
rating: string
/** Screen-reader text after a step number. {value} = the number. */
step: string
}
export const BLOCK_TEXTS: Record<'en' | 'pl', BlockTexts> = {
en: { rating: 'Rated {value} out of 5', step: 'Step {value}' },
pl: { rating: 'Ocena: {value} na 5', step: 'Krok {value}' },
}
/** The texts for a page locale: the project's own first, then Polish for `pl…`, else English. */
export function blockTexts(locale: string, own?: Partial<Record<string, Partial<BlockTexts>>>): BlockTexts {
const base = locale.toLowerCase().startsWith('pl') ? BLOCK_TEXTS.pl : BLOCK_TEXTS.en
return { ...base, ...own?.[locale] }
}
export const fillText = (text: string, value: number | string) => text.replace('{value}', String(value))
+33
View File
@@ -0,0 +1,33 @@
/**
* Sketches of the library blocks for the block picker — inline SVG data URLs, so no route or
* static folder is needed. Neutral greys; the picker shows them at about 120 × 80.
*/
type Shape = [x: number, y: number, w: number, h: number, tone?: 0 | 1 | 2]
const TONES = ['#d4d4d8', '#a1a1aa', '#71717a']
const SKETCHES: Record<string, Shape[]> = {
contact: [[8, 10, 40, 6, 2], [8, 22, 36, 4], [8, 30, 30, 4], [60, 8, 52, 10], [60, 22, 52, 10], [60, 36, 52, 22], [60, 62, 24, 10, 2]],
cta: [[10, 24, 100, 32, 1], [24, 32, 60, 6, 2], [24, 44, 28, 6, 0]],
entryList: [[8, 10, 30, 26, 1], [8, 40, 30, 4], [45, 10, 30, 26, 1], [45, 40, 30, 4], [82, 10, 30, 26, 1], [82, 40, 30, 4]],
faq: [[10, 12, 100, 10, 1], [10, 28, 100, 10, 1], [10, 44, 100, 10, 1], [10, 60, 100, 10, 1]],
featureGrid: [[8, 12, 30, 30, 1], [45, 12, 30, 30, 1], [82, 12, 30, 30, 1], [8, 48, 30, 4], [45, 48, 30, 4], [82, 48, 30, 4]],
gallery: [[8, 10, 32, 28, 1], [44, 10, 32, 28, 2], [80, 10, 32, 28, 1], [8, 42, 32, 28, 2], [44, 42, 32, 28, 1], [80, 42, 32, 28, 2]],
hero: [[8, 20, 48, 10, 2], [8, 36, 40, 4], [8, 48, 22, 8, 2], [64, 10, 48, 60, 1]],
logos: [[8, 34, 20, 12, 1], [32, 34, 20, 12, 1], [56, 34, 20, 12, 1], [80, 34, 20, 12, 1], [104, 34, 8, 12, 1]],
pricing: [[8, 10, 30, 60, 0], [45, 6, 30, 68, 2], [82, 10, 30, 60, 0]],
richText: [[24, 10, 72, 6, 2], [24, 22, 72, 4], [24, 30, 72, 4], [24, 38, 60, 4], [24, 50, 72, 4], [24, 58, 52, 4]],
stats: [[8, 26, 24, 14, 2], [38, 26, 24, 14, 2], [68, 26, 24, 14, 2], [8, 44, 24, 4], [38, 44, 24, 4], [68, 44, 24, 4]],
steps: [[10, 16, 10, 10, 2], [10, 36, 10, 10, 2], [10, 56, 10, 10, 2], [28, 18, 80, 6], [28, 38, 70, 6], [28, 58, 76, 6]],
team: [[12, 12, 24, 24, 1], [48, 12, 24, 24, 1], [84, 12, 24, 24, 1], [12, 42, 24, 4, 2], [48, 42, 24, 4, 2], [84, 42, 24, 4, 2]],
testimonials: [[10, 14, 46, 40, 0], [64, 14, 46, 40, 0], [16, 60, 10, 10, 1], [70, 60, 10, 10, 1]],
textMedia: [[8, 20, 48, 6, 2], [8, 32, 44, 4], [8, 40, 40, 4], [8, 48, 44, 4], [64, 10, 48, 60, 1]],
}
/** A data URL of the block's sketch (a plain frame for an unknown slug). */
export function blockThumbnail(slug: string): string {
const shapes = SKETCHES[slug] ?? []
const rects = shapes.map(([x, y, w, h, tone = 0]) => `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="2" fill="${TONES[tone]}"/>`).join('')
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 80"><rect width="120" height="80" rx="4" fill="#f4f4f5"/>${rects}</svg>`
return `data:image/svg+xml,${encodeURIComponent(svg)}`
}
+77
View File
@@ -0,0 +1,77 @@
import type { Block, Field } from 'payload'
import type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from '../blocks/sectionFields.js'
import type { BuildLinksFieldOptions } from '../links/buildLinkField.js'
/** Slugs of the library blocks (the default slugs; a project may rename them with `slug`). */
export type LibraryBlockSlug =
| 'contact'
| 'cta'
| 'entryList'
| 'faq'
| 'featureGrid'
| 'gallery'
| 'hero'
| 'logos'
| 'pricing'
| 'richText'
| 'stats'
| 'steps'
| 'team'
| 'testimonials'
| 'textMedia'
/**
* `fields` = one structure, text per language (default): text, rich text and images that differ
* per language carry `localized: true`.
* `layout` = the project localizes the whole `layout` field, so the block's own fields drop `localized`.
*/
export type BlockLocalization = 'fields' | 'layout'
/** What every library block builder accepts. The project's values win (CLAUDE.md main rule). */
export type BlockOptions = {
/** Merged over the block's `admin`. */
admin?: Block['admin']
/** Merged over the block's `custom`. */
custom?: Record<string, unknown>
/** Replace the fields, or `(defaults) => fields` to add, change or drop some. */
fields?: ((defaults: Field[]) => Field[]) | Field[]
/** Options for the shared section header (`buildSectionHeaderField`). `false` drops it. */
header?: false | SectionHeaderFieldOptions
/** Generated TypeScript type name. Default `<Name>Block`, e.g. `FaqBlock`. */
interfaceName?: string
/** Panel name of the block. */
labels?: Block['labels']
/** Options for the section buttons (`buildLinksField`). `false` drops them. */
links?: BuildLinksFieldOptions | false
/** See BlockLocalization. Default 'fields'. */
localization?: BlockLocalization
/** Max items in the block's `items` array. */
maxItems?: number
/** Options for the section settings (`buildSectionSettingsField`), e.g. project backgrounds. */
settings?: SectionSettingsFieldOptions
/** Block slug (blockType). Change it to keep an existing slug, e.g. `reviews` for testimonials. */
slug?: string
/** Picture in the block picker: `true` = the plugin's sketch of the block (inline SVG, no route), a URL of your own, or off (default). */
thumbnail?: boolean | string
/**
* Variants the editor may pick: a subset of the block's values, extra values of the project's own
* (`{ label, value }`), or `false` to drop the select (the first default variant is used).
*/
variants?: false | readonly (string | VariantOption)[]
}
/** An option of the `variant` select. */
export type VariantOption = { label: { [lang: string]: string; en: string; pl: string } | string; value: string }
/** A block builder: options → a Payload block. */
export type BlockBuilder<O extends BlockOptions = BlockOptions> = (options?: O) => Block
/**
* `true` = on with the defaults; an options object = on with those options;
* `(block) => block` = on, and the function takes the finished block over; `false`/missing = off.
*/
export type LibraryBlockSetting<O extends BlockOptions = BlockOptions> = ((block: Block) => Block) | boolean | O
/** Shared defaults for every block passed to `libraryBlocks`. */
export type LibraryBlocksShared = Pick<BlockOptions, 'localization' | 'settings'>
+20
View File
@@ -0,0 +1,20 @@
import type { ComponentType, ReactNode } from 'react'
/** next/link, passed in by the project (the plugin never imports next/*). */
export type LinkComponent = ComponentType<{ children?: ReactNode; className?: string; href: string; rel?: string; target?: string }>
/** An internal link through `Link` when the project passed one, otherwise a plain <a>. */
export function Anchor({ children, className, href, internal, Link, targetProps }: { children: ReactNode; className?: string; href: string; internal: boolean; Link?: LinkComponent; targetProps: Record<string, string> }) {
if (internal && Link) {
return (
<Link className={className} href={href} {...targetProps}>
{children}
</Link>
)
}
return (
<a className={className} href={href} {...targetProps}>
{children}
</a>
)
}
+19
View File
@@ -0,0 +1,19 @@
/**
* Button looks by link appearance — the one place buttons are styled. Token utilities only.
* Swap it with createBlockRegistry({ ui: { buttonClass } }) or extend BUTTON_CLASSES' keys
* with the project's own appearance names.
*/
const BASE =
'inline-flex items-center justify-center gap-2 rounded-control px-5 py-3 font-medium leading-none transition-colors duration-fast ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus'
export const BUTTON_CLASSES: Record<string, string> = {
link: 'font-medium text-link underline underline-offset-4 hover:text-link-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus',
primary: `${BASE} bg-primary text-on-primary hover:bg-primary-hover`,
secondary: `${BASE} border border-border-strong bg-transparent text-fg hover:bg-hover`,
}
/** Classes for a link appearance; an unknown name gets the primary look. No appearance → ''. */
export function buttonClass(appearance?: null | string): string {
if (!appearance) {return ''}
return BUTTON_CLASSES[appearance] ?? BUTTON_CLASSES.primary
}
+29
View File
@@ -0,0 +1,29 @@
import type { BlockUi } from '../context.js'
import type { LinksData } from '../data.js'
import { cx } from './cx.js'
/** The section's buttons in a row; nothing when there are none. */
export function Buttons({ className, CMSLink, links, locale }: { className?: string; CMSLink: BlockUi['CMSLink']; links?: LinksData; locale: string }) {
const rows = (links ?? []).filter((row) => row.link)
if (!rows.length) {return null}
return (
<div className={cx('mt-8 flex flex-wrap items-center gap-3', className)}>
{rows.map((row, i) => (
<CMSLink key={row.id ?? i} link={row.link} locale={locale} />
))}
</div>
)
}
/** The id of a block's heading (aria-labelledby), when it has one. */
export function headingId(block: { blockType: string; header?: { heading?: null | string } | null; id?: null | string }): string | undefined {
return block.header?.heading && block.id ? `${block.blockType}-${block.id}-heading` : undefined
}
/** Grid columns from the `columns` select. */
export const GRID_COLUMNS: Record<string, string> = {
four: 'sm:grid-cols-2 lg:grid-cols-4',
three: 'sm:grid-cols-2 lg:grid-cols-3',
two: 'sm:grid-cols-2',
}
+40
View File
@@ -0,0 +1,40 @@
import type { ReactNode } from 'react'
import type { ResolvedLink } from '../../links/resolveNav.js'
import type { LinkData } from '../data.js'
import type { LinkComponent } from './Anchor.js'
import { Anchor } from './Anchor.js'
import { buttonClass as defaultButtonClass } from './Button.js'
import { cx } from './cx.js'
export type ResolveLink = (link: LinkData, locale: string) => null | Promise<null | ResolvedLink> | ResolvedLink
export type CMSLinkProps = {
/** For a link that wraps something (a card, an image): the content instead of the label. */
children?: ReactNode
className?: string
link: LinkData
locale: string
}
/** The plugin's link: `resolve` (lib/content `resolveLink`), `buttonClass` and `Link` (next/link) are bound by createBlockRegistry. */
export async function CMSLink({
buttonClass = defaultButtonClass,
children,
className,
link,
Link,
locale,
resolve,
}: { buttonClass?: (appearance?: null | string) => string; Link?: LinkComponent; resolve: ResolveLink } & CMSLinkProps) {
const l = await resolve(link, locale)
const content = children ?? l?.label
if (!l || !content) {return null}
const cls = cx(buttonClass(l.appearance), className) || undefined
return (
<Anchor className={cls} href={l.href} internal={l.internal} Link={Link} targetProps={l.targetProps}>
{content}
</Anchor>
)
}
+13
View File
@@ -0,0 +1,13 @@
import type { ElementType, ReactNode } from 'react'
import { cx } from './cx.js'
export const CARD_CLASS = 'flex flex-col rounded-card border border-border bg-surface text-fg shadow-sm'
export const CARD_INTERACTIVE_CLASS = 'relative transition-shadow duration-fast ease-out hover:shadow-md focus-within:shadow-md'
export type CardProps = { as?: ElementType; children: ReactNode; className?: string; interactive?: boolean }
/** A card surface. `interactive` = the whole card is a link (hover and focus lift). */
export function Card({ as: As = 'article', children, className, interactive = false }: CardProps) {
return <As className={cx(CARD_CLASS, interactive && CARD_INTERACTIVE_CLASS, className)}>{children}</As>
}
@@ -0,0 +1,18 @@
import type { ReactNode } from 'react'
import { cx } from './cx.js'
export type ContainerWidth = 'default' | 'narrow' | 'wide'
export const CONTAINER_WIDTHS: Record<ContainerWidth, string> = {
default: 'max-w-container',
narrow: 'max-w-narrow',
wide: 'max-w-container-wide',
}
export type ContainerProps = { children: ReactNode; className?: string; width?: ContainerWidth }
/** The page column: centred, the site's max width, side gutters. */
export function Container({ children, className, width = 'default' }: ContainerProps) {
return <div className={cx('mx-auto w-full px-gutter', CONTAINER_WIDTHS[width], className)}>{children}</div>
}
+40
View File
@@ -0,0 +1,40 @@
import type { ComponentType } from 'react'
import type { MediaImageProps, VideoMode } from '../../media/mediaProps.js'
import type { MediaValue } from '../data.js'
import { MEDIA_SIZES, mediaImageProps, videoProps } from '../../media/mediaProps.js'
/** next/image, passed in by the project (the plugin never imports next/*). */
export type ImageComponent = ComponentType<{ className?: string } & MediaImageProps>
export type MediaProps = {
/** Override the document's alt text — `''` for a decorative image. */
alt?: string
className?: string
poster?: MediaValue
/** Only the first visible image of the page (the LCP image). */
priority?: boolean
resource: MediaValue
/** The width on screen (MEDIA_SIZES.*). Without it the full width downloads. */
sizes?: string
videoMode?: VideoMode
}
/**
* Every image or video of the library blocks. With `Image` (next/image, bound by createBlockRegistry)
* images are optimized with blur-up; without it a plain <img> with width, height, lazy loading and focal point.
*/
export function Media({ alt, className, Image, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
const video = videoProps(resource, { mode: videoMode, poster })
if (video) {
// Captions are not stored with media uploads; a project that needs them swaps Media (ui option).
// eslint-disable-next-line jsx-a11y/media-has-caption
return <video {...video} aria-hidden={videoMode === 'background' ? true : undefined} className={className} />
}
const img = mediaImageProps(resource, { priority, sizes, ...(alt !== undefined ? { alt } : {}) })
if (!img) {return null}
if (Image) {return <Image {...img} className={className} />}
const { blurDataURL: _blur, placeholder: _placeholder, preload: _preload, ...plain } = img
return <img {...plain} alt={plain.alt} className={className} decoding="async" />
}
+47
View File
@@ -0,0 +1,47 @@
import type { ReactNode } from 'react'
import type { SectionSettingsData } from '../data.js'
import type { ContainerWidth } from './Container.js'
import { Container } from './Container.js'
import { cx } from './cx.js'
/** Section backgrounds (`settings.background`) → token utilities. Add project values with createBlockRegistry({ backgrounds }). */
export const SECTION_BACKGROUNDS: Record<string, string> = {
default: 'bg-bg text-fg',
inverted: 'bg-inverse text-on-inverse',
muted: 'bg-surface-muted text-fg',
}
/** `data-surface` per background — the token preset re-maps text, links, borders and focus inside `inverse`. */
const SURFACES: Record<string, string> = { inverted: 'inverse', muted: 'muted' }
export type SectionProps = {
backgrounds?: Record<string, string>
/** The block's slug — `data-ipal-block` for project CSS and tests. */
block: string
children: ReactNode
className?: string
/** Smaller vertical spacing (CTA band, logos). */
compact?: boolean
/** The heading's id, for aria-labelledby. */
labelledBy?: string
settings?: null | SectionSettingsData
width?: ContainerWidth
}
/** One <section> per block: anchor id, background, spacing, the page column. */
export function Section({ backgrounds = SECTION_BACKGROUNDS, block, children, className, compact = false, labelledBy, settings, width }: SectionProps) {
const background = settings?.background ?? 'default'
return (
<section
aria-labelledby={labelledBy}
className={cx(compact ? 'py-section-sm' : 'py-section', backgrounds[background] ?? backgrounds.default, className)}
data-ipal-block={block}
data-surface={SURFACES[background]}
id={settings?.anchor || undefined}
>
<Container width={width}>{children}</Container>
</section>
)
}
@@ -0,0 +1,35 @@
import type { SectionHeaderData } from '../data.js'
import { cx } from './cx.js'
export type HeadingLevel = 'h1' | 'h2'
export type SectionHeaderProps = {
align?: 'center' | 'start'
/** h1 only for the first section of the page (`isFirst`). */
as?: HeadingLevel
className?: string
/** Larger heading for a hero. */
display?: boolean
header?: null | SectionHeaderData
/** The heading's id — the section's aria-labelledby. */
id?: string
}
const SIZES: Record<HeadingLevel, string> = { h1: 'text-h1', h2: 'text-h2' }
/** Eyebrow, heading and introduction from the panel. Nothing renders when all three are empty. */
export function SectionHeader({ id, align = 'start', as: H = 'h2', className, display = false, header }: SectionHeaderProps) {
if (!header?.heading && !header?.eyebrow && !header?.intro) {return null}
return (
<header className={cx('mb-10 flex max-w-measure flex-col gap-3', align === 'center' && 'mx-auto items-center text-center', className)}>
{header.eyebrow ? <p className="text-sm font-medium uppercase tracking-heading text-fg-muted">{header.eyebrow}</p> : null}
{header.heading ? (
<H className={cx('font-heading leading-heading tracking-heading text-fg-strong', display ? 'text-display' : SIZES[H])} id={id}>
{header.heading}
</H>
) : null}
{header.intro ? <p className="text-lead text-fg-muted">{header.intro}</p> : null}
</header>
)
}
@@ -0,0 +1,22 @@
import type { ReactNode } from 'react'
import type { LinkData } from '../data.js'
import type { LinkComponent } from './Anchor.js'
import type { ResolveLink } from './CMSLink.js'
import { Anchor } from './Anchor.js'
/**
* A card title that links when its link leads somewhere, and stays plain text when it doesn't
* (a deleted page, an entry without an archive). `stretch` makes the whole card the click area.
*/
export async function TitleLink({ children, link, Link, locale, resolve, stretch = true }: { children: ReactNode; link: LinkData; Link?: LinkComponent; locale: string; resolve: ResolveLink; stretch?: boolean }) {
const l = link ? await resolve(link, locale) : null
if (!l) {return <>{children}</>}
const className = `${stretch ? 'after:absolute after:inset-0 ' : ''}hover:text-link focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus`
return (
<Anchor className={className} href={l.href} internal={l.internal} Link={Link} targetProps={l.targetProps}>
{children}
</Anchor>
)
}
+11
View File
@@ -0,0 +1,11 @@
/** Joins class names, skipping empty ones. */
export function cx(...classes: (false | null | string | undefined)[]): string {
return classes.filter(Boolean).join(' ')
}
/** A block's classes by part; the project's `classNames` replace a part's defaults. */
export type PartClasses<P extends string = string> = Partial<Record<P, string>>
export function parts<P extends string>(defaults: Record<P, string>, overrides?: PartClasses): Record<P, string> {
return overrides ? ({ ...defaults, ...overrides } as Record<P, string>) : defaults
}
+6 -2
View File
@@ -91,8 +91,12 @@ export function buildLinkField({
{
name: 'newTab',
type: 'checkbox',
admin: { style: { alignSelf: 'flex-end' }, width: '50%' },
label: { en: 'Open in new tab', pl: 'Otwórz w nowej karcie' },
admin: {
description: { en: 'Opens the link in a new browser tab.', pl: 'Otwiera link w nowej karcie przeglądarki.' },
style: { alignSelf: 'flex-end' },
width: '50%',
},
label: { en: 'New tab', pl: 'Nowa karta' },
},
],
},
+1 -1
View File
@@ -76,7 +76,7 @@ export function buildTableOfContentsField({ name = 'tableOfContents' }: { name?:
pl: 'Lista nagłówków sekcji z linkami do nich, przydatna na długich stronach.',
},
},
label: { en: 'Show table of contents', pl: 'Pokaż spis treści' },
label: { en: 'Show contents', pl: 'Pokaż spis treści' },
},
{
name: 'label',
+19 -2
View File
@@ -80,6 +80,8 @@ export type SeederOptions = {
* Refused outside a local database unless `guard.forceOnlyLocal: false`.
*/
force?: boolean
/** Collection `{ $form: '<title>' }` references resolve in. Default 'forms'. */
formsCollection?: string
/**
* The production guard. false turns it off (the project takes the risk).
* `update` on production (NODE_ENV=production) or a non-local database is
@@ -164,10 +166,16 @@ const defaultLog = (line: string) => {
type Item = { data: Record<string, unknown>; key: Record<string, number | string>; label: string; ref: string }
type Planned = { action?: 'create' | 'update'; id?: number | string; result?: SeedResult } & Item
const formRef = (v: object): string | undefined => {
const ref = (v as { $form?: unknown }).$form
return typeof ref === 'string' ? ref : undefined
}
/** True when the value holds a { $page } or { $form } reference — such fields are written once refs resolve. */
const hasRef = (v: unknown): boolean =>
Array.isArray(v)
? v.some(hasRef)
: !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || Object.values(v).some(hasRef))
: !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || formRef(v) !== undefined || Object.values(v).some(hasRef))
export function createSeeder(payload: BasePayload, options: SeederOptions = {}): Seeder {
const env = process.env
@@ -180,6 +188,7 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
const hashField = options.editCheck?.hashField ?? defaultHashField()
const untouchedSeconds = options.editCheck?.untouchedSeconds ?? defaultUntouchedSeconds()
const pagesCollection = options.pagesCollection ?? 'pages'
const formsCollection = options.formsCollection ?? 'forms'
const context = { ...DEFAULT_CONTEXT, ...options.context }
const onlyList = options.only ?? (env.SEED_ONLY ? env.SEED_ONLY.split(',') : undefined)
const only = onlyList ? onlyList.map((r) => r.trim()).filter(Boolean) : null
@@ -255,12 +264,20 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
}
/**
* Replaces { $page: slug } with the page id (a placeholder for a planned create in a dry run).
* Replaces { $page: slug } with the page id (a placeholder for a planned create in a dry run)
* and { $form: title } with the form id (forms are seeded before the pages that use them).
* lenient: an unknown page gives a placeholder instead of an error (edit check before pass 1).
*/
const resolveRefs = async (v: unknown, lenient = false): Promise<unknown> => {
if (Array.isArray(v)) {return Promise.all(v.map((x) => resolveRefs(x, lenient)))}
if (!v || typeof v !== 'object') {return v}
const form = formRef(v)
if (form !== undefined) {
const id = await findId(formsCollection, { title: form })
if (id !== undefined) {return id}
if (lenient || dryRun) {return `(form:${form})`}
throw new Error(`$form "${form}" not found — seed that form first or create it in the panel`)
}
const ref = (v as { $page?: unknown }).$page
if (typeof ref === 'string') {
let id = pageIds.get(ref)
+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 },
],