Merge claude/block-library-build: block library (15 blocks, /blocks, /blocks/rsc, /templates, ipal-blocks)

Fifteen opt-in library blocks (libraryBlocks({ ... }) from /blocks, rendered with
createBlockRegistry from /blocks/rsc), templates (/templates), the ipal-blocks
eject CLI and blockLibraryManifest; block sources ship in src/modules/block-library
for eject. Nothing is on by default; fields, variants, slugs, labels, part
classes, primitives and components are overridable. Seeder { $form } fix. Label
changes "New tab" / "Show contents" (no data change). Contains the design-tokens
branch (already merged). No conflicts; one Unreleased CHANGELOG section.
This commit is contained in:
Radosław Smoliński
2026-10-29 14:30:42 +01:00
86 changed files with 6091 additions and 38 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".`)
+19 -1
View File
@@ -10,7 +10,8 @@ once there are more than 20.
## Unreleased
Database names follow one rule, and seeding a live site touches only the records you name.
Database names follow one rule, and seeding a live site touches only the records you name. The block library:
fifteen ready page sections and ten page templates.
### New
- **Design-token standard** ([design-tokens.md](./design-tokens.md)): one set of `--ipal-*` names for every site,
@@ -22,6 +23,17 @@ Database names follow one rule, and seeding a live site touches only the records
New bin `ipal-tokens`: `src/design/tokens.ts` → `src/design/tokens.css` + WCAG contrast check (`--check` for CI).
Templates `DESIGN.md` and `tokens.ts` in `ipal-setup/resources`. `ipal-audit` checks the standard.
- `fluid.css` / `fluid-wide.css`: `--ipal-fs-xs`, `--ipal-fs-h4`, `--ipal-space-stack`, `--ipal-space-section-sm`.
- **Block library** ([block-library.md](./block-library.md)): `hero`, `textMedia`, `featureGrid`, `cta`, `richText`, `faq`,
`contact`, `gallery`, `testimonials`, `stats`, `steps`, `logos`, `team`, `pricing`, `entryList` — Payload block +
server component each, `{ en, pl }` panel, accessibility built in, styled only with design-token utilities.
Opt in per block: `libraryBlocks({ hero: true, … })` (`@intecion/ipal-kit/blocks`); render with
`createBlockRegistry(content, { Image, Link, sendForm })` (`@intecion/ipal-kit/blocks/rsc`). Nothing is on by default.
Override fields, variants, slugs, labels, part classes, primitives or whole components; own blocks share the registry.
- **Page templates:** `pageTemplates` (`@intecion/ipal-kit/templates`) — home, about, services, service, contact, blog
index, post, legal pages, cookie policy, 404 — as `createSeeder` data in English and Polish; `systemPageRefs`.
- **`ipal-blocks eject <block>`** copies a library block into `src/blocks/` (same slug and data shape).
- **`blockLibraryManifest`** — the library's blocks, variants, fields and primitives as data, for checks.
- **Seeder:** `{ $form: 'Contact form' }` references (by title, `formsCollection`, default `forms`).
- **Database name rule:** `<domain without dots>_prod` / `_dev` (e.g. `acmepl_prod`), docs/deployment.md.
`ipalEnvRules({ databaseName: true })` (domain from `NEXT_PUBLIC_SERVER_URL`, skipped on localhost) or
`{ databaseName: { domain, warn } }` checks `DATABASE_URI` and **warns only** — never fails startup. Default off.
@@ -37,6 +49,8 @@ Database names follow one rule, and seeding a live site touches only the records
device. A `-dark` variable a site still sets is used as the dark fallback. The secondary button's dark fallback text
is `#d4d4d4` (was `#e5e5e5`).
- Lightbox fade: `--ipal-lightbox-duration` defaults to `var(--ipal-duration, 200ms)`; new `--ipal-lightbox-easing`.
- **Admin labels:** the link "Open in new tab" checkbox is now **New tab** (with a description) and the table-of-contents
switch **Show contents** — shorter labels per admin-ux; the stored fields are unchanged.
- **A full seed of a live database is refused:** a run without `only` / `SEED_ONLY` against `NODE_ENV=production` or
a non-local database now throws (with the steps to follow). Dry runs (`SEED_DRY_RUN=1`) are never refused. Allow it
only with the owner's explicit OK: `IPAL_SEED_ALLOW_FULL=1` or `guard: { allowFull: true }`; `guard: false` turns
@@ -52,6 +66,10 @@ Database names follow one rule, and seeding a live site touches only the records
4. Optional: adopt the design-token standard (design-tokens.md → "Migrating an existing site"; **ipal-upgrade**). A
site that styles the cookie banner only through `--ipal-*-dark` for its dark theme and does not adopt `tokens.css`:
check the banner in the dark theme (the dark fallback now needs `color-scheme: dark`, which `<ThemeScript>` sets).
5. Block library — optional, nothing changes until you turn blocks on. New sites: the starter turns on eight blocks.
Existing sites move block by block when they get work (an own block with the same slug and fields can be replaced by
the library block with `slug`, else a migration with **ipal-migrate-fields**). After turning blocks on:
`pnpm generate:types`, `pnpm payload generate:importmap`, Postgres/SQLite `pnpm payload migrate:create`.
## 1.14.6
+1
View File
@@ -23,6 +23,7 @@ API details — one file per module:
| Accessibility widget (optional) | [accessibility.md](./accessibility.md) |
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Blocks, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Block library: ready sections, page templates | [block-library.md](./block-library.md) |
| Cookie consent, banner, settings window (in the bar / modal / large with cookie details) | [consent.md](./consent.md) |
| Cookie scanner: review list of drafts, "Scan cookies", Open Cookie Database lookup (optional) | [cookie-scanner.md](./cookie-scanner.md) |
| Under construction — locks subpages behind a popup (developer tool) | [construction.md](./construction.md) |
+16 -2
View File
@@ -134,6 +134,8 @@ export function Offer({ header, items }: OfferBlockProps) { return <Section head
`docs/dev/admin-ux.md`); no empty "just in case" fields.
7. **Renderers from the plugin:** `RenderBlocks` (not a `switch`), `RenderRichText` (not
your own Lexical parser), `useForm` (not hand-made form plumbing).
**Sections from the block library first:** `libraryBlocks` + `createBlockRegistry` (15 ready blocks,
docs/block-library.md); an own block only when no library block, variant or option fits.
8. **No `any` and no `@ts-ignore`.** Types from `@/payload-types`, `unknown` + guard.
9. **One source of truth** — `i18n.config.ts`, `lib/content.ts`, never copies.
10. **"Done" only after** a local `pnpm build` + the checks from §11.
@@ -145,7 +147,8 @@ export function Offer({ header, items }: OfferBlockProps) { return <Section head
| What | How |
|---|---|
| a page | in the panel: Pages + blocks, no code (§5.1) |
| a section (block) | `src/blocks/<Name>/config.ts` + `Component.tsx`, an entry in `blocks/registry.ts`, the block in the Pages `layout` field → `pnpm generate:types` (+ `pnpm payload generate:importmap` with `rowLabel`) — **ipal-block** |
| a section (block) | a library block first: `blockOptions` → `libraryBlocks` in `src/blocks/configs.ts`, `createBlockRegistry(content, { Image, Link, sendForm })` in `blocks/registry.ts` (docs/block-library.md). None fits → `src/blocks/<Name>/config.ts` + `Component.tsx`, `extra` in the registry, `pageBlocks` → `pnpm generate:types` (+ `pnpm payload generate:importmap` with `rowLabel`) — **ipal-block** |
| a standard page (home, about, services, contact, legal, 404…) | `pageTemplates` from `@intecion/ipal-kit/templates` in the content seed (after launch only with `SEED_ONLY`) — **ipal-site** phase 6 |
| a form | the Forms panel (builder) from the seed `scripts/seed-form-*.ts`, a block with `<RenderForm>`, sending via `sendForm` — **ipal-form** |
| a language | `i18n.config.ts` (the only place) + a Postgres migration + content in the new language — **ipal-locale-add** |
| a collection with URLs | `content: { collections: [...] }` in `ipalKit` and `createContentHelpers` (§5.4) — **ipal-collection** |
@@ -566,6 +569,13 @@ never by slug. pages.md.
## 6. BUILDING SECTIONS (`.tsx` blocks)
**Block library first.** The plugin ships 15 sections built to every rule below — `hero`, `textMedia`,
`featureGrid`, `cta`, `richText`, `faq`, `contact`, `gallery`, `testimonials`, `stats`, `steps`, `logos`, `team`,
`pricing`, `entryList` — with variants, `{ en, pl }` panels, accessibility and token-only styling, plus ten page
templates ([block-library.md](../block-library.md)). Turn them on with `libraryBlocks(blockOptions)`, render them with
`createBlockRegistry`, change them with their options (`fields`, `variants`, `classNames`, `ui`, `components`), own one
with `ipal-blocks eject`. The rules below are how those blocks are built and how you build your own when none fits.
Three problems that must never repeat: **a zoo of CTA fields** (`ctaLabel`,
`cta2Text`, `buttonUrl`…), **files as text** (`pdfUrl: '/files/x.pdf'`),
**the monolith section** (200–400 lines with cards, SVG icons and button styles).
@@ -625,7 +635,10 @@ Field labels as `{ en, pl }` objects (the panel runs in English and Polish; §6.
### 6.3 Layer 2 — UI primitives
Code 1:1: [section-code.md](./skills/ipal-block/resources/section-code.md). Each one has one job:
With the block library they come from the plugin: `Section`, `SectionHeader`, `Media`, `CMSLink`, `buttonClass`,
`Container`, `Card` from `@intecion/ipal-kit/blocks/rsc` (no project copies; `src/components/ui/` holds only a
project version you pass in with `createBlockRegistry(content, { ui: { Media } })`). A project without the library:
code 1:1 from [section-code.md](./skills/ipal-block/resources/section-code.md). Each one has one job:
| Primitive | Does | Instead of |
|---|---|---|
@@ -1262,6 +1275,7 @@ Anything that needs a developer → move it to the panel.
| Accessibility widget (optional) | [accessibility.md](../accessibility.md) |
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok | [analytics.md](../analytics.md) |
| Blocks, RenderBlocks, enhanceProps | [blocks.md](../blocks.md) |
| Block library: 15 ready sections, page templates, eject | [block-library.md](../block-library.md) |
| Cookie consent, banner | [consent.md](../consent.md) |
| Cookie scanner (review list, Open Cookie Database) | [cookie-scanner.md](../cookie-scanner.md) |
| Routing, archives, redirects, Markdown, search | [content.md](../content.md) |
+26 -5
View File
@@ -1,6 +1,6 @@
---
name: ipal-block
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short `{ en, pl }` labels per docs/dev/admin-ux.md, no empty spare fields), shared fields from the plugin (buildSectionHeaderField, buildLinksField, buildLinkField, buildSectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — first a block of the plugin's block library (libraryBlocks / createBlockRegistry, 15 ready sections) or its variant or options, and only when none fits an own block with a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short `{ en, pl }` labels per docs/dev/admin-ux.md, no empty spare fields), shared fields from the plugin (buildSectionHeaderField, buildLinksField, buildLinkField, buildSectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
---
# ipal-block
@@ -13,8 +13,29 @@ decision on that part; no hand-built replacement, no silent workaround. **Code r
One section per use of this skill. Details and ready code:
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.
## 0. Prerequisites
Check that these exist: `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
## 0. Library block first (docs/block-library.md)
The plugin ships 15 blocks: `hero`, `textMedia`, `featureGrid`, `cta`, `richText`, `faq`, `contact`, `gallery`,
`testimonials`, `stats`, `steps`, `logos`, `team`, `pricing`, `entryList` (variants: `blockLibraryManifest`).
1. Does a library block or one of its variants fit the section? → turn it on in `src/blocks/configs.ts`
(`blockOptions` → `libraryBlocks`), no component code. Done after step 3 below.
2. Almost fits → its options, not a copy: `fields: (defaults) => …` (`replaceField`, `removeField`), `variants`
(own `{ label: { en, pl }, value }` + `components` / `classNames` in the registry), `settings: { backgrounds }`,
`links`, `maxItems`. Another look of one part → `createBlockRegistry(content, { classNames: { faq: { item: '…' } } })`;
another primitive everywhere → `ui: { Media }`.
3. The project must own it completely → `pnpm exec ipal-blocks eject <block>` (same slug and data, no migration),
then the ejected builder in `pageBlocks` and `components: { <slug>: <Name>Block }` in the registry.
4. Nothing fits → an own block (below), with the library's builders (`buildItemsField`, `buildMediaField`,
`buildVariantField`, `buildContentField`, `defineLibraryBlock`) and primitives (`Section`, `SectionHeader`, `Media`,
`CMSLink`, `Card` from `@intecion/ipal-kit/blocks/rsc`), added to `extra` in `createBlockRegistry`.
Record the reason in AGENTS.md → "Project decisions" (`ipal-doctor` warns about own blocks that copy a library block).
**Check (library block):** `pnpm generate:types` → `pnpm payload generate:importmap` → Postgres/SQLite
`pnpm payload migrate:create`; add the block to a page in the panel (en and pl labels, ≤ 6 fields), the page shows
the section with `data-ipal-block="<slug>"`.
## 0a. Prerequisites (own block)
With `createBlockRegistry` the primitives come from `@intecion/ipal-kit/blocks/rsc` — import them, no project copies.
A project without it: check that these exist: `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
Old `src/fields/sectionHeader.ts` / `sectionSettings.ts` → replace with the plugin import and delete them (blocks.md, no migration).
Links (`buildLinkField`, `buildLinksField`, `resolveLink`) and section fields (`buildSectionHeaderField`, `buildSectionSettingsField`) come from the plugin — do not create them in the project.
Missing → first create them 1:1 from `resources/section-code.md` (this skill)
@@ -50,8 +71,8 @@ File patterns (Hero, FeatureGrid + FeatureCard): `resources/section-code.md`.
`<LightboxTrigger group={`<name>-${id}`} image={lightboxImage(item.image, { size: 'hero' })}>`
(`@intecion/ipal-kit/client`; skip the trigger when `lightboxImage` returns `null`). No
`useState` dialog, no `glightbox` — lightbox.md.
4. Add `config.ts` to `layout` in `src/collections/Pages.ts`,
and the component to `src/blocks/registry.ts` (key = slug).
4. Add `config.ts` to `pageBlocks` (`src/blocks/configs.ts`, used by `layout` in `src/collections/Pages.ts`),
and the component to `src/blocks/registry.ts` (`extra: { <slug>: Component }` in `createBlockRegistry`, key = slug).
5. `pnpm generate:types`.
## 3. Check
+5 -1
View File
@@ -184,12 +184,16 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| analytics | layout | `SiteProviders` wires `Analytics` (ID from Site integrations → Analytics); Consent Mode: `analytics={{ consentMode: 'basic' }}` = no request to Google before consent, default `'advanced'` = the Google tag loads at once with every signal `denied` | Meta/other pixels only after consent; in `basic` no `gtm.js` / `gtag/js` in Network before consent | analytics.md, gtm-meta-pixel.md |
| extra JSON-LD | layout / `lib/content` | `jsonLd={[buildNavigationJsonLd(…)]}`; `siteJsonLd` → `buildLocalBusinessJsonLd` | Rich Results Test | seo.md |
| links and navigation | components | `buildLinkField`/`buildLinksField` in fields; `resolveNav`, `resolveLink`, `getSystemLinks` | a menu link still works after a slug change | links.md, skill **ipal-nav** |
| blocks | `src/blocks/registry.ts` | `blocks` for `createPageRoute`; fields `buildSectionHeaderField`, `buildSectionSettingsField` | block visible on the page | blocks.md, skill **ipal-block** |
| block library (schema) | `src/blocks/configs.ts` → `Pages.layout` | `export const blockOptions = { hero: true, textMedia: true, featureGrid: true, cta: true, richText: true, faq: true, contact: true, gallery: true } satisfies LibraryBlocksOptions`; `blocks: [...libraryBlocks(blockOptions), ...ownBlocks]` (`/blocks`) | block picker in en/pl; `pnpm generate:types`, `generate:importmap`; Postgres/SQLite `migrate:create` | block-library.md |
| blocks (registry) | `src/blocks/registry.ts` | `createBlockRegistry(content, { Image, Link, sendForm, formClassNames, contactDetails?, extra: { own: Own } })` (`/blocks/rsc`; `Image`/`Link` from `next/image`/`next/link`) → `blocks` for `createPageRoute`; own blocks use `buildSectionHeaderField`, `buildSectionSettingsField`, `buildItemsField` | every section has `data-ipal-block`; one `h1` per page | block-library.md, blocks.md, skill **ipal-block** |
| page templates | `scripts/seed-content.ts` | `pageTemplates.home({ blocks: libraryBlockSlugs(blockOptions) })`, `pageTemplates.contact({ form: { $form: 'Contact form' } })` (`/templates`); after launch only with `SEED_ONLY` | seed summary 0 errors | block-library.md, seeding.md |
| FAQ rich results | page route | `getPageJsonLd(locale, slug, { faq: faqItemsFromLayout })` | Rich Results Test → FAQPage | block-library.md, seo.md |
| languages in the header | header | `<LanguageSwitcher>` (`/client`), `<AlternateLinksUpdater>` | switches to `/en/<slug-en>` | i18n.md |
| Tailwind + design tokens | `styles.css`, `src/design/tokens.ts`, `DESIGN.md` | `@import` `fluid-wide.css` (or `fluid.css`), `tokens.css`, `tailwind.css`, `../../design/tokens.css` + `@source "…/node_modules/@intecion/ipal-kit/dist/**/*.js";`; `pnpm exec ipal-tokens`; next/font `--font-family-body` / `--font-family-heading` | `ipal-tokens --check` up to date, no ✗ contrast rows; the cookie banner in the brand colour in both themes | design-tokens.md |
| a11y widget CSS | `styles.css` | `@import "@intecion/ipal-kit/a11y.css";` (only with `<AccessibilityWidget>`) | widget options change the page | accessibility.md |
| `/its` panel | `app/(payload)/its/…` | `adminRoute: '/its'` + `its` in the proxy matcher | `/its` login, `/admin` 404 | security.md |
| skills | `package.json` | `"ipal:skills": "ipal-skills"` | `.agents/skills/` up to date | PROGRAMISTA §2.1a |
| eject a library block | CLI | `pnpm exec ipal-blocks list` / `pnpm exec ipal-blocks eject faq [--dest src/blocks] [--dry-run]` → `src/blocks/Faq/`; then the ejected builder in `blockOptions`' place and `components: { faq: FaqBlock }` | the block renders from the project file | block-library.md "Own blocks and eject" |
**`createContentHelpers` keys (exports of `@/lib/content`)** — all lazy and cached per request:
@@ -1,7 +1,7 @@
# ipal-kit — export index
Every public export of `@intecion/ipal-kit` (all entries: root, `/client`, `/rsc`,
`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`, `/tokens`), grouped by module. Search with grep
`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`), grouped by module. Search with grep
(`grep -n "name" .agents/skills/ipal-reference/resources/api.md`) before you write anything yourself.
"Import from" column — the first entry is preferred. Plugin options, env, routes and what the
project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/docs/<page>.md`.
@@ -109,6 +109,35 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
**Types:** `BlockData`, `BlockComponentMap`, `EnhanceProps`, `RenderBlocksProps` (`/rsc`) — block data, component map, props enhancer, renderer props; `SectionHeaderFieldOptions`, `SectionSettingsFieldOptions` (root) — options of the section field builders.
## Block library (`block-library`) — details: `node_modules/@intecion/ipal-kit/docs/block-library.md`
Fifteen ready blocks and ten page templates. **Use a library block (or a variant / options of one) before writing a block.**
| Export | Import from | What it does / when |
|---|---|---|
| `libraryBlocks(options, shared?)` | `@intecion/ipal-kit/blocks` | The blocks the project turned on, for `Pages.layout`: `{ hero: true, faq: { maxItems: 10 }, cta: (b) => b }`; nothing is on by default; `shared` = `{ localization, settings }` for every block. |
| `libraryBlockSlugs(options)` | `@intecion/ipal-kit/blocks` | Turned-on blocks with renamed slugs → `{ faq: 'faq', testimonials: 'reviews' }` — for `pageTemplates` (`blocks`) and the registry (`slugs`). |
| `LIBRARY_BLOCK_BUILDERS`, `LIBRARY_BLOCK_SLUGS` | `@intecion/ipal-kit/blocks` | Builder per slug; the 15 slugs in picker order. |
| `buildHeroBlock`, `buildTextMediaBlock`, `buildFeatureGridBlock`, `buildCtaBlock`, `buildRichTextBlock`, `buildFaqBlock`, `buildContactBlock`, `buildGalleryBlock`, `buildTestimonialsBlock`, `buildStatsBlock`, `buildStepsBlock`, `buildLogosBlock`, `buildTeamBlock`, `buildPricingBlock`, `buildEntryListBlock` | `@intecion/ipal-kit/blocks` | One block each, `(options?: BlockOptions) => Block`. Options: `slug`, `interfaceName`, `labels`, `admin`, `custom`, `fields` (array or `(defaults) => fields`), `variants` (subset / own / `false`), `header`, `links`, `settings` (`false` drops header / links), `maxItems`, `localization` (`'fields'` / `'layout'`), `thumbnail`. Extra: featureGrid `icons`, testimonials `collection`, entryList `collections`, contact `formsCollection`. |
| `buildItemsField`, `buildMediaField`, `buildVariantField`, `buildIconField`, `buildContentField`, `columnsField`, `COLUMNS` | `@intecion/ipal-kit/blocks` | Field builders of the library for the project's own blocks: `items` array with readable rows, `media` upload, sidebar `variant`, `icon` select of the project's names, `content` rich text, `columns` (`two`/`three`/`four`). |
| `defineLibraryBlock(def)`, `adminText(en, pl)`, `variantOption(value, en, pl)` | `@intecion/ipal-kit/blocks` | The library's block frame (header → fields → buttons → variant → settings) for an own block; `{ en, pl }` text and variant shorthands. |
| `applyBlockOptions(block, options)`, `isNamed(field, name)`, `replaceField(fields, name, patch)`, `removeField(fields, name)`, `stripLocalized(fields)`, `pickVariants(defaults, chosen)` | `@intecion/ipal-kit/blocks` | Option merging and field-list helpers (also for `fields: (defaults) => …`). |
| `blockThumbnail(slug)` | `@intecion/ipal-kit/blocks` | Inline SVG sketch (data URL) for the block picker — what `thumbnail: true` uses. |
| `faqItemsFromLayout(doc, { field?, slugs? })` | `@intecion/ipal-kit/blocks` | FAQ questions of the page's FAQ blocks → `getPageJsonLd(locale, slug, { faq: faqItemsFromLayout })` (FAQPage). |
| `blockLibraryManifest`, `buildBlockLibraryManifest()`, `fieldPaths(fields)` | `@intecion/ipal-kit/blocks` | Plain data: every block's slug, interface name, variants, stored field paths; primitives, field builders, templates — for `ipal-doctor` and tests. |
| `createBlockRegistry(content, options?)` | `@intecion/ipal-kit/blocks/rsc` | `blockType → component` map for `createPageRoute` / `RenderBlocks`, bound to lib/content. Options: `Image`, `Link` (next/image, next/link), `sendForm`, `formClassNames`, `contactDetails`, `classNames` (per block part), `ui` (swap primitives), `components` (swap a block), `backgrounds`, `slugs`, `only`, `extra` (own blocks), `noSnippet` (e.g. `['cta']`), `icons`, `texts`, `lightbox`, `richText`, `entryCard`, `mapTestimonial`. |
| `LIBRARY_BLOCK_COMPONENTS` | `@intecion/ipal-kit/blocks/rsc` | The plugin's component per slug. |
| `HeroBlock`, `TextMediaBlock`, `FeatureGridBlock`, `GalleryBlock`, `FaqBlock`, `CtaBlock`, `ContactBlock`, `TeamBlock`, `PricingBlock`, `LogosBlock`, `TestimonialsBlock`, `StatsBlock`, `RichTextBlock`, `StepsBlock`, `EntryListBlock` | `@intecion/ipal-kit/blocks/rsc` | The block components (server; props `LibraryBlockProps`: data + `locale`, `isFirst`, `ui`, `ctx`, `classNames`). |
| `HERO_PARTS`, `TEXT_MEDIA_PARTS`, `FEATURE_GRID_PARTS`, `GALLERY_PARTS`, `FAQ_PARTS`, `CTA_PARTS`, `CONTACT_PARTS`, `TEAM_PARTS`, `PRICING_PARTS`, `LOGOS_PARTS`, `TESTIMONIALS_PARTS`, `STATS_PARTS`, `RICH_TEXT_PARTS`, `STEPS_PARTS`, `ENTRY_LIST_PARTS` | `@intecion/ipal-kit/blocks/rsc` | Default token classes per block part — the keys of `classNames`. |
| `defaultEntryCard(doc)`, `defaultTestimonial(doc)` | `@intecion/ipal-kit/blocks/rsc` | Default mapping of a collection document to an entry card / a testimonial (`entryCard`, `mapTestimonial` replace them). |
| `Section`, `SECTION_BACKGROUNDS`, `SectionHeader`, `Media`, `CMSLink`, `Anchor`, `buttonClass`, `BUTTON_CLASSES`, `Container`, `CONTAINER_WIDTHS`, `Card`, `CARD_CLASS`, `CARD_INTERACTIVE_CLASS` | `@intecion/ipal-kit/blocks/rsc` | UI primitives, token utilities only: section (anchor, background, `data-surface`), heading group, image/video, panel link, link element, button looks, page column, card. |
| `Buttons`, `headingId(block)`, `TitleLink`, `GRID_COLUMNS`, `cx`, `parts(defaults, overrides)` | `@intecion/ipal-kit/blocks/rsc` | Helpers for own blocks: button row, heading id for `aria-labelledby`, card title link (plain text when the link is dead), grid columns, class joining, part classes. |
| `BLOCK_TEXTS`, `blockTexts(locale, own?)`, `fillText(text, value)` | `@intecion/ipal-kit/blocks/rsc` | Visitor texts the blocks write (rating, step) in en/pl; override with `texts`. |
| `pageTemplates` | `@intecion/ipal-kit/templates` | `home`, `about`, `services`, `service`, `contact`, `blogIndex`, `post`, `legal(role)`, `cookiePolicy`, `notFound` → `{ title, slug, layout }` for `seed.upsertBySlug('pages', …)`. Options: `blocks`, `overrides`, `layout`, `slug`, `title`, `defaultLocale`, `linkTo`; `contact`/`service` take `form` (`{ $form: 'title' }`). After launch: only with `SEED_ONLY`. |
| `systemPageRefs(roles)` | `@intecion/ipal-kit/templates` | `{ homepage: 'start' }` → `{ homepage: { $page: 'start' } }` for `seed.fillGlobal('site-settings', …)`. |
**Types:** `BlockOptions`, `BlockBuilder`, `BlockLocalization`, `LibraryBlockSetting`, `LibraryBlocksShared`, `LibraryBlockSlug`, `LibraryBlocksOptions`, `VariantOption`, `LibraryBlockDefinition`, `ContactOptions`, `EntryListOptions`, `FeatureGridOptions`, `TestimonialsOptions`, `ItemsFieldOptions`, `MediaFieldOptions`, `VariantFieldOptions`, `IconFieldOptions`, `Columns`, `BlockLibraryManifest`, `ManifestBlock`, `ManifestField` (`/blocks`); `BlockRegistryOptions`, `BlockContent`, `BlockContext`, `BlockUi`, `LibraryBlockProps`, `ContactDetail`, `EntryCard`, `TestimonialItem`, `BlockTexts`, `PartClasses`, `BaseBlockData`, `LinkData`, `LinksData`, `MediaValue`, `RichTextData`, `SectionHeaderData`, `SectionSettingsData`, `HeroBlockData`, `TextMediaBlockData`, `FeatureGridBlockData`, `FeatureItem`, `GalleryBlockData`, `GalleryItem`, `FaqBlockData`, `FaqItem`, `CtaBlockData`, `ContactBlockData`, `TeamBlockData`, `TeamMember`, `PricingBlockData`, `PricingPlan`, `LogosBlockData`, `LogoItem`, `TestimonialsBlockData`, `StatsBlockData`, `StatItem`, `RichTextBlockData`, `StepsBlockData`, `StepItem`, `EntryListBlockData`, `CMSLinkProps`, `ResolveLink`, `LinkComponent`, `ImageComponent`, `MediaProps`, `SectionProps`, `SectionHeaderProps`, `HeadingLevel`, `CardProps`, `ContainerProps`, `ContainerWidth` (`/blocks/rsc`); `TemplateOptions`, `TemplatePage`, `TemplateBlock`, `TemplateValue` (`/templates`).
## Cookie consent (`consent`) — details: `node_modules/@intecion/ipal-kit/docs/consent.md`
| Export | Import from | What it does / when |
@@ -523,8 +552,8 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order. |
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
+18 -6
View File
@@ -54,14 +54,22 @@ decision on that part; no hand-built replacement, no silent workaround. **Code r
## Phase 2 — Content model
- Pages = `Pages` + blocks. Collections only for lists with URLs (**ipal-collection**).
- Globals: Header, Footer, Company (**ipal-nav**), Site settings, System pages.
- Every section from the site map → an existing block, a variant of an existing one (`variant`)
or a new block. Goal: as few blocks as possible, as many variants as possible.
- Every section from the site map → **a block of the block library first** (`libraryBlocks` from
`@intecion/ipal-kit/blocks`: hero, textMedia, featureGrid, cta, richText, faq, contact, gallery, testimonials,
stats, steps, logos, team, pricing, entryList — docs/block-library.md), or one of its variants (`variant`),
or its options (`fields`, `variants`, `settings`); a project block only when none fits, recorded in
"Project decisions". Goal: as few own blocks as possible.
- Write the map down: page → sections → library block + variant (or own block + why). The starter turns on
hero, textMedia, featureGrid, cta, richText, faq, contact, gallery; turn on the rest only when the map needs them.
- Schema change with content in the database → **ipal-migrate-fields**, never "live".
## Phase 3 — Navigation and company data → **ipal-nav**
## Phase 4 — Sections → **ipal-block** for every block
Order: Hero → recurring sections (FeatureGrid, CTA, FAQ…) → specific ones.
Library blocks need no code: `libraryBlocks(blockOptions)` in the Pages layout and `createBlockRegistry(content,
{ Image, Link, sendForm })` in `src/blocks/registry.ts` (docs/block-library.md "Setup"). Change looks through
`classNames` / `ui`, never by copying a block; own it completely only with `ipal-blocks eject <block>`.
Own blocks (no library block fits): order Hero → recurring sections → specific ones.
Every block: schema from the field dictionary, composition of primitives, zero text in JSX
(`ipal-audit --quick` after every block — fix errors right away).
**Enlarged images** (gallery, cards, product photos, certificates, rich text): the shared lightbox,
@@ -76,8 +84,11 @@ company **and** confirmation to the customer, every language) — the renderer a
form with fields in JSX, an `api/contact` route, `nodemailer`, reCAPTCHA (AGENT.md §0b).
## Phase 6 — Content in the panel, every language
1. Copy `resources/seed-content.template.ts` → `scripts/seed-content.ts`,
enter content from the brief: pages, blocks, links (`{ $page: 'slug' }`), globals —
1. Copy `resources/seed-content.template.ts` → `scripts/seed-content.ts`. Start every standard page from
`pageTemplates` (`@intecion/ipal-kit/templates`: home, about, services, service, contact, blogIndex, post,
legal, cookiePolicy, notFound) with `blocks: libraryBlockSlugs(blockOptions)` and `overrides` for the brief's
texts; forms by `{ $form: 'Contact form' }`; system pages with `systemPageRefs` (docs/block-library.md).
Enter content from the brief: pages, blocks, links (`{ $page: 'slug' }`), globals —
all languages side by side (`{ pl, en }`). Missing data → `[TO FILL: …]`.
Never invent company data, prices, reviews, numbers, certificates, names.
**VERY IMPORTANT — after launch never run the whole seed again** (the owner's edits must survive): a later
@@ -108,7 +119,8 @@ keep the auto-fill or fix it when the summary is weak.
The design-token standard (AGENT.md §6.11, `design-tokens.md`): `DESIGN.md` exists → its values go into
`src/design/tokens.ts` (template `.agents/skills/ipal-setup/resources/tokens.ts`) → `pnpm exec ipal-tokens` (no ✗
contrast rows). None → copy the `DESIGN.md` template, keep the neutral defaults + the brand primary, and recommend
Impeccable in the report. Components use only the preset's utilities. Do not polish styles ad hoc in components.
Impeccable in the report. Components use only the preset's utilities. Do not polish styles ad hoc in components. Library blocks follow the
tokens by themselves (token utilities only); a part that needs another look → `createBlockRegistry({ classNames })`.
Responsiveness: 360 px, 768 px, 1280 px — no horizontal scroll.
## Phase 9 — Verification (all by yourself, results go into the report)
@@ -26,27 +26,37 @@
* heading: { pl: 'Nasze usługi', en: 'Our services' } → localized value
* heading: 'Nasze usługi' → same in every locale / non-localized field
* page: { $page: 'kontakt' } → ID of the page whose DEFAULT-locale slug is 'kontakt'
* form: { $form: 'Contact form' } → ID of the form with that title (seed forms first)
* Missing data: '[TO FILL: tax ID (NIP)]' — never invent company data, prices, reviews, numbers.
* Media: leave empty or reference existing uploads by ID — the editor adds images. Never upload here.
*/
import config from '@payload-config'
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { pageTemplates } from '@intecion/ipal-kit/templates'
import { getPayload } from 'payload'
import { blockOptions } from '@/blocks/configs'
// ------------------------------------------------------------------ CONTENT --
// Standard pages start from the library templates (docs/block-library.md "Page templates"): every text in
// pl + en, [TO FILL: …] where only the client can write. Put the brief's texts in `overrides`; change the
// sections with `layout`. `blocks` = the library blocks this project turned on (others are left out).
const blocks = libraryBlockSlugs(blockOptions)
const PAGES: Record<string, unknown>[] = [
{
title: { pl: 'Strona główna', en: 'Home' },
slug: { pl: 'home', en: 'home' },
layout: [
{
blockType: 'hero',
pageTemplates.home({
blocks,
overrides: {
hero: {
header: { heading: { pl: 'Nagłówek z briefu', en: 'Heading from the brief' } }, // buildSectionHeaderField
links: [{ link: { type: 'internal', page: { $page: 'kontakt' }, label: { pl: 'Kontakt', en: 'Contact' }, appearance: 'primary' } }],
variant: 'split',
},
],
},
{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' }, layout: [] },
},
}),
pageTemplates.contact({ blocks, form: { $form: 'Contact form' } }), // seed the form first (ipal-form)
pageTemplates.legal('privacyPolicy', { blocks }),
pageTemplates.notFound({ blocks }),
// A page of your own: { title: { pl, en }, slug: { pl, en }, layout: [{ blockType: 'faq', items: [...] }] }
]
const GLOBALS: { slug: string; data: Record<string, unknown> }[] = [
// { slug: 'header', data: { links: [{ link: { type: 'internal', page: { $page: 'kontakt' }, label: { pl: 'Kontakt', en: 'Contact' } } }] } },
+281
View File
@@ -0,0 +1,281 @@
# Block library — ready page sections and page templates
Fifteen standard page sections (Payload block + React server component) and ten page templates,
so every site is assembled from the same parts. Each block is made of the plugin's building blocks
(`buildSectionHeaderField`, `buildLinksField`, `RenderForm`, `LightboxTrigger`, `RenderRichText`…),
has an editor panel in English and Polish (docs/dev/admin-ux.md), meets the accessibility rules below,
and is styled **only with the design-token utilities** (`bg-surface`, `text-fg`, `py-section`…).
Nothing is on by default. The project turns on the blocks it wants, and can change, swap or eject any
of them, or keep its own blocks in the same layout (CLAUDE.md main rule).
| Entry | What | Imported by |
|---|---|---|
| `@intecion/ipal-kit/blocks` | block configs, field builders, the manifest — no React | `payload.config`, collections |
| `@intecion/ipal-kit/blocks/rsc` | block components, UI primitives, `createBlockRegistry` | `src/blocks/registry.ts` |
| `@intecion/ipal-kit/templates` | page templates (seed data) | seed scripts only |
## Setup (a new site)
**1. Turn the blocks on in the Pages layout:**
```ts
// src/blocks/configs.ts — imported by src/collections/Pages.ts
import { libraryBlocks, type LibraryBlocksOptions } from '@intecion/ipal-kit/blocks'
export const blockOptions = {
hero: true, textMedia: true, featureGrid: true, cta: true, richText: true, faq: true, contact: true, gallery: true,
} satisfies LibraryBlocksOptions
export const pageBlocks = [
...libraryBlocks(blockOptions),
// the project's own blocks, e.g. TimelineBlock
]
// Pages.ts: { name: 'layout', type: 'blocks', blocks: pageBlocks }
```
The eight above are what every surveyed site built; add `testimonials`, `stats`, `steps`, `logos`, `team`,
`pricing`, `entryList` when the site map needs them. Fewer blocks = a shorter block picker for the editor.
**2. The registry** — every library block bound to lib/content, plus the project's own:
```ts
// src/blocks/registry.ts
import Image from 'next/image'
import Link from 'next/link'
import { createBlockRegistry } from '@intecion/ipal-kit/blocks/rsc'
import * as content from '@/lib/content'
import { sendForm } from '@/lib/sendForm'
import { formClasses } from '@/components/forms/formClasses'
export const blockRegistry = createBlockRegistry(content, {
Image, // next/image: optimized images with blur-up (without it: a plain <img>)
Link, // next/link: client-side navigation (without it: a plain <a>)
sendForm, // the contact block's form action (createSubmitAction, docs/forms.md)
formClassNames: formClasses,
// contactDetails: async (locale) => [{ label: 'Phone', value: '+48 …', href: 'tel:+48…' }],
// extra: { timeline: TimelineBlock },
})
```
The plugin never imports `next/*` itself, so `Image` and `Link` are passed in. `createPageRoute(content, { blocks: blockRegistry, … })`
or `<RenderBlocks components={blockRegistry} />` renders them (docs/frontend.md, docs/blocks.md).
**3. Styles.** The components use the token utilities of the design-token preset, and Tailwind must scan the
plugin's files. The standard `styles.css` ([design-tokens.md](./design-tokens.md)) already does both:
```css
@import "tailwindcss";
@import "@intecion/ipal-kit/fluid-wide.css";
@import "@intecion/ipal-kit/tokens.css";
@import "@intecion/ipal-kit/tailwind.css";
@import "../../design/tokens.css";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
```
**4. Also wire:** `<SiteProviders lightbox>` in the layout (gallery images open in the viewer, docs/lightbox.md) and
FAQ rich results: `getPageJsonLd(locale, slug, { faq: faqItemsFromLayout })` (docs/seo.md). For your own
`seo` pass-through: `faqItemsFromLayout(doc, { slugs: ['faq'] })`.
**5. Then:** `pnpm generate:types` · `pnpm payload generate:importmap` (the blocks use the plugin's row-label
component) · Postgres/SQLite: `pnpm payload migrate:create` and commit the migration (MongoDB needs none).
**Verify:** the block picker shows the blocks in the editor's language; adding each block shows at most six
fields; a page with every block renders (`pnpm build`); every section has `data-ipal-block="<slug>"` in the HTML; only the
first section's heading is `h1`; the gallery opens images in the viewer; `ipal-doctor` / `ipal-audit` report no block errors.
## The blocks
Every block has, in panel order: `header` (eyebrow, heading, intro) → its own fields → `links` (buttons, where the
block has them) → `variant` (sidebar) → `settings` (sidebar: anchor, background). Field names follow AGENT.md §6.5.
| Slug (builder) | Panel name | Own fields | Variants | Accessibility |
|---|---|---|---|---|
| `hero` (`buildHeroBlock`) | Hero / `Sekcja główna` | `media` (image or video), `poster` | `split`, `background`, `centered`, `page` | the first section's heading is the page `h1`; its image is the LCP image (eager, high priority); a background image is decorative (`alt=""`) under a scrim |
| `textMedia` (`buildTextMediaBlock`) | Text and image | `content` (rich text), `media` | `mediaRight`, `mediaLeft` | reading order = text first on every screen |
| `featureGrid` (`buildFeatureGridBlock`) | Feature grid | `items[]`: `icon` (with `icons`), `media`, `heading`, `text`, `link`; `columns` | `cards`, `list`, `numbered` | a linked feature: its heading is the link and covers the card; a dead link leaves plain text |
| `gallery` (`buildGalleryBlock`) | Gallery | `items[]`: `media`, `caption`; `columns` | `grid`, `masonry` | each image a `LightboxTrigger` (keyboard, focus return, labels from Form messages); captions in `<figcaption>` |
| `faq` (`buildFaqBlock`) | FAQ | `items[]`: `question`, `answer` | `single`, `twoColumn` | native `<details>`/`<summary>`, works without script |
| `cta` (`buildCtaBlock`) | Call to action | `media` | `band`, `card`, `split` | renders nothing without a heading and buttons |
| `contact` (`buildContactBlock`) | Contact | `form` (relation), `content` | `formWithDetails`, `formOnly` | `RenderForm` (labels, errors, consent); details as `<dl>` |
| `team` (`buildTeamBlock`) | Team | `items[]`: `media`, `heading` (name), `text` (role), `bio`, `link` | `grid`, `list` | the name is the profile link |
| `pricing` (`buildPricingBlock`) | Pricing | `items[]`: `heading`, `price`, `period`, `text`, `features[]`, `highlighted`, `link`; `highlightLabel`, `note` | — | the highlighted plan carries a text label, not only a colour |
| `logos` (`buildLogosBlock`) | Logos | `items[]`: `media`, `heading` (name), `link` | `row`, `grid` | the name is the alt text when the image has none; no marquee |
| `testimonials` (`buildTestimonialsBlock`) | Testimonials | `items[]`: `quote`, `heading` (author), `text`, `media`, `rating`; with `collection`: `source`, `entries` | `grid`, `single` | `<figure>` + `<blockquote>` + `<figcaption>`; stars hidden, rating read as text |
| `stats` (`buildStatsBlock`) | Key figures / `Liczby` | `items[]`: `value`, `heading` (label), `text` | `row`, `cards` | a `<dl>`; static (no count-up animation) |
| `richText` (`buildRichTextBlock`) | Text | `content`, `tableOfContents` | `narrow`, `wide` | heading anchors + table of contents (`aria-current` on the section being read) |
| `steps` (`buildStepsBlock`) | Steps | `items[]`: `heading`, `text`, `media` | `numbered`, `timeline` | an `<ol>`; the number read as "Step 1" |
| `entryList` (`buildEntryListBlock`) | Entry list | `collection`, `mode` (latest / chosen), `limit`, `entries` | `cards`, `list` | each title links to its entry and covers the card; dates in `<time>` |
**Rules every block meets:** one `<section>` with `aria-labelledby` its heading and `data-ipal-block`; `h1` only in the
first block (`isFirst` from `createPageRoute`), `h2` otherwise, items `h3`; images through `Media` (alt from the media
document, width and height, lazy except the hero); visible focus (`outline-focus`); no autoplay, motion only through
the token durations (0 ms under reduced motion); **an empty block renders nothing** (no empty section, no "Lorem").
**Visitor texts** the components write themselves — `rating` ("Rated {value} out of 5") and `step` ("Step {value}") —
ship in English and Polish (`BLOCK_TEXTS`, picked by `blockTexts(locale, own)`, `{value}` filled by `fillText`); other
languages or words: `createBlockRegistry(content, { texts: { de: { rating: '{value} von 5' } } })`. Everything else
comes from the panel.
## Change a block (schema)
`libraryBlocks(options, shared?)` takes a setting per block: `true`, an options object, a function `(block) => block`
that takes the finished block over, or `false`/missing = off. `shared` (`localization`, `settings`) applies to every
block; a block's own options win. Each block also has its own builder (`buildFaqBlock(options)` …, all in
`LIBRARY_BLOCK_BUILDERS`, slugs in `LIBRARY_BLOCK_SLUGS`).
| Option (`BlockOptions`) | Does |
|---|---|
| `slug` | keep an existing slug, e.g. `testimonials: { slug: 'reviews' }` (then `libraryBlockSlugs(options)` gives the registry and the templates the renamed slugs) |
| `interfaceName`, `labels`, `admin`, `custom` | the generated type name, the panel name, merged admin / custom |
| `fields` | an array replaces the fields; `(defaults) => fields` adds, changes or drops some — `replaceField(fields, 'media', { required: true })`, `removeField(fields, 'links')`, `isNamed(field, 'items')` |
| `variants` | a subset (`['single']`), the project's own (`{ label: { en, pl }, value }`), or `false` (no select). Unknown names throw (`pickVariants`) |
| `header`, `links`, `settings` | options for `buildSectionHeaderField`, `buildLinksField`, `buildSectionSettingsField` (e.g. project backgrounds); `header: false` / `links: false` drop them |
| `maxItems` | the `items` limit |
| `localization` | `'fields'` (default: text localized inside the block) or `'layout'` for projects that localize the whole `layout` field — drops every inner `localized` (`stripLocalized`) |
| `thumbnail` | the block picker picture: `true` = the plugin's sketch (an inline SVG from `blockThumbnail(slug)`, no route), a URL of your own, default none |
Block-specific options: `featureGrid: { icons: ['phone', 'mail'] }` (the project's icon names — adds an icon select;
the components come from `createBlockRegistry({ icons })`), `testimonials: { collection: 'testimonials' }` (pick from a
collection as well), `entryList: { collections: [{ label: { en: 'Projects', pl: 'Realizacje' }, value: 'projects' }] }`
(default posts), `contact: { formsCollection }` (default `forms`).
**Same panel for the project's own blocks:** `buildItemsField({ fields, labels, rowLabelField, maxRows })`,
`buildMediaField()`, `buildVariantField({ options })`, `buildIconField({ names })`, `buildContentField()`,
`columnsField()` (values `COLUMNS`: `two`, `three`, `four`), `adminText(en, pl)`, `variantOption(value, en, pl)`, and
`defineLibraryBlock({ slug, interfaceName, labels, fields, links, variants })` for the same frame
(header → fields → buttons → variant → settings). `applyBlockOptions(block, options)` applies `BlockOptions` to any block.
## Change the look or the component (front end)
`createBlockRegistry(content, options)` returns the `blockType → component` map; `LIBRARY_BLOCK_COMPONENTS` lists the
plugin's components. `content` needs `resolveLink`; `getEntries` (entry list), `getFormTexts` and `getLinkOptions`
(contact) are used when present — pass the whole `@/lib/content`.
| Option (`BlockRegistryOptions`) | Does |
|---|---|
| `classNames` | replace the classes of one part: `{ faq: { item: 'border-b border-border' } }`. The parts and their defaults: `HERO_PARTS`, `TEXT_MEDIA_PARTS`, `FEATURE_GRID_PARTS`, `GALLERY_PARTS`, `FAQ_PARTS`, `CTA_PARTS`, `CONTACT_PARTS`, `TEAM_PARTS`, `PRICING_PARTS`, `LOGOS_PARTS`, `TESTIMONIALS_PARTS`, `STATS_PARTS`, `RICH_TEXT_PARTS`, `STEPS_PARTS`, `ENTRY_LIST_PARTS` |
| `ui` | swap a primitive for every block: `{ Media, CMSLink, Section, SectionHeader, Container, Card, buttonClass }` |
| `components` | replace one block's component; it gets the same props (`LibraryBlockProps`: the data, `locale`, `isFirst`, `ui`, `ctx`, `classNames`) |
| `backgrounds` | section background values → classes, merged over `SECTION_BACKGROUNDS` (`default`, `muted`, `inverted`) |
| `slugs`, `only`, `extra` | renamed slugs; only some blocks; the project's own blocks in the same map |
| `Image`, `Link` | next/image and next/link |
| `sendForm`, `formClassNames`, `contactDetails` | the contact block: form action, form classes, details beside the form |
| `entryCard`, `mapTestimonial` | how a collection document becomes an entry card / a testimonial (defaults `defaultEntryCard`, `defaultTestimonial`) |
| `noSnippet` | blocks kept out of Google's snippets (`<NoSnippet>`), e.g. `['cta']` when the same call to action is on every page (docs/seo.md) |
| `icons`, `texts`, `lightbox`, `richText` | feature icons by name; visitor texts; `lightbox: false` = plain gallery images; `richText.className` for every rich text |
**UI primitives** (`/blocks/rsc`), each styled once with token utilities: `Section` (anchor, background,
`data-surface` for the inverted token scope, spacing, `Container`), `SectionHeader` (eyebrow, `h1`/`h2`, intro),
`Media` (image or video; `next/image` when passed), `CMSLink` (a panel link → `Anchor`, with `buttonClass`),
`buttonClass` / `BUTTON_CLASSES` (button looks by appearance), `Container` / `CONTAINER_WIDTHS`, `Card` / `CARD_CLASS` /
`CARD_INTERACTIVE_CLASS`. Helpers for the project's own blocks: `Buttons` (a block's button row), `headingId(block)`
(the heading id for `aria-labelledby`), `TitleLink` (a card title that links when its link resolves), `GRID_COLUMNS`,
`cx`, `parts(defaults, overrides)`.
**Every component is exported** (`HeroBlock`, `TextMediaBlock`, `FeatureGridBlock`, `GalleryBlock`, `FaqBlock`, `CtaBlock`,
`ContactBlock`, `TeamBlock`, `PricingBlock`, `LogosBlock`, `TestimonialsBlock`, `StatsBlock`, `RichTextBlock`,
`StepsBlock`, `EntryListBlock`) for a project that wires them without the factory.
**Section backgrounds and tokens.** `settings.background` → `default` `bg-bg text-fg`, `muted` `bg-surface-muted`
(+ `data-surface="muted"`), `inverted` `bg-inverse text-on-inverse` + `data-surface="inverse"`; inside the inverse
scope the token preset re-maps text, borders, links and focus, so blocks use plain `text-fg`, `text-link`,
`border-border`. No hex, no `dark:` for colours, no `clamp()` in the components (a test enforces it).
## Own blocks and eject
A section no library block or variant fits → the project's own block (**ipal-block** skill): `src/blocks/<Name>/`,
the same field builders and primitives, added to `pageBlocks` and to `extra` in the registry.
To own a library block completely:
```bash
pnpm exec ipal-blocks list
pnpm exec ipal-blocks eject faq # → src/blocks/Faq/config.ts + Component.tsx
```
Eject copies the block's source with its imports pointing at the package entries (same slug, same data shape —
no migration). Then use the ejected `buildFaqBlock` in `pageBlocks` (instead of `faq: true`), pass
`components: { faq: FaqBlock }` to the registry, and record it in AGENTS.md → "Project decisions". It never
overwrites an existing file (`--dest`, `--dry-run`).
## Page templates
`pageTemplates` (`@intecion/ipal-kit/templates`) — pages made of library blocks, every text in English and Polish,
`[TO FILL: …]` where only the client can write. Data for `createSeeder` (docs/seeding.md); nothing changes in the panel.
| Template | Layout | System page role |
|---|---|---|
| `home()` | hero · logos · featureGrid · textMedia · stats · testimonials · faq · cta | `homepage` |
| `about()` | hero (page) · textMedia · stats · team · steps · cta | — |
| `services()` | hero (page) · featureGrid · steps · pricing · faq · cta | — |
| `service({ form? })` | hero · textMedia · featureGrid (list) · gallery · faq · contact | — |
| `contact({ form })` | hero (page) · contact · faq | — |
| `blogIndex()` | hero (page) · cta — the entries come from the archive view (docs/content.md) | `postsArchive` |
| `post()` | richText (table of contents) · entryList · cta — for a posts collection with a `layout` field | — |
| `legal('privacyPolicy' \| 'termsOfService')` | hero (page) · richText (table of contents) — structure only; the wording comes from the client | `privacyPolicy`, `termsOfService` |
| `cookiePolicy()` | hero (page) · richText | `cookiePolicy` |
| `notFound()` | hero (page) with a button home | `notFound` |
```ts
// scripts/seed-content.ts
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks'
import { pageTemplates, systemPageRefs } from '@intecion/ipal-kit/templates'
import { blockOptions } from '@/blocks/configs' // the object passed to libraryBlocks
const blocks = libraryBlockSlugs(blockOptions) // blocks that are off are left out (with a warning)
await seed.upsertBy('forms', { title: 'Contact form' }, CONTACT_FORM)
await seed.upsertBySlug('pages', [
pageTemplates.home({ blocks, overrides: { hero: { header: { heading: { pl: '…', en: '…' } } } } }),
pageTemplates.contact({ blocks, form: { $form: 'Contact form' } }),
pageTemplates.legal('privacyPolicy', { blocks }),
])
await seed.fillGlobal('site-settings', systemPageRefs({ homepage: 'start', privacyPolicy: 'polityka-prywatnosci' }))
```
Template options (`TemplateOptions`): `blocks` (turned-on blocks with renamed slugs), `overrides` (data per block),
`layout` (`(blocks) => blocks` to reorder, drop or add), `slug`, `title`, `defaultLocale` (buttons link to pages by
their slug in it; default `pl`), `linkTo` (the slugs of the about / contact / home pages when yours differ).
`{ $form: 'title' }` and `{ $page: 'slug' }` are seed references (docs/seeding.md).
**After launch — named records only** (AGENT.md "Seeding on production", docs/seeding.md): use a template only through a
seed that names its records — `SEED_ONLY="pages:kontakt" pnpm payload run scripts/seed-content.ts` after
`SEED_DRY_RUN=1` and a Coolify backup — never a run of every template. Seeds stay create-only; a page an editor
changed is skipped. A newer ipal-kit never changes existing pages: templates are only read when a seed runs.
## Versioning — new fields never break content
- A minor release only **adds**: new optional fields (or with a `defaultValue`), new variant values. A component renders
the old output while a new field is empty.
- Never in a minor: renaming or removing a stored field, a select value, a slug or an `interfaceName`; a new
required field; a field becoming required. A rename happens only in a major, with an **ipal-migrate-fields** recipe
and upgrade notes.
- Database names come from the slugs and field names only — never from labels — so renaming a panel label changes no
table, column or enum.
- `test/blockLibrarySchema.test.ts` compares every block's field paths, types, select values and required flags with
`test/block-library.schema.json` and fails on any of the above.
- Upgrade notes list every new field. Postgres/SQLite: a new field needs `pnpm payload migrate:create` in the project;
MongoDB needs nothing.
## Manifest (for checks)
`blockLibraryManifest` (`/blocks`) is plain data built from the block configs: every block's `slug`, `interfaceName`,
`variants` and stored `fields` (paths from `fieldPaths(fields)`), the `primitives` a project may swap, the
`fieldBuilders` a project block should use instead of its own copy, and the `templates`. `ipal-doctor` reads its names
from here. `buildBlockLibraryManifest()` builds it again (e.g. in a test).
## Turn off, override, extend
| What | Default | Turn off / override |
|---|---|---|
| Any block | off | `libraryBlocks({ faq: true })`; your own block next to it |
| Fields, labels, variants, slug | the library's | `BlockOptions` per block, or `(block) => block` |
| Look of one part | token classes (`*_PARTS`) | `classNames` per block and part |
| A primitive | the plugin's | `ui: { Media, CMSLink, … }` |
| A block's component | the plugin's | `components: { faq: MyFaq }`, or eject |
| Images / links | `<img>` / `<a>` | `Image` / `Link` (next/image, next/link) |
| Lightbox on gallery images | on | `lightbox: false` |
| Visitor texts | `en`, `pl` | `texts` |
| Picker thumbnails | off | `thumbnail: true` or a URL |
| Localization | inside the blocks | `localization: 'layout'` |
| The whole library | not used | don't import it — `RenderBlocks` and the field builders work as before (docs/blocks.md) |
+4
View File
@@ -1,5 +1,9 @@
# blocks
> **Ready sections:** the plugin ships fifteen standard blocks (hero, FAQ, gallery, contact…) and page
> templates — [block-library.md](./block-library.md). Use a library block or a variant of one first; this page
> describes the engine and the field builders they are made of, which your own blocks use too.
`RenderBlocks` — a generic, server-side block rendering engine. The plugin does not
know your blocks: it iterates over the data, maps `blockType` → component through a
registry (prop), handles nesting and per-block extensions. You define the blocks
+509
View File
@@ -0,0 +1,509 @@
# Block library — proposal
> **Status:** approved (D1–D10, 2026-10-29) and built on `claude/block-library-build`. The shipped reference is
> [block-library.md](../block-library.md); where the build differs from this proposal, §13 says how and why.
> Building starts when the coordinator confirms that all five designs (tokens, blocks, reference site,
> doctor, starter) are in and consistent.
> **Scope:** a shared set of page blocks and page templates in `@intecion/ipal-kit`, so agents
> assemble pages from standard parts instead of rebuilding them on each site.
> **Related tracks:** design tokens standard (token names, §6), project starter and reference
> site (consumers, §10), `ipal-doctor` (conformance checks, §10).
---
## 1. Why
Seven client sites (`/Users/rasm/Projects/Payload/*-web`) have built **about 170 blocks** between
them. Almost every site rebuilt the same ten blocks (hero, CTA, rich text, text with image,
feature cards, FAQ, contact form, testimonials, gallery, stats). The field names, panel labels,
localization model and accessibility differ from site to site. An agent that starts a new site
copies the closest older site and inherits its quirks.
Today the plugin ships the **engine and the building blocks** (`RenderBlocks`, `buildSectionHeaderField`,
`buildSectionSettingsField`, `buildLinkField(s)`, `rowLabel`, `RenderForm`, `LightboxTrigger`,
`RenderRichText`, `buildFaqJsonLd`, `CookieTable`, `buildTableOfContentsField`). It ships **no
blocks**. The `ipal-block` skill gives patterns (`section-code.md`) that every project copies by hand.
The library adds the next layer: **ready blocks (schema + component) built from those parts**. The
project can still turn any of them off, change its fields, swap its component or add its own blocks.
## 2. Survey
### 2.1 Blocks per site
| Site | ipal-kit | Blocks | Uses plugin section fields |
|---|---|---|---|
| architektimprezpl-web | 1.14.6 | 20 | yes, plus a local `adminLabels` map |
| coastalclimatesupplycomau-web | 1.14.1 | 30 | mostly no: local `buildActionButtonsField`, `buildMetricsField`, `buildStatsField` |
| ecogenicacouk-web | 1.14.1 | 14 | yes, plus a local `buildItemsField` |
| intecioncom-web | 1.14.6 | 44 | yes |
| saydiamondspl-web | 1.11.0 | 15 | yes |
| thecleanteampl-web | ^1.12.2 | 11 | yes |
| vanstevpl-web | 1.12.2 | 25 | **no**: `ctaLabel`/`ctaTarget`/`url` fields, local `ctaHref.ts` |
### 2.2 The common set (how many of the 7 sites built it)
| Block kind | Sites | Names found |
|---|---|---|
| Hero (incl. a smaller page hero) | 7 | `hero`, `pageHero`, `simpleHero`, `videoHero`, `aboutHero`, `trustHero`, `hotWaterHero`, `productEnquiryHero` |
| CTA band | 7 | `cta`, `ctaBanner`, `ctaBand`, `bannerCta`, `ctaSection`, `callout`, `textCta`, `joinBanner`, `trustCta` |
| Rich text section | 7 | `richText`, `content`, `fullContent`, `textSection`, `introText`, `legal` |
| Contact / form | 7 | `formBlock`, `contact`, `contactBlock`, `contactSection`, `contactDetails`, `freeQuote`, `consultationCta` |
| Text with image | 7 | `imageText`, `imageStory`, `about`, `serviceIntro`, `textWithFacts`, `twoColumnWhy` |
| Feature / card grid | 7 | `featureGrid`, `features`, `uspList`, `infoGrid`, `servicesGrid`, `reasonCards`, `audienceCards`, `categoryGrid`, `offer`, `services`, `values`… |
| FAQ | 5 | `faq` (4 × `items[].question/answer`, 1 × `heading/text`) |
| Testimonials | 5 | `testimonials`, `testimonial`, `reviews`, `trustReviews` (inline items or a relation to a collection) |
| Gallery | 4 | `gallery`, `galleryMasonry`, `galleryStrip`, `photoGallery` (lightbox in 1 site) |
| Stats | 4 | `statsCounter`, `statsStrip`, `stats`, hero `metrics` |
| Steps / process | 4 | `processSteps`, `process`, `guideSteps`, `storySteps`, `numberedList`, `whyUsTimeline` |
| List of collection entries | 4 | `blogList`, `projectList`, `projects`, `featuredProducts`, `products`, `jobsList` |
| Pricing | 2 | `pricingTiers`, `pricing` |
| Logos | 2 | `clientLogos`, `certificates` |
| Tabs / accordion with content | 2 | `featureTabs`, `systemTabs`, `splitAccordion` |
| Video section | 1 | `videoShowcase` (+ `videoHero`) |
| Team | 1 | `teamGrid` |
| Map | 1 | `mapEmbed` |
| Cookie table | 1 | `cookieTable` (wraps the plugin's `CookieTable`) |
About 60 % of all blocks are one of the first twelve kinds. The other 40 % are site-specific
(`eventTypesMarquee`, `grantChecker`, `systemDiagram`, `jobDetail`, `incentives`…) and stay in the
projects.
### 2.3 Differences that cause the drift
1. **One block per page section.** coastal has `aboutClimate`, `aboutEfficiency`, `aboutSupport`,
`aboutTrade`, `aboutWhy` (five near-identical blocks); intecion has 10+ card-grid blocks that
differ only in layout. AGENT.md asks for a `variant` instead.
2. **Field names.** FAQ `question/answer` vs `heading/text`; pricing `tiers[].name` vs
`items[].heading`; logos `name` vs `heading`; galleries carry their own `prevLabel`/`nextLabel`
fields instead of the lightbox texts.
3. **Localization model.** ecogenica and saydiamonds localize the whole `layout` field
(each language has its own list of sections); the others localize fields inside blocks
(one structure, text per language). architekt localizes whole arrays (`items` with
`localized: true`), so item counts can differ per language.
4. **Panel language.** Bare English strings (intecion, saydiamonds), a local `adminLabels` map
(architekt), `{ en, pl }` objects (newer blocks). `docs/dev/admin-ux.md` asks for `{ en, pl }`.
5. **Local copies of plugin helpers.** `buildItemsField`, `buildActionButtonsField`,
`buildMetricsField`, `ctaHref.ts`.
6. **Hand-made image dialogs.** vanstev `PhotoGallery` (227 lines with `useState` + `role="dialog"`);
only architekt uses `LightboxTrigger`.
7. **Monoliths.** vanstev `JobDetail` (420 lines), coastal `TrustProjects` (288), `ProductEnquiryHero` (187).
8. **Registry file names.** `registry.ts` everywhere, but the config list is `allBlocks.ts`, `configs.ts`
or `pageBlocks.ts`.
**Conclusion:** the plugin's field builders fixed the "CTA field zoo", but each site still designs
the same blocks again. A shared library fixes items 1–7 for new sites and gives old sites a path to
move over (§9).
## 3. Design principles
1. **Building blocks first, finished blocks on top.** Every block is made from exported parts that
a project can use on its own: field builders, UI primitives, item cards, the block config, the block component.
2. **Nothing is on by default.** Installing or upgrading ipal-kit adds no block to any collection.
The project lists the blocks it wants (§7.1).
3. **The project wins.** Slug, labels, fields, variants, component, primitives and styles can all be
overridden per block (§7). Projects keep their own blocks next to library blocks in one registry.
4. **Server components, native HTML.** Interaction only where HTML is not enough, in small
`'use client'` files (FAQ = `<details>`, gallery = `LightboxTrigger`).
5. **Styling only through the shared design tokens** (§6). No hex values, no fixed widths, no `clamp()`
in components.
6. **Panel per `docs/dev/admin-ux.md`.** Every label `{ en, pl }`, glossary terms, sentence case,
descriptions ≤ 120 characters, `settings` in the sidebar.
7. **Additive versioning.** A minor release never removes or renames a stored field (§8).
## 4. Package layout
New entries (names to confirm, decision D1):
| Entry | Contains | Imported by |
|---|---|---|
| `@intecion/ipal-kit/blocks` | block configs and field builders (no React) | `payload.config`, collections |
| `@intecion/ipal-kit/blocks/rsc` | block components, UI primitives, `createBlockRegistry` | the page route, `blocks/registry.ts` |
| `@intecion/ipal-kit/templates` | page template data for seeds | seed scripts only |
**Manifest.** `@intecion/ipal-kit/blocks` also exports `blockLibraryManifest`, plain data with no React:
`{ version, blocks: [{ slug, interfaceName, variants, fields: [paths], phase }], primitives: ['Section', 'SectionHeader',
'Media', 'CMSLink', 'Button', 'Container', 'Card'], fieldBuilders: ['buildItemsField', …], templates: ['home', …] }`.
ipal-doctor reads the block, variant and primitive names from it instead of keeping its own list. The schema snapshot
test (§8) and the docs tables are generated from the same data, so the manifest cannot drift from the code.
Configs and components are separate entries so `payload.config` never imports React
(AGENT.md §6.12). Source layout: `src/modules/block-library/<block>/{config.ts,Component.tsx,<Item>Card.tsx,texts.ts}`.
## 5. The blocks
### 5.1 Shared parts every block uses
**Fields (already in the plugin):** `buildSectionHeaderField()` → `header` (eyebrow, heading, intro),
`buildSectionSettingsField()` → `settings` (anchor, background), `buildLinksField()` → `links`,
`buildLinkField()` → `link`, `rowLabel()`.
**Fields (new, exported):**
| Builder | Field | Why |
|---|---|---|
| `buildItemsField({ fields, labels, rowLabelField, maxRows, minRows })` | `items` array with `initCollapsed` + `rowLabel` | replaces the local copies (ecogenica, coastal) |
| `buildMediaField({ name, required, label })` | `media` upload to `media` | one label set, one place for `relationTo` |
| `buildVariantField({ options, defaultValue })` | `variant` select in the sidebar | variants instead of copies |
| `buildIconField({ names })` | `icon` select | the names list from the project; the plugin ships no icon set |
**UI primitives (new, exported from `/blocks/rsc`):** `Section`, `SectionHeader`, `Media`, `CMSLink`,
`Button`, `Container`, `Card`. These are the files every project copies today from `section-code.md`.
The plugin versions take `resolveLink` from `createContentHelpers` through the registry factory (§7.3),
so they need no `@/lib/content` import. A project can keep its own primitives and pass them in.
**Heading levels.** The first block on the page gets `isFirst` from `createPageRoute`; its
`SectionHeader` renders `h1`, every other block `h2`, and item headings `h3`. One `h1` per page, no
skipped levels.
**Background.** `settings.background` (`default` / `muted` / `inverted` + project values) maps to
token utilities in `Section` (§6). Contrast is the tokens' job: each background has a matching text token.
### 5.2 Block list
Phase 1 = the twelve blocks the brief asks for plus `steps` and `entryList` (both built by 4 of 7 sites).
Phase 2 = less common blocks.
| Slug | Panel name (en / pl) | Fields (in panel order) | Variants | Notes |
|---|---|---|---|---|
| `hero` | Hero / `Sekcja główna` | `header`, `media`, `links`, `settings` | `split` (image beside), `background` (image behind, `bg-overlay` scrim), `centered`, `page` (small page hero, no media) | the LCP image: `priority` when `isFirst`; video via `Media videoMode="background"` with a poster |
| `textMedia` | Text and image / Tekst i obraz | `header`, `content` (rich text), `media`, `links`, `settings` | `mediaRight`, `mediaLeft` | rich text via `RenderRichText`; image `sizes` = half |
| `featureGrid` | Feature grid / Siatka zalet | `header`, `items[]` (`icon` or `media`, `heading`, `text`, `link`), `links`, `settings` | `cards`, `list`, `numbered`; columns 2 / 3 / 4 | covers USP lists, service cards, category cards; whole card clickable when `link` has no label |
| `gallery` | Gallery / Galeria | `header`, `items[]` (`media`, `caption`), `links`, `settings` | `grid`, `masonry`; columns | every image a `LightboxTrigger` (group = block id); labels from Form messages → Image viewer; no own prev/next fields |
| `faq` | FAQ / Pytania i odpowiedzi | `header`, `items[]` (`question`, `answer`), `links`, `settings` | `single`, `twoColumn` | `<details>`/`<summary>`; FAQPage JSON-LD through `getPageJsonLd({ faq })` with the exported `faqItemsFromLayout()` |
| `cta` | Call to action / `Wezwanie do działania` | `header`, `links`, `media` (optional), `settings` | `band`, `card`, `split` | wrap in `<NoSnippet>` when the project repeats it on every page (option) |
| `contact` | Contact / Kontakt | `header`, `form` (relation to `forms`), `details` (from the company global, toggle), `content`, `settings` | `formOnly`, `formWithDetails` | form through `RenderForm` (`sendForm`, `formTexts` from `blockProps`); `classNames` from the shared form tokens; contact details from a project-supplied resolver, never typed into the block |
| `team` | Team / `Zespół` | `header`, `items[]` (`media`, `heading` = name, `text` = role, `link` = profile), `settings` | `grid`, `list` | profile link label = screen-reader text |
| `pricing` | Pricing / Cennik | `header`, `items[]` (`heading`, `price`, `period`, `text`, `features[]`, `highlighted`, `link`), `note`, `settings` | — | highlighted plan: label text from the block (`highlightLabel`), not colour only |
| `logos` | Logos / Logotypy | `header`, `items[]` (`media`, `heading` = name, `link`), `settings` | `row`, `grid` | alt = name when the media alt is empty; no marquee by default (reduced motion) |
| `testimonials` | Testimonials / Opinie | `header`, `source` (`inline` / `collection`), `items[]` (`quote`, `heading` = author, `text` = role, `media`, `rating`) or `entries` (relation), `settings` | `grid`, `single` | `<figure>` + `<blockquote>` + `<figcaption>`; rating has a text equivalent; `collection` mode only when the project passes the collection slug |
| `stats` | Key figures / Liczby | `header`, `items[]` (`value`, `heading` = label, `text`), `settings` | `row`, `cards` | static numbers; count-up animation off by default and never under reduced motion. Panel name avoids "statistics" (glossary: visit counting) |
| `richText` | Text / Tekst | `header`, `content`, `tableOfContents` (`buildTableOfContentsField`), `settings` | `narrow` (measure), `wide` | used by legal pages and posts; heading anchors from `richtext/headings` |
| `steps` | Steps / Kroki | `header`, `items[]` (`heading`, `text`, `media`), `links`, `settings` | `numbered`, `timeline` | ordered list `<ol>` |
| `entryList` | Entry list / `Lista wpisów` | `header`, `collection` (select from the project's `content.collections`), `mode` (`latest` / `selected`), `entries`, `limit`, `links`, `settings` | `cards`, `list` | blog teasers, projects, products; data loaded on the server through `createContentHelpers` |
| *phase 2* `video`, `tabs`, `map`, `cookieTable`, `comparisonTable` | | | | `video` = `YouTubeEmbed`/`Media player`; `map` behind consent; `cookieTable` wraps `CookieTable` |
Field names follow AGENT.md §6.5 (`header`, `items`, `heading`, `text`, `content`, `media`, `link(s)`,
`settings`). Two deliberate exceptions, both already the norm in the sites: FAQ keeps
`question`/`answer` (4 of 5 sites; also the `buildFaqJsonLd` input), and testimonials keep `quote`.
### 5.3 Example — `faq`
```ts
// src/modules/block-library/faq/config.ts (plugin)
export function buildFaqBlock(options: BlockOptions<'faq'> = {}): Block {
return applyBlockOptions(
{
slug: 'faq',
interfaceName: 'FaqBlock',
labels: { singular: { en: 'FAQ', pl: 'Pytania i odpowiedzi' }, plural: { en: 'FAQs', pl: 'Pytania i odpowiedzi' } },
imageURL: '/ipal-blocks/faq.svg', // block picker thumbnail (optional, §5.5)
fields: [
buildSectionHeaderField(),
buildItemsField({
labels: { singular: { en: 'Question', pl: 'Pytanie' }, plural: { en: 'Questions', pl: 'Pytania' } },
rowLabelField: 'question',
fields: [
{ name: 'question', type: 'text', localized: true, required: true, label: { en: 'Question', pl: 'Pytanie' } },
{ name: 'answer', type: 'textarea', localized: true, required: true, label: { en: 'Answer', pl: 'Odpowiedź' } },
],
}),
buildLinksField({ maxRows: 1 }),
buildVariantField({ options: FAQ_VARIANTS, defaultValue: 'single' }),
buildSectionSettingsField(),
],
},
options,
)
}
```
```tsx
// src/modules/block-library/faq/Component.tsx (plugin) — server component
export function FaqBlock({ header, items, links, settings, variant, ui, locale, isFirst }: FaqBlockProps) {
const { Section, SectionHeader, CMSLink } = ui
if (!items?.length) return null
return (
<Section settings={settings} data-ipal-block="faq">
<SectionHeader header={header} as={isFirst ? 'h1' : 'h2'} />
<div className={FAQ_LAYOUT[variant ?? 'single']}>
{items.map((item) => <FaqItem key={item.id} item={item} />)}
</div>
{links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
</Section>
)
}
```
### 5.4 Accessibility (every block)
The plugin's tests check these for each block, and the block docs list them:
- Landmarks: each block is one `<section>` with `aria-labelledby` pointing at its heading (when there is one).
- Headings: `h1` only in the first block, then `h2`, items `h3`.
- Images: alt from the media document (required, localized); decorative images (`background` hero)
get `alt=""`; logos fall back to the item name.
- Links: no "Read more" alone — a card link without a label uses the card heading as its name.
- Keyboard: every control reachable, visible focus ring from the focus token; `<details>` for FAQ;
lightbox focus handling is already in `LightboxDialog`.
- Motion: no autoplay carousels; animations only with `prefers-reduced-motion: no-preference`.
- Colour: information never by colour only (highlighted plan, rating); contrast through token pairs (§6).
- Forms: `RenderForm` handles labels, errors and `aria-describedby`.
- Language: visitor-facing fixed strings (lightbox, "Highlighted", rating text) ship in `en` and `pl`
and follow the page locale, overridable per project.
### 5.5 Panel (admin-ux)
- Every label, description, option and `labels.singular/plural` is `{ en, pl }`.
- Block names say what the editor sees: "Text and image", not "ImageText".
- Order inside each block: `header` → content → `media` → `items` → `links`; `variant`, `settings`
in the sidebar.
- Optional block thumbnails (`imageURL`) in the block picker, served from the plugin's static folder
only when the project turns them on (`thumbnails: true`) — no forced route (decision D7).
- Every block passes the empty-block test (≤ 6 fields visible when added).
## 6. Styling — design tokens
The library styles **only through the token names of the design-tokens track**
(`docs/dev/design-tokens-proposal.md` on `claude/design-tokens-95806d`; names agreed with that session
on 2026-10-29; the owner may still rename the utilities, see below). The canonical variables are the `--ipal-*` names the
plugin already ships; utilities come from the plugin preset `@intecion/ipal-kit/tailwind.css`.
Colours switch under `html[data-theme=dark]`, so blocks never use `dark:` for colours.
| Block need | Utilities (variable) |
|---|---|
| Section backgrounds (`settings.background`) | `default` → `bg-bg`; `muted` → `bg-surface-muted`; `inverted` → `bg-inverse text-on-inverse` (`--ipal-bg`, `--ipal-surface-muted`, `--ipal-surface-inverse`, `--ipal-text-inverse`) |
| Body, heading, muted text | `text-fg`, `text-fg-strong`, `text-fg-muted` (eyebrow, captions, item roles) |
| Card (feature, team, pricing, testimonial) | `bg-surface text-fg border border-border rounded-card shadow-sm`; clickable card: `hover:shadow-md transition-shadow duration-fast ease-out` |
| Highlighted pricing plan, rating stars, badges | `bg-accent text-on-accent` / `text-accent` (always with a text label, §5.4) |
| Buttons (in the `Button` primitive only) | `bg-primary hover:bg-primary-hover text-on-primary`, `bg-secondary …`, ghost `hover:bg-hover`; `rounded-control` |
| Links in rich text and cards | `text-link hover:text-link-hover` |
| Focus | `focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus` |
| Hero image overlay | `bg-overlay` (scrim), gradient `bg-linear-to-t from-overlay to-transparent` |
| Images | `rounded-media` |
| Type | `font-heading text-display / text-h1 / text-h2 / text-h3 / text-h4`, `text-lead` (intro), `leading-heading tracking-heading`; hero fit: `text-[length:var(--ipal-fs-display-fit)]`, `min-h-[var(--ipal-hero-min-h)]` |
| Spacing | `py-section` (`py-section-sm` for CTA band, logos), `gap-gap` for section grids, Tailwind steps inside cards, `mt-stack` heading → content, `px-gutter` |
| Widths | `max-w-container` (default), `max-w-container-wide` (gallery wide), `max-w-narrow` (`richText narrow`, legal), `max-w-measure` (running text) |
| Motion | `duration-fast/base/slow`, `ease-out` (0 ms under reduced motion) |
| Layering | `z-overlay` (lightbox is already the plugin's) |
**Inverted sections** (agreed with the tokens track). `Section` renders `bg-inverse` with
`data-surface="inverse"`. Inside that scope the preset re-maps the text, muted-text, border, surface and
hover tokens, plus link (`--ipal-link-inverse`) and focus (`--ipal-focus-inverse`), and flips `color-scheme`.
Blocks inside use plain `text-fg`, `text-link`, `border-border` and need no inverse variants. Primary and accent are not re-mapped; the
tokens contrast report warns when primary on `surface-inverse` fails. `data-surface="muted"` is set on
muted sections as a hook and re-maps nothing by default.
If the owner picks shadcn-style utility names instead (`text-foreground`, `bg-muted`), the blocks change
by a mechanical class rename; the roles stay.
**How blocks carry styles (decision D2).** Recommended: **Tailwind v4 utilities that use only token
names**, compiled by the project through `@source "…/node_modules/@intecion/ipal-kit/dist/**/*.js"`
(the line projects already have). All seven sites use Tailwind v4. Each element also gets a
`data-ipal-block` / `data-ipal-part` attribute, and each block takes a `classNames` map (like
`RenderForm`) that replaces the default classes per part. Alternative: a plain CSS file
(a `blocks.css` file in the package) on CSS variables — works without Tailwind, but is harder to
change per project.
## 7. How a project uses, changes and extends it
### 7.1 Opt in per block (schema)
```ts
// src/collections/Pages.ts
import { libraryBlocks } from '@intecion/ipal-kit/blocks'
import { ProjectTimeline } from '@/blocks/ProjectTimeline/config'
{
name: 'layout',
type: 'blocks',
blocks: [
...libraryBlocks({
hero: true,
textMedia: true,
faq: { variants: ['single'] }, // fewer variants
gallery: { fields: (fields) => [...fields, captionPosition] }, // add a field
pricing: false, // off (also the default when not listed)
testimonials: { slug: 'reviews', interfaceName: 'ReviewsBlock' }, // keep an old slug
}),
ProjectTimeline, // the project's own block
],
}
```
Each block also has its own builder (`buildFaqBlock(options)`) for projects that prefer to list them one by one.
**Options per block** (`BlockOptions`): `slug`, `interfaceName`, `labels`, `fields` (array or
`(defaults) => fields`), `variants` (subset or extra values), `maxItems`, `header` / `links` / `settings`
options passed to the shared builders (e.g. `settings: { backgrounds: […] }`), `localization`
(§7.5), `admin` (merged), `custom`. An object merges with the defaults key by key and the project's
keys win; a function `(block) => block` takes over completely — the same rule as `globalOverrides`.
### 7.2 Override fields
- Add: `fields: (defaults) => [...defaults, myField]`.
- Change one: `fields: (defaults) => defaults.map((f) => (isNamed(f, 'media') ? { ...f, required: true } : f))`
— the plugin exports `isNamed` and `replaceField(fields, name, patch)`.
- Remove one: allowed (e.g. drop `links` from `faq`); the component renders nothing for a missing field.
- Labels: any `label`/`labels` override wins; texts for other locales than `en`/`pl` come from the project.
### 7.3 Swap a component or a primitive (front end)
```ts
// src/blocks/registry.ts
import { createBlockRegistry } from '@intecion/ipal-kit/blocks/rsc'
import * as content from '@/lib/content'
import { Media } from '@/components/ui/Media' // project primitive
import { HeroSplit } from '@/blocks/Hero/Component' // project component for one block
import { ProjectTimeline } from '@/blocks/ProjectTimeline/Component'
export const blockRegistry = createBlockRegistry(content, {
ui: { Media }, // replace one primitive for every library block
components: { hero: HeroSplit }, // replace one block component
classNames: { faq: { item: 'border-b border-border' } },
extra: { projectTimeline: ProjectTimeline }, // the project's own blocks, same registry
})
```
`createBlockRegistry` returns a plain `blockType → component` map for `RenderBlocks` /
`createPageRoute`. It binds `resolveLink`, `ui` and `classNames` into server components, so no
function crosses to the client. A project that wants nothing from the factory imports the bare
components (`FaqBlock`, `FaqItem`) and wires them itself. **Eject:** `pnpm exec ipal-blocks eject faq`
copies the block's config and component into `src/blocks/Faq/` with the same slug and data shape, for
a project that wants to own it fully (decision D3).
### 7.4 Add your own block
Unchanged from today: `ipal-block` skill, `src/blocks/<Name>/`, same primitives (now importable from
the plugin), same registry. Rule for agents: **a library block or a variant of one first; a new block
only when no variant fits**, recorded in "Project decisions".
### 7.5 Localization model (decision D4)
Default: **fields inside blocks are localized** (`localized: true` on text, rich text and media
that differ per language); the `layout` field is not. One page structure, text per language — this matches
`createSeeder` (`writeLocales` writes the same row ids per locale) and the content audits.
Option `localization: 'layout'` drops the inner `localized` flags for projects that localize the whole
`layout` field (ecogenica, saydiamonds), so Payload does not store nested localized values.
## 8. Versioning — adding fields never breaks content
Rules for the library (enforced in plugin CI):
1. **Minor releases only add.** New fields are optional, or have a `defaultValue`; new variants are
new select values; the component renders the old output when the new field is empty.
2. **Never rename or remove** a stored field, a select value, a slug or an `interfaceName` in a minor.
A rename happens only in a major, with an **ipal-migrate-fields** recipe and upgrade notes.
3. **`dbName` is pinned** on array and select fields so Postgres table and enum names do not change
when a label or a project slug changes.
4. **Schema snapshot test.** `test/block-library.schema.json` stores every block's field paths, types,
select values and `required` flags. CI fails when a path disappears, a type changes or a field becomes
required. Adding is allowed and updates the snapshot.
5. **Upgrade notes** list every new field per block. On Postgres/SQLite a new field still needs a project
migration (`payload migrate:create`); the notes say so. MongoDB needs none.
6. **Content safety.** New required fields are never added to existing blocks; validation that would reject
old documents is never added in a minor.
## 9. Page templates
A template is **data, not code**: a function that returns a page (`title`, `slug`, `layout`) built from
library blocks, with every visible text in `en` and `pl` and `[TO FILL: …]` where only the client can write it.
Templates feed `createSeeder.upsertBySlug`; nothing in the panel changes.
| Template | Layout (blocks, in order) | System page role |
|---|---|---|
| `home` | `hero` · `logos` · `featureGrid` · `textMedia` · `stats` · `testimonials` · `faq` · `cta` | `homepage` |
| `about` | `hero (page)` · `textMedia` · `stats` · `team` · `steps` · `cta` | — |
| `services` | `hero (page)` · `featureGrid (cards)` · `steps` · `pricing` · `faq` · `cta` | — |
| `service` (one service) | `hero (split)` · `textMedia` · `featureGrid (list)` · `gallery` · `faq` · `contact` | — |
| `contact` | `hero (page)` · `contact (formWithDetails)` · `faq` | — |
| `blogIndex` | `hero (page)` · archive view from `createPageRoute` `render` (content.md) · `cta` | `postsArchive` |
| `post` (posts collection) | post header (title, date, author, media) · `content` with `tableOfContents` · `entryList (related)` · `cta` | — |
| `legal` (privacy, terms) | `hero (page)` · `richText (narrow, tableOfContents)` | `privacyPolicy`, `termsOfService` |
| `cookiePolicy` | `hero (page)` · `richText` · `cookieTable` | `cookiePolicy` |
| `notFound` | `hero (page, with links home)` | `notFound` |
```ts
// scripts/seed-content.ts
import { pageTemplates } from '@intecion/ipal-kit/templates'
await seed.upsertBySlug('pages', [
pageTemplates.home({ slug: { pl: 'start', en: 'home' }, overrides: { hero: { header: { heading: { pl: '…', en: '…' } } } } }),
pageTemplates.contact({ form: { $form: 'Contact form' } }),
pageTemplates.legal('privacyPolicy'),
])
```
- A template takes `overrides` per block and `layout: (blocks) => blocks` to reorder, drop or add sections.
- It only uses blocks the project turned on; a missing block is left out and reported in the seed summary.
- Templates set the system page role in Site settings through `fillGlobal` (empty fields only).
- Text defaults are neutral and short (admin-ux tone); legal templates ship structure and headings, never
legal wording presented as final.
- `$form: 'title'` is a new seed reference (like `$page`) — a small `createSeeder` addition.
**After launch** (AGENT.md / seeding.md, "named records only"): templates are used only through a seed
that names the records it writes (`upsertBySlug('pages', [pageTemplates.contact(…)])`), never a full
"seed every template" run. Seeds stay create-only; `SEED_UPDATE` keeps skipping edited pages. A template
change in a new ipal-kit version never touches existing pages.
## 10. Links to the other tracks and the skills
| Track / skill | What changes |
|---|---|
| **Design tokens** | the token contract in §6; the starter's `styles.css` defines them; blocks never introduce new names without that track |
| **Project starter** | turns on the phase 1 blocks, `createBlockRegistry`, the token CSS and a `seed-content.ts` built from templates |
| **Reference site** | uses every library block and variant on real pages; it is the visual test and the screenshot source for docs |
| **ipal-doctor** | reads `blockLibraryManifest` (§4); rules agreed with that session (its proposal §2.5a): `blocks-ui-required`, `blocks-ui-override`, `blocks-duplicate`, `blocks-helper-copy`, `blocks-registry`, `blocks-tokens`. Checks: library blocks used where one fits (warns on project blocks that duplicate one), no local copies of `buildItemsField` etc., registry from `createBlockRegistry` or `RenderBlocks`, token-only classes |
| **ipal-block** skill | step 0: "is there a library block or a variant?"; then options (§7.1), component swap (§7.3), eject; own blocks as today |
| **ipal-site** skill | phase 2 maps each section of the site map to a library block + variant first; phase 6 builds `seed-content.ts` from templates |
| **seeding.md + ipal-site `seed-content.template.ts`** | templates, `$form`, named-records rule after launch |
| **ipal-audit** | "panel:" checks also run on library blocks with project overrides |
| **AGENT.md** | §6 starts with "use the block library"; §12 module map gets `blocks` and `templates`; `docs/blocks.md` gets a "Block library" part and one doc per block (fields, variants, a11y, options, verify) |
## 11. Delivery plan (after approval)
1. **Foundations** — new field builders, UI primitives, `createBlockRegistry`, `BlockOptions` + merge,
schema snapshot test, docs skeleton. Patch-safe: nothing is on by default.
2. **Phase 1 blocks** — `hero`, `textMedia`, `featureGrid`, `cta`, `richText`, `faq`, `contact`, `gallery`,
then `testimonials`, `stats`, `steps`, `logos`, `team`, `pricing`, `entryList`. Each with tests
(render with empty data, a11y checks, schema snapshot), docs and `{ en, pl }` texts.
3. **Templates** — `@intecion/ipal-kit/templates`, `$form` in the seeder.
4. **Agent guide and skills** — AGENT.md, ipal-block, ipal-site, ipal-reference `api.md`, ipal-audit.
5. **Reference site + starter** adopt it; then one existing site as the first move-over (decision D8).
Ships as **1.15.0** (new feature, no breaking change).
## 12. Decisions
The owner accepted every recommendation below on 2026-10-29 ("Accept all three", relayed by the coordinator).
| # | Decision | Accepted |
|---|---|---|
| D1 | Ship the library inside `@intecion/ipal-kit` (new entries) or as a separate package `@intecion/ipal-blocks` | **inside**, new entries `/blocks`, `/blocks/rsc`, `/templates` — one version, one guide |
| D2 | Styling: Tailwind token utilities from the plugin preset + `classNames`/`data-ipal-*`, or a plain CSS file on variables | **Tailwind token utilities** (all sites are on Tailwind v4; agreed with the design-tokens session) |
| D3 | Offer an `ipal-blocks eject <block>` command that copies a block into the project | **yes**, phase 2 |
| D4 | Localization default: fields inside blocks (one structure) or the whole `layout` per language | **fields inside blocks**, `localization: 'layout'` as an option |
| D5 | Default slugs: plain (`faq`, `hero`) or prefixed (`ipalFaq`) | **plain**, with a `slug` option for clashes — data stays readable and matches what sites use |
| D6 | Phase 1 scope: the 15 blocks in §5.2 | **yes**; `video`, `tabs`, `map`, `cookieTable`, `comparisonTable` in phase 2 |
| D7 | Block picker thumbnails in the admin panel | **opt-in** (`thumbnails: true`) |
| D8 | Move existing sites onto the library, or new sites only | **new sites + the reference site now**; old sites move block by block when they get work, with ipal-migrate-fields recipes, never as a big-bang |
| D9 | Testimonials: inline items only, or also a relation to a `testimonials` collection | **both**, collection mode only when the project names the collection |
| D10 | Panel name for the stats block ("Statistics" is the glossary word for visit counting) | **"Key figures" / "Liczby"** |
## 13. As built — differences from this proposal
- **No `/blocks/client` entry.** No block needed its own client code: FAQ is `<details>`, the gallery uses the
lightbox's `LightboxTrigger`, the table of contents is the rich-text module's.
- **`next/image` and `next/link` are passed in** (`createBlockRegistry(content, { Image, Link })`), because the plugin
never imports `next/*`. Without them the blocks render a plain `<img>` (width, height, lazy, focal point) and `<a>`.
- **No pinned `dbName`.** A fixed table name would clash when one block is used in two collections. Database names
come only from slugs and field names (never labels), and the schema snapshot test guards them.
- **Contact needs no `blockProps`:** the block reads the form texts and link options from lib/content itself; only
`sendForm` is passed to the registry.
- **`ui` primitives:** `Button` is the `buttonClass` function (a look, not an element); `Anchor` and `TitleLink` were
added so internal links can use next/link and a card title stays text when its link is dead.
- **Admin wording:** the new admin-ux test over the library found two 4-word labels in existing builders —
the link checkbox is now "New tab" (with a description) and the table-of-contents switch "Show contents".
- **Seeder:** `{ $form: 'title' }` references are deferred to the second pass like `$page`, so a page with a form
never reaches the database with an unresolved reference.
+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)
+6 -2
View File
@@ -194,11 +194,14 @@ process.exit(seed.summary().errors ? 1 : 0)
**Seed values.** Write each value once, every language side by side. An object whose keys are all
locale codes is one value per locale (`{ pl: 'Kontakt', en: 'Contact' }`); anything else is the same
in every locale. A locale missing from such an object is left untouched in that locale.
`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`.
`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`;
`{ $form: 'Contact form' }` becomes the ID of the form with that title (seed the form first). A missing form
is an error for that record, never an empty relation. Ready pages made of library blocks:
`pageTemplates` in [block-library.md](./block-library.md#page-templates).
| Method | What it does |
|---|---|
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (without fields that hold `$page` links), then every record gets its full content, so pages can link to each other in any order |
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (without fields that hold `$page` / `$form` links), then every record gets its full content, so pages can link to each other in any order |
| `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) |
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). With `update` and an untouched global: every seeded field |
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` |
@@ -245,6 +248,7 @@ the script:
| `SEED_HASH_FIELD` | `editCheck.hashField` | `seedHash` | the hash field name; empty / `false` = timestamps only |
| — | `context` | `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }` all `true` | merged over the defaults; set a key to `false` to drop it |
| — | `pagesCollection` | `pages` | the collection `{ $page }` links resolve in |
| — | `formsCollection` | `forms` | the collection `{ $form }` links resolve in (by `title`) |
| — | `label`, `log` | `[seed]`, stdout | line prefix and where lines go |
| `SEED_NOTIFY_EMAIL` | — | — | form seed: notification address for a first run when the company global is still empty |
+18 -1
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",
@@ -64,12 +79,14 @@
"types": "./dist/index.d.ts",
"bin": {
"ipal-skills": "bin/ipal-skills.mjs",
"ipal-blocks": "bin/ipal-blocks.mjs",
"ipal-tokens": "bin/ipal-tokens.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 } : {}) }
}
+109
View File
@@ -0,0 +1,109 @@
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. */
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>>
/** The 15 slugs in the order of the block picker: the sections every site needs first. */
export const LIBRARY_BLOCK_SLUGS: readonly LibraryBlockSlug[] = [
'hero',
'textMedia',
'featureGrid',
'cta',
'richText',
'faq',
'contact',
'gallery',
'testimonials',
'stats',
'steps',
'logos',
'team',
'pricing',
'entryList',
]
/** 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
}
+119
View File
@@ -0,0 +1,119 @@
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 { NoSnippet } from '../seo/NoSnippet.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
/**
* Blocks kept out of Google's snippets (`data-nosnippet`) — for sections repeated on every page,
* e.g. `['cta']`, so the same call to action is not quoted under every result. Default none.
*/
noSnippet?: readonly LibraryBlockSlug[]
/** 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 = {}, noSnippet = [], 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 hidden = noSnippet.includes(slug)
const bound = (props: Record<string, unknown>) => {
const block = <Block {...props} classNames={classNames[slug]} ctx={ctx} ui={ui} />
return hidden ? <NoSnippet>{block}</NoSnippet> : block
}
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
+305
View File
@@ -0,0 +1,305 @@
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('styling: every token utility the blocks use exists in the preset', () => {
test('colours, radii, spacing and widths come from tailwind.css', () => {
const preset = readFileSync(path.join(root, 'src/styles/tailwind.css'), 'utf8')
const theme = (ns: string) => new Set([...preset.matchAll(new RegExp(`--${ns}-([\\w-]+?)(?:--[\\w-]+)?:`, 'g'))].map((m) => m[1]))
const colors = theme('color')
const radii = new Set(['full', 'none', ...theme('radius')])
const spacing = theme('spacing')
const widths = new Set(['full', 'md', 'none', ...theme('container')])
const text = new Set(['center', 'left', 'right', ...theme('text')])
const problems: string[] = []
const classes = libraryFiles().filter((f) => !f.endsWith('thumbnails.ts')).flatMap((file) =>
[...readFileSync(file, 'utf8').matchAll(/'([^'\n]*)'|"([^"\n]*)"/g)].flatMap((m) => (m[1] ?? m[2] ?? '').split(/\s+/).map((c) => [path.relative(root, file), c] as const)),
)
for (const [file, raw] of classes) {
const c = raw.replace(/^(?:[a-z0-9@-]+:)+/, '') // drop variants: hover:, md:, group-open:, after:
let m: null | RegExpMatchArray
if ((m = c.match(/^(?:bg|text|border|from|to|outline|ring|before:text)-([a-z][\w-]*)$/)) && !/^(?:\d|[blrtxy](?:-|$)|offset|linear|transparent|inherit|current)/.test(m[1])) {
const name = m[1]
const known = colors.has(name) || (c.startsWith('text-') && text.has(name)) || (c.startsWith('border-') && /^\d+$/.test(name))
if (!known) {problems.push(`${file}: ${raw} (no --color-${name})`)}
} else if ((m = c.match(/^rounded-([a-z][\w-]*)$/)) && !radii.has(m[1])) {problems.push(`${file}: ${raw}`)}
else if ((m = c.match(/^(?:p[xytblr]?|m[xytblr]?|gap(?:-[xy])?|space-y)-([a-z][a-z-]*)$/)) && !['auto', 'px'].includes(m[1]) && !spacing.has(m[1])) {problems.push(`${file}: ${raw}`)}
else if ((m = c.match(/^max-w-([a-z][\w-]*)$/)) && !widths.has(m[1])) {problems.push(`${file}: ${raw}`)}
}
expect(problems).toEqual([])
})
})
describe('ipal-blocks eject', () => {
const tmp = mkdtempSync(path.join(os.tmpdir(), 'ipal-eject-'))
afterAll(() => rmSync(tmp, { force: true, recursive: true }))
/** Names an entry file exports. */
const exportsOf = (file: string) => {
const src = readFileSync(path.join(root, file), 'utf8')
return new Set([...src.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)].flatMap((m) => m[1].split(',').map((s) => s.trim().replace(/^type\s+/, '').split(/\s+as\s+/).pop()!)).filter(Boolean))
}
const ENTRIES: Record<string, Set<string>> = {
'@intecion/ipal-kit': exportsOf('src/index.ts'),
'@intecion/ipal-kit/blocks': exportsOf('src/exports/blocks.ts'),
'@intecion/ipal-kit/blocks/rsc': exportsOf('src/exports/blocks-rsc.ts'),
'@intecion/ipal-kit/client': exportsOf('src/exports/client.ts'),
'@intecion/ipal-kit/rsc': exportsOf('src/exports/rsc.ts'),
}
test('every block ejects with imports that exist in the package entries', () => {
const problems: string[] = []
for (const slug of LIBRARY_BLOCK_SLUGS) {
execFileSync('node', [path.join(root, 'bin/ipal-blocks.mjs'), 'eject', slug, '--dest', tmp], { cwd: tmp, stdio: 'pipe' })
const dir = path.join(tmp, slug[0].toUpperCase() + slug.slice(1))
for (const file of readdirSync(dir)) {
const src = readFileSync(path.join(dir, file), 'utf8')
if (/from '\.\.?\//.test(src)) {problems.push(`${slug}/${file}: relative import left`)}
for (const m of src.matchAll(/import (?:type )?\{([^}]*)\} from '(@intecion\/ipal-kit[^']*)'/g)) {
const entry = ENTRIES[m[2]]
if (!entry) {
problems.push(`${slug}/${file}: unknown entry ${m[2]}`)
continue
}
for (const name of m[1].split(',').map((s) => s.trim()).filter(Boolean)) {
if (!entry.has(name)) {problems.push(`${slug}/${file}: ${name} not exported from ${m[2]}`)}
}
}
}
}
expect(problems).toEqual([])
})
test('an existing file is never overwritten', () => {
const out = execFileSync('node', [path.join(root, 'bin/ipal-blocks.mjs'), 'eject', 'faq', '--dest', tmp], { cwd: tmp, encoding: 'utf8', stdio: 'pipe' })
expect(out).not.toMatch(/^write /m)
})
})
+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/)
})
})
+257
View File
@@ -0,0 +1,257 @@
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('noSnippet keeps a repeated section out of search snippets', async () => {
const map = createBlockRegistry(content, { noSnippet: ['cta'] })
expect(await render(h(map.cta, { blockType: 'cta', header, locale: 'en', ...SAMPLES.cta }))).toMatch(/^<div><div data-nosnippet="">/)
expect(await render(block('cta'))).not.toContain('data-nosnippet')
})
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())
})
})
+3
View File
@@ -16,12 +16,15 @@ const read = (p: string) => readFileSync(path.join(root, p), 'utf8')
const ENTRIES: Record<string, string> = {
'': 'src/index.ts',
'/admin': 'src/exports/admin.ts',
'/blocks': 'src/exports/blocks.ts',
'/blocks/rsc': 'src/exports/blocks-rsc.ts',
'/client': 'src/exports/client.ts',
'/env': 'src/exports/env.ts',
'/next/middleware': 'src/exports/next-middleware.ts',
'/rsc': 'src/exports/rsc.ts',
'/seed': 'src/exports/seed.ts',
'/server': 'src/exports/server.ts',
'/templates': 'src/exports/templates.ts',
'/tokens': 'src/exports/tokens.ts',
}
+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 },
],