Block library: 15 blocks, registry, primitives, templates, manifest, eject
- @intecion/ipal-kit/blocks: libraryBlocks() opt-in, one builder per block, field
builders, option merging, blockLibraryManifest, faqItemsFromLayout
- @intecion/ipal-kit/blocks/rsc: createBlockRegistry, the block components and UI
primitives (token utilities only; next/image and next/link passed in)
- @intecion/ipal-kit/templates: 10 page templates as createSeeder data
- createSeeder: { $form: title } references
- ipal-blocks eject <block>
- tests: options, rendering and a11y per block, Payload + seeding, GraphQL, admin
wording, schema snapshot (versioning), eject imports
- shorter admin labels: link "New tab", table of contents "Show contents"
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
7918eaf6d4
commit
2d1cc0e77d
@@ -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,
|
||||
})
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 })
|
||||
@@ -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() }))
|
||||
}
|
||||
@@ -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 } : {}) }
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { Block } from 'payload'
|
||||
|
||||
import type { ContactOptions } from './blocks/contact/config.js'
|
||||
import type { EntryListOptions } from './blocks/entryList/config.js'
|
||||
import type { FeatureGridOptions } from './blocks/featureGrid/config.js'
|
||||
import type { TestimonialsOptions } from './blocks/testimonials/config.js'
|
||||
import type { BlockBuilder, BlockOptions, LibraryBlockSetting, LibraryBlockSlug, LibraryBlocksShared } from './types.js'
|
||||
|
||||
import { buildContactBlock } from './blocks/contact/config.js'
|
||||
import { buildCtaBlock } from './blocks/cta/config.js'
|
||||
import { buildEntryListBlock } from './blocks/entryList/config.js'
|
||||
import { buildFaqBlock } from './blocks/faq/config.js'
|
||||
import { buildFeatureGridBlock } from './blocks/featureGrid/config.js'
|
||||
import { buildGalleryBlock } from './blocks/gallery/config.js'
|
||||
import { buildHeroBlock } from './blocks/hero/config.js'
|
||||
import { buildLogosBlock } from './blocks/logos/config.js'
|
||||
import { buildPricingBlock } from './blocks/pricing/config.js'
|
||||
import { buildRichTextBlock } from './blocks/richText/config.js'
|
||||
import { buildStatsBlock } from './blocks/stats/config.js'
|
||||
import { buildStepsBlock } from './blocks/steps/config.js'
|
||||
import { buildTeamBlock } from './blocks/team/config.js'
|
||||
import { buildTestimonialsBlock } from './blocks/testimonials/config.js'
|
||||
import { buildTextMediaBlock } from './blocks/textMedia/config.js'
|
||||
|
||||
/** Every library block builder, by default slug, in the order of the block picker. */
|
||||
export const LIBRARY_BLOCK_BUILDERS = {
|
||||
contact: buildContactBlock,
|
||||
cta: buildCtaBlock,
|
||||
entryList: buildEntryListBlock,
|
||||
faq: buildFaqBlock,
|
||||
featureGrid: buildFeatureGridBlock,
|
||||
gallery: buildGalleryBlock,
|
||||
hero: buildHeroBlock,
|
||||
logos: buildLogosBlock,
|
||||
pricing: buildPricingBlock,
|
||||
richText: buildRichTextBlock,
|
||||
stats: buildStatsBlock,
|
||||
steps: buildStepsBlock,
|
||||
team: buildTeamBlock,
|
||||
testimonials: buildTestimonialsBlock,
|
||||
textMedia: buildTextMediaBlock,
|
||||
} satisfies Record<LibraryBlockSlug, BlockBuilder<never>>
|
||||
|
||||
export const LIBRARY_BLOCK_SLUGS = Object.keys(LIBRARY_BLOCK_BUILDERS) as LibraryBlockSlug[]
|
||||
|
||||
/** What `libraryBlocks` takes: a setting per block. Blocks not listed are off. */
|
||||
export type LibraryBlocksOptions = {
|
||||
contact?: LibraryBlockSetting<ContactOptions>
|
||||
cta?: LibraryBlockSetting
|
||||
entryList?: LibraryBlockSetting<EntryListOptions>
|
||||
faq?: LibraryBlockSetting
|
||||
featureGrid?: LibraryBlockSetting<FeatureGridOptions>
|
||||
gallery?: LibraryBlockSetting
|
||||
hero?: LibraryBlockSetting
|
||||
logos?: LibraryBlockSetting
|
||||
pricing?: LibraryBlockSetting
|
||||
richText?: LibraryBlockSetting
|
||||
stats?: LibraryBlockSetting
|
||||
steps?: LibraryBlockSetting
|
||||
team?: LibraryBlockSetting
|
||||
testimonials?: LibraryBlockSetting<TestimonialsOptions>
|
||||
textMedia?: LibraryBlockSetting
|
||||
}
|
||||
|
||||
/**
|
||||
* The library blocks the project turned on, ready for a `blocks` field:
|
||||
*
|
||||
* { name: 'layout', type: 'blocks', blocks: [...libraryBlocks({ hero: true, faq: { maxItems: 10 } }), MyBlock] }
|
||||
*
|
||||
* Nothing is on by default. `shared` applies to every block (a block's own options win).
|
||||
*/
|
||||
export function libraryBlocks(options: LibraryBlocksOptions, shared: LibraryBlocksShared = {}): Block[] {
|
||||
return LIBRARY_BLOCK_SLUGS.flatMap((slug) => {
|
||||
const setting = options[slug] as LibraryBlockSetting | undefined
|
||||
if (!setting) {return []}
|
||||
const build = LIBRARY_BLOCK_BUILDERS[slug] as BlockBuilder
|
||||
if (typeof setting === 'function') {return [setting(build(shared))]}
|
||||
const own: BlockOptions = setting === true ? {} : setting
|
||||
return [build({ ...shared, ...own, settings: own.settings ?? shared.settings })]
|
||||
})
|
||||
}
|
||||
|
||||
/** The block slugs `libraryBlocks(options)` turns on, with the project's renames — for templates and the registry. */
|
||||
export function libraryBlockSlugs(options: LibraryBlocksOptions): Partial<Record<LibraryBlockSlug, string>> {
|
||||
const out: Partial<Record<LibraryBlockSlug, string>> = {}
|
||||
for (const slug of LIBRARY_BLOCK_SLUGS) {
|
||||
const setting = options[slug]
|
||||
if (!setting) {continue}
|
||||
out[slug] = typeof setting === 'object' && setting.slug ? setting.slug : slug
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { ComponentType } from 'react'
|
||||
|
||||
import type { BlockComponentMap } from '../blocks/types.js'
|
||||
import type { BlockContent, BlockContext, BlockUi } from './context.js'
|
||||
import type { LibraryBlockSlug } from './types.js'
|
||||
import type { CMSLinkProps } from './ui/CMSLink.js'
|
||||
import type { PartClasses } from './ui/cx.js'
|
||||
import type { MediaProps } from './ui/Media.js'
|
||||
import type { SectionProps } from './ui/Section.js'
|
||||
|
||||
import { ContactBlock } from './blocks/contact/Component.js'
|
||||
import { CtaBlock } from './blocks/cta/Component.js'
|
||||
import { EntryListBlock } from './blocks/entryList/Component.js'
|
||||
import { FaqBlock } from './blocks/faq/Component.js'
|
||||
import { FeatureGridBlock } from './blocks/featureGrid/Component.js'
|
||||
import { GalleryBlock } from './blocks/gallery/Component.js'
|
||||
import { HeroBlock } from './blocks/hero/Component.js'
|
||||
import { LogosBlock } from './blocks/logos/Component.js'
|
||||
import { PricingBlock } from './blocks/pricing/Component.js'
|
||||
import { RichTextBlock } from './blocks/richText/Component.js'
|
||||
import { StatsBlock } from './blocks/stats/Component.js'
|
||||
import { StepsBlock } from './blocks/steps/Component.js'
|
||||
import { TeamBlock } from './blocks/team/Component.js'
|
||||
import { TestimonialsBlock } from './blocks/testimonials/Component.js'
|
||||
import { TextMediaBlock } from './blocks/textMedia/Component.js'
|
||||
import { buttonClass } from './ui/Button.js'
|
||||
import { Card } from './ui/Card.js'
|
||||
import { CMSLink } from './ui/CMSLink.js'
|
||||
import { Container } from './ui/Container.js'
|
||||
import { Media } from './ui/Media.js'
|
||||
import { Section, SECTION_BACKGROUNDS } from './ui/Section.js'
|
||||
import { SectionHeader } from './ui/SectionHeader.js'
|
||||
|
||||
/** The plugin's component for each library block, by default slug. */
|
||||
export const LIBRARY_BLOCK_COMPONENTS = {
|
||||
contact: ContactBlock,
|
||||
cta: CtaBlock,
|
||||
entryList: EntryListBlock,
|
||||
faq: FaqBlock,
|
||||
featureGrid: FeatureGridBlock,
|
||||
gallery: GalleryBlock,
|
||||
hero: HeroBlock,
|
||||
logos: LogosBlock,
|
||||
pricing: PricingBlock,
|
||||
richText: RichTextBlock,
|
||||
stats: StatsBlock,
|
||||
steps: StepsBlock,
|
||||
team: TeamBlock,
|
||||
testimonials: TestimonialsBlock,
|
||||
textMedia: TextMediaBlock,
|
||||
} as const
|
||||
|
||||
export type BlockRegistryOptions = {
|
||||
/** Section backgrounds (`settings.background` values) → classes, merged over the defaults. */
|
||||
backgrounds?: Record<string, string>
|
||||
/** Classes per block part, replacing that part's defaults: `{ faq: { item: 'border-b border-border' } }`. */
|
||||
classNames?: Partial<Record<LibraryBlockSlug, PartClasses>>
|
||||
/** Replace a block's component. It gets the same props (data, locale, isFirst, ui, ctx, classNames). */
|
||||
components?: Partial<Record<LibraryBlockSlug, ComponentType<never>>>
|
||||
/** The project's own blocks, in the same registry. */
|
||||
extra?: BlockComponentMap
|
||||
/** Turn on only these library blocks. Default: all 15 (an unused entry costs nothing). */
|
||||
only?: readonly LibraryBlockSlug[]
|
||||
/** Renamed slugs (BlockOptions `slug`), so the registry key matches the stored blockType. */
|
||||
slugs?: Partial<Record<LibraryBlockSlug, string>>
|
||||
/** Swap UI primitives for every library block (e.g. the project's own Media). */
|
||||
ui?: Partial<BlockUi>
|
||||
} & Omit<BlockContext, 'content' | 'lightbox'> & Partial<Pick<BlockContext, 'lightbox'>>
|
||||
|
||||
/**
|
||||
* The `blockType → component` map for RenderBlocks / createPageRoute, with the library
|
||||
* blocks bound to the project's lib/content and options:
|
||||
*
|
||||
* // src/blocks/registry.ts
|
||||
* export const blockRegistry = createBlockRegistry(content, { sendForm, extra: { timeline: Timeline } })
|
||||
*
|
||||
* Everything is bound on the server, so no function crosses to the client.
|
||||
*/
|
||||
export function createBlockRegistry(content: BlockContent, options: BlockRegistryOptions = {}): BlockComponentMap {
|
||||
const { backgrounds, classNames = {}, components = {}, extra = {}, only, slugs = {}, ui: own = {}, ...rest } = options
|
||||
const ctx: BlockContext = { ...rest, content, lightbox: rest.lightbox ?? true }
|
||||
const ui = buildUi(ctx, own, backgrounds)
|
||||
const map: BlockComponentMap = {}
|
||||
for (const slug of only ?? (Object.keys(LIBRARY_BLOCK_COMPONENTS) as LibraryBlockSlug[])) {
|
||||
const Block = (components[slug] ?? LIBRARY_BLOCK_COMPONENTS[slug]) as ComponentType<Record<string, unknown>>
|
||||
const bound = (props: Record<string, unknown>) => <Block {...props} classNames={classNames[slug]} ctx={ctx} ui={ui} />
|
||||
bound.displayName = `Library(${slug})`
|
||||
map[slugs[slug] ?? slug] = bound
|
||||
}
|
||||
return { ...map, ...extra }
|
||||
}
|
||||
|
||||
/** The plugin's primitives, with lib/content's resolveLink and the project's buttons and backgrounds bound in. */
|
||||
function buildUi(ctx: BlockContext, own: Partial<BlockUi>, backgrounds?: Record<string, string>): BlockUi {
|
||||
const buttons = own.buttonClass ?? buttonClass
|
||||
const sectionBackgrounds = { ...SECTION_BACKGROUNDS, ...backgrounds }
|
||||
const BoundLink = (props: CMSLinkProps) => <CMSLink {...props} buttonClass={buttons} Link={ctx.Link} resolve={ctx.content.resolveLink} />
|
||||
const BoundMedia = (props: MediaProps) => <Media {...props} Image={ctx.Image} />
|
||||
const BoundSection = (props: SectionProps) => <Section backgrounds={sectionBackgrounds} {...props} />
|
||||
return {
|
||||
buttonClass: buttons,
|
||||
Card: own.Card ?? Card,
|
||||
CMSLink: own.CMSLink ?? BoundLink,
|
||||
Container: own.Container ?? Container,
|
||||
Media: own.Media ?? BoundMedia,
|
||||
Section: own.Section ?? BoundSection,
|
||||
SectionHeader: own.SectionHeader ?? SectionHeader,
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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))
|
||||
@@ -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)}`
|
||||
}
|
||||
@@ -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'>
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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',
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
}
|
||||
@@ -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" />
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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' },
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user