From 2d1cc0e77d764877dd9d953716f31a76d1d5ea94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 14:05:47 +0100 Subject: [PATCH] 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 - 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 --- bin/ipal-blocks.mjs | 102 ++ docs/richtext.md | 2 +- package.json | 21 +- src/exports/blocks-rsc.ts | 63 + src/exports/blocks.ts | 50 + src/exports/templates.ts | 8 + .../blocks/contact/Component.tsx | 70 + .../block-library/blocks/contact/config.ts | 30 + .../block-library/blocks/cta/Component.tsx | 50 + .../block-library/blocks/cta/config.ts | 17 + .../blocks/entryList/Component.tsx | 80 + .../block-library/blocks/entryList/config.ts | 63 + .../block-library/blocks/faq/Component.tsx | 44 + .../block-library/blocks/faq/config.ts | 24 + .../blocks/featureGrid/Component.tsx | 70 + .../blocks/featureGrid/config.ts | 42 + .../blocks/gallery/Component.tsx | 58 + .../block-library/blocks/gallery/config.ts | 26 + .../block-library/blocks/hero/Component.tsx | 54 + .../block-library/blocks/hero/config.ts | 27 + .../block-library/blocks/logos/Component.tsx | 50 + .../block-library/blocks/logos/config.ts | 27 + .../blocks/pricing/Component.tsx | 72 + .../block-library/blocks/pricing/config.ts | 58 + .../blocks/richText/Component.tsx | 41 + .../block-library/blocks/richText/config.ts | 15 + .../block-library/blocks/stats/Component.tsx | 42 + .../block-library/blocks/stats/config.ts | 29 + .../block-library/blocks/steps/Component.tsx | 50 + .../block-library/blocks/steps/config.ts | 23 + .../block-library/blocks/team/Component.tsx | 49 + .../block-library/blocks/team/config.ts | 34 + .../blocks/testimonials/Component.tsx | 72 + .../blocks/testimonials/config.ts | 70 + .../blocks/textMedia/Component.tsx | 39 + .../block-library/blocks/textMedia/config.ts | 16 + src/modules/block-library/context.ts | 76 + src/modules/block-library/data.ts | 31 + src/modules/block-library/define.ts | 49 + src/modules/block-library/faq.ts | 17 + src/modules/block-library/fields.ts | 103 ++ src/modules/block-library/library.ts | 92 ++ src/modules/block-library/manifest.ts | 87 + src/modules/block-library/options.ts | 73 + src/modules/block-library/registry.tsx | 109 ++ src/modules/block-library/shared.ts | 22 + src/modules/block-library/templates/build.ts | 101 ++ src/modules/block-library/templates/index.ts | 21 + src/modules/block-library/templates/pages.ts | 128 ++ src/modules/block-library/texts.ts | 23 + src/modules/block-library/thumbnails.ts | 33 + src/modules/block-library/types.ts | 77 + src/modules/block-library/ui/Anchor.tsx | 20 + src/modules/block-library/ui/Button.ts | 19 + src/modules/block-library/ui/Buttons.tsx | 29 + src/modules/block-library/ui/CMSLink.tsx | 40 + src/modules/block-library/ui/Card.tsx | 13 + src/modules/block-library/ui/Container.tsx | 18 + src/modules/block-library/ui/Media.tsx | 40 + src/modules/block-library/ui/Section.tsx | 47 + .../block-library/ui/SectionHeader.tsx | 35 + src/modules/block-library/ui/TitleLink.tsx | 22 + src/modules/block-library/ui/cx.ts | 11 + src/modules/links/buildLinkField.ts | 8 +- src/modules/richtext/headings.ts | 2 +- src/modules/seed/seeder.ts | 21 +- test/adminUx.test.ts | 12 + test/block-library.schema.json | 1393 +++++++++++++++++ test/blockLibrary.test.ts | 277 ++++ test/blockLibraryPayload.test.ts | 134 ++ test/blockLibraryRender.test.ts | 251 +++ test/blockLibrarySchema.test.ts | 66 + test/graphqlSchema.test.ts | 12 +- 73 files changed, 5091 insertions(+), 9 deletions(-) create mode 100644 bin/ipal-blocks.mjs create mode 100644 src/exports/blocks-rsc.ts create mode 100644 src/exports/blocks.ts create mode 100644 src/exports/templates.ts create mode 100644 src/modules/block-library/blocks/contact/Component.tsx create mode 100644 src/modules/block-library/blocks/contact/config.ts create mode 100644 src/modules/block-library/blocks/cta/Component.tsx create mode 100644 src/modules/block-library/blocks/cta/config.ts create mode 100644 src/modules/block-library/blocks/entryList/Component.tsx create mode 100644 src/modules/block-library/blocks/entryList/config.ts create mode 100644 src/modules/block-library/blocks/faq/Component.tsx create mode 100644 src/modules/block-library/blocks/faq/config.ts create mode 100644 src/modules/block-library/blocks/featureGrid/Component.tsx create mode 100644 src/modules/block-library/blocks/featureGrid/config.ts create mode 100644 src/modules/block-library/blocks/gallery/Component.tsx create mode 100644 src/modules/block-library/blocks/gallery/config.ts create mode 100644 src/modules/block-library/blocks/hero/Component.tsx create mode 100644 src/modules/block-library/blocks/hero/config.ts create mode 100644 src/modules/block-library/blocks/logos/Component.tsx create mode 100644 src/modules/block-library/blocks/logos/config.ts create mode 100644 src/modules/block-library/blocks/pricing/Component.tsx create mode 100644 src/modules/block-library/blocks/pricing/config.ts create mode 100644 src/modules/block-library/blocks/richText/Component.tsx create mode 100644 src/modules/block-library/blocks/richText/config.ts create mode 100644 src/modules/block-library/blocks/stats/Component.tsx create mode 100644 src/modules/block-library/blocks/stats/config.ts create mode 100644 src/modules/block-library/blocks/steps/Component.tsx create mode 100644 src/modules/block-library/blocks/steps/config.ts create mode 100644 src/modules/block-library/blocks/team/Component.tsx create mode 100644 src/modules/block-library/blocks/team/config.ts create mode 100644 src/modules/block-library/blocks/testimonials/Component.tsx create mode 100644 src/modules/block-library/blocks/testimonials/config.ts create mode 100644 src/modules/block-library/blocks/textMedia/Component.tsx create mode 100644 src/modules/block-library/blocks/textMedia/config.ts create mode 100644 src/modules/block-library/context.ts create mode 100644 src/modules/block-library/data.ts create mode 100644 src/modules/block-library/define.ts create mode 100644 src/modules/block-library/faq.ts create mode 100644 src/modules/block-library/fields.ts create mode 100644 src/modules/block-library/library.ts create mode 100644 src/modules/block-library/manifest.ts create mode 100644 src/modules/block-library/options.ts create mode 100644 src/modules/block-library/registry.tsx create mode 100644 src/modules/block-library/shared.ts create mode 100644 src/modules/block-library/templates/build.ts create mode 100644 src/modules/block-library/templates/index.ts create mode 100644 src/modules/block-library/templates/pages.ts create mode 100644 src/modules/block-library/texts.ts create mode 100644 src/modules/block-library/thumbnails.ts create mode 100644 src/modules/block-library/types.ts create mode 100644 src/modules/block-library/ui/Anchor.tsx create mode 100644 src/modules/block-library/ui/Button.ts create mode 100644 src/modules/block-library/ui/Buttons.tsx create mode 100644 src/modules/block-library/ui/CMSLink.tsx create mode 100644 src/modules/block-library/ui/Card.tsx create mode 100644 src/modules/block-library/ui/Container.tsx create mode 100644 src/modules/block-library/ui/Media.tsx create mode 100644 src/modules/block-library/ui/Section.tsx create mode 100644 src/modules/block-library/ui/SectionHeader.tsx create mode 100644 src/modules/block-library/ui/TitleLink.tsx create mode 100644 src/modules/block-library/ui/cx.ts create mode 100644 test/block-library.schema.json create mode 100644 test/blockLibrary.test.ts create mode 100644 test/blockLibraryPayload.test.ts create mode 100644 test/blockLibraryRender.test.ts create mode 100644 test/blockLibrarySchema.test.ts diff --git a/bin/ipal-blocks.mjs b/bin/ipal-blocks.mjs new file mode 100644 index 0000000..f9ea1cc --- /dev/null +++ b/bin/ipal-blocks.mjs @@ -0,0 +1,102 @@ +#!/usr/bin/env node +// ipal-blocks — the block library's command line. +// pnpm exec ipal-blocks list → the library blocks +// pnpm exec ipal-blocks eject faq → src/blocks/Faq/{config.ts,Component.tsx} +// pnpm exec ipal-blocks eject faq --dest src/blocks --dry-run +// Eject copies one block's source into the project, with its imports pointing at the +// package entries, so the project owns it: same slug and data shape, no migration. +// Then: use the ejected builder in Pages.layout instead of the library one, pass the ejected +// component as createBlockRegistry({ components: { faq: FaqBlock } }), record it in AGENTS.md. + +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join, relative, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const args = process.argv.slice(2) +const [command, slug] = args +const dryRun = args.includes('--dry-run') +const destArg = args.indexOf('--dest') +const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] : 'src/blocks') + +const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const libRoot = join(pkgRoot, 'src/modules/block-library') +const blocksRoot = join(libRoot, 'blocks') + +if (!command || command === '--help' || command === '-h') { + console.log('Usage: ipal-blocks list | ipal-blocks eject [--dest src/blocks] [--dry-run]') + process.exit(0) +} + +const slugs = existsSync(blocksRoot) ? readdirSync(blocksRoot).sort() : [] + +if (command === 'list') { + console.log(slugs.join('\n')) + process.exit(0) +} + +if (command !== 'eject' || !slug) { + console.error('Usage: ipal-blocks eject ') + process.exit(1) +} +if (!slugs.includes(slug)) { + console.error(`Unknown block "${slug}". Blocks: ${slugs.join(', ')}`) + process.exit(1) +} + +/** + * Where an import inside the library goes in a project, by the file it points at. + * Config files (no React) take the Payload-side entries; components take /rsc and /client. + */ +const ROOT = '@intecion/ipal-kit' +const BLOCKS = '@intecion/ipal-kit/blocks' +const RSC = '@intecion/ipal-kit/blocks/rsc' +function target(file, isComponent) { + const rel = relative(join(pkgRoot, 'src/modules'), file).replace(/\\/g, '/').replace(/\.js$/, '') + if (rel.startsWith('block-library/')) { + const inner = rel.slice('block-library/'.length) + if (/^(define|fields|options|shared|types|faq|library|manifest|thumbnails)$/.test(inner)) {return BLOCKS} + return RSC // context, data, texts, ui/* + } + if (rel === 'lightbox/LightboxProvider' || rel === 'richtext/TableOfContents') {return '@intecion/ipal-kit/client'} + if (rel === 'forms/RenderForm' || rel === 'richtext/RenderRichText') {return '@intecion/ipal-kit/rsc'} + if (rel === 'richtext/headings') {return isComponent ? '@intecion/ipal-kit/rsc' : ROOT} + return ROOT +} + +/** Rewrites relative imports to package entries and merges imports of the same entry. */ +function rewrite(source, file) { + const isComponent = file.endsWith('.tsx') + const merged = new Map() + const body = source.replace(/^import (type )?\{([^}]*)\} from '(\.[^']+)'\n/gm, (_, type, names, spec) => { + const entry = target(resolve(dirname(file), spec), isComponent) + const key = `${type ? 'type ' : ''}${entry}` + const set = merged.get(key) ?? new Set() + for (const n of names.split(',').map((s) => s.trim()).filter(Boolean)) {set.add(n)} + merged.set(key, set) + return '' + }) + const lines = [...merged].map(([key, set]) => { + const [type, entry] = key.startsWith('type ') ? ['type ', key.slice(5)] : ['', key] + return `import ${type}{ ${[...set].sort().join(', ')} } from '${entry}'` + }) + return body.replace(/^((?:import [^\n]*\n)*)/, (head) => `${head}${lines.join('\n')}\n`).replace(/\n{3,}/g, '\n\n') +} + +const folder = slug[0].toUpperCase() + slug.slice(1) +const outDir = join(dest, folder) +const files = readdirSync(join(blocksRoot, slug)).filter((f) => /\.(ts|tsx)$/.test(f)) +for (const name of files) { + const from = join(blocksRoot, slug, name) + const to = join(outDir, name) + if (existsSync(to)) { + console.error(`skip ${relative(process.cwd(), to)} (exists — delete it first to eject again)`) + continue + } + const out = `// Ejected from @intecion/ipal-kit (block library: ${slug}). The project owns this file now.\n${rewrite(readFileSync(from, 'utf8'), from)}` + console.log(`${dryRun ? 'would write' : 'write'} ${relative(process.cwd(), to)}`) + if (!dryRun) { + mkdirSync(outDir, { recursive: true }) + writeFileSync(to, out) + } +} +console.log(`\nNext: Pages.layout → the ejected build${folder}Block; registry → components: { ${slug}: ${folder}Block }; AGENTS.md → "Project decisions".`) diff --git a/docs/richtext.md b/docs/richtext.md index 1f86e11..c982035 100644 --- a/docs/richtext.md +++ b/docs/richtext.md @@ -86,7 +86,7 @@ const items = block.tableOfContents?.show ? extractHeadings(block.content) : [] (works without JS); in the browser the link of the section being read gets `aria-current="location"` and `classNames.linkActive`. `classNames`: `nav`, `label`, `list`, `item`, `link`, `linkActive`; `offset` (default 0.3 of the screen height); `data-ipal="toc"`, `data-level` on items. -- `buildTableOfContentsField({ name = 'tableOfContents' })` — a "Show table of contents" switch + a localized label (type `TableOfContentsSettings`). +- `buildTableOfContentsField({ name = 'tableOfContents' })` — a "Show contents" switch + a localized label (type `TableOfContentsSettings`). A new field in a block = a migration (`pnpm payload migrate:create`). ## Click-to-enlarge images (lightbox, opt-in) diff --git a/package.json b/package.json index d9cf0ca..d7ed665 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,11 @@ "types": "./dist/exports/seed.d.ts", "default": "./dist/exports/seed.js" }, + "./templates": { + "import": "./dist/exports/templates.js", + "types": "./dist/exports/templates.d.ts", + "default": "./dist/exports/templates.js" + }, "./next/middleware": { "import": "./dist/exports/next-middleware.js", "types": "./dist/exports/next-middleware.d.ts", @@ -44,6 +49,16 @@ "types": "./dist/exports/admin.d.ts", "default": "./dist/exports/admin.js" }, + "./blocks": { + "import": "./dist/exports/blocks.js", + "types": "./dist/exports/blocks.d.ts", + "default": "./dist/exports/blocks.js" + }, + "./blocks/rsc": { + "import": "./dist/exports/blocks-rsc.js", + "types": "./dist/exports/blocks-rsc.d.ts", + "default": "./dist/exports/blocks-rsc.js" + }, "./env": { "import": "./dist/exports/env.js", "types": "./dist/exports/env.d.ts", @@ -55,12 +70,14 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "bin": { - "ipal-skills": "bin/ipal-skills.mjs" + "ipal-skills": "bin/ipal-skills.mjs", + "ipal-blocks": "bin/ipal-blocks.mjs" }, "files": [ "dist", "docs", - "bin" + "bin", + "src/modules/block-library" ], "sideEffects": [ "**/*.css" diff --git a/src/exports/blocks-rsc.ts b/src/exports/blocks-rsc.ts new file mode 100644 index 0000000..175fae3 --- /dev/null +++ b/src/exports/blocks-rsc.ts @@ -0,0 +1,63 @@ +/** + * Entry point: @intecion/ipal-kit/blocks/rsc + * + * The block library's components (React Server Components), its UI primitives and + * createBlockRegistry. Schemas: '@intecion/ipal-kit/blocks'. Docs: docs/block-library.md. + * + * export const blockRegistry = createBlockRegistry(content, { Image, Link, sendForm }) + */ +export { CONTACT_PARTS, ContactBlock } from '../modules/block-library/blocks/contact/Component.js' +export type { ContactBlockData } from '../modules/block-library/blocks/contact/Component.js' +export { CTA_PARTS, CtaBlock } from '../modules/block-library/blocks/cta/Component.js' +export type { CtaBlockData } from '../modules/block-library/blocks/cta/Component.js' +export { defaultEntryCard, ENTRY_LIST_PARTS, EntryListBlock } from '../modules/block-library/blocks/entryList/Component.js' +export type { EntryListBlockData } from '../modules/block-library/blocks/entryList/Component.js' +export { FAQ_PARTS, FaqBlock } from '../modules/block-library/blocks/faq/Component.js' +export type { FaqBlockData, FaqItem } from '../modules/block-library/blocks/faq/Component.js' +export { FEATURE_GRID_PARTS, FeatureGridBlock } from '../modules/block-library/blocks/featureGrid/Component.js' +export type { FeatureGridBlockData, FeatureItem } from '../modules/block-library/blocks/featureGrid/Component.js' +export { GALLERY_PARTS, GalleryBlock } from '../modules/block-library/blocks/gallery/Component.js' +export type { GalleryBlockData, GalleryItem } from '../modules/block-library/blocks/gallery/Component.js' +export { HERO_PARTS, HeroBlock } from '../modules/block-library/blocks/hero/Component.js' +export type { HeroBlockData } from '../modules/block-library/blocks/hero/Component.js' +export { LOGOS_PARTS, LogosBlock } from '../modules/block-library/blocks/logos/Component.js' +export type { LogoItem, LogosBlockData } from '../modules/block-library/blocks/logos/Component.js' +export { PRICING_PARTS, PricingBlock } from '../modules/block-library/blocks/pricing/Component.js' +export type { PricingBlockData, PricingPlan } from '../modules/block-library/blocks/pricing/Component.js' +export { RICH_TEXT_PARTS, RichTextBlock } from '../modules/block-library/blocks/richText/Component.js' +export type { RichTextBlockData } from '../modules/block-library/blocks/richText/Component.js' +export { STATS_PARTS, StatsBlock } from '../modules/block-library/blocks/stats/Component.js' +export type { StatItem, StatsBlockData } from '../modules/block-library/blocks/stats/Component.js' +export { STEPS_PARTS, StepsBlock } from '../modules/block-library/blocks/steps/Component.js' +export type { StepItem, StepsBlockData } from '../modules/block-library/blocks/steps/Component.js' +export { TEAM_PARTS, TeamBlock } from '../modules/block-library/blocks/team/Component.js' +export type { TeamBlockData, TeamMember } from '../modules/block-library/blocks/team/Component.js' +export { defaultTestimonial, TESTIMONIALS_PARTS, TestimonialsBlock } from '../modules/block-library/blocks/testimonials/Component.js' +export type { TestimonialsBlockData } from '../modules/block-library/blocks/testimonials/Component.js' +export { TEXT_MEDIA_PARTS, TextMediaBlock } from '../modules/block-library/blocks/textMedia/Component.js' +export type { TextMediaBlockData } from '../modules/block-library/blocks/textMedia/Component.js' +export type { BlockContent, BlockContext, BlockUi, ContactDetail, EntryCard, LibraryBlockProps, TestimonialItem } from '../modules/block-library/context.js' +export type { BaseBlockData, LinkData, LinksData, MediaValue, RichTextData, SectionHeaderData, SectionSettingsData } from '../modules/block-library/data.js' +export { createBlockRegistry, LIBRARY_BLOCK_COMPONENTS } from '../modules/block-library/registry.js' +export type { BlockRegistryOptions } from '../modules/block-library/registry.js' +export { BLOCK_TEXTS, blockTexts, fillText } from '../modules/block-library/texts.js' +export type { BlockTexts } from '../modules/block-library/texts.js' +export { Anchor } from '../modules/block-library/ui/Anchor.js' +export type { LinkComponent } from '../modules/block-library/ui/Anchor.js' +export { BUTTON_CLASSES, buttonClass } from '../modules/block-library/ui/Button.js' +export { Buttons, GRID_COLUMNS, headingId } from '../modules/block-library/ui/Buttons.js' +export { Card, CARD_CLASS, CARD_INTERACTIVE_CLASS } from '../modules/block-library/ui/Card.js' +export type { CardProps } from '../modules/block-library/ui/Card.js' +export { CMSLink } from '../modules/block-library/ui/CMSLink.js' +export type { CMSLinkProps, ResolveLink } from '../modules/block-library/ui/CMSLink.js' +export { Container, CONTAINER_WIDTHS } from '../modules/block-library/ui/Container.js' +export type { ContainerProps, ContainerWidth } from '../modules/block-library/ui/Container.js' +export { cx, parts } from '../modules/block-library/ui/cx.js' +export type { PartClasses } from '../modules/block-library/ui/cx.js' +export { Media } from '../modules/block-library/ui/Media.js' +export type { ImageComponent, MediaProps } from '../modules/block-library/ui/Media.js' +export { Section, SECTION_BACKGROUNDS } from '../modules/block-library/ui/Section.js' +export type { SectionProps } from '../modules/block-library/ui/Section.js' +export { SectionHeader } from '../modules/block-library/ui/SectionHeader.js' +export type { HeadingLevel, SectionHeaderProps } from '../modules/block-library/ui/SectionHeader.js' +export { TitleLink } from '../modules/block-library/ui/TitleLink.js' diff --git a/src/exports/blocks.ts b/src/exports/blocks.ts new file mode 100644 index 0000000..71d55e1 --- /dev/null +++ b/src/exports/blocks.ts @@ -0,0 +1,50 @@ +/** + * Entry point: @intecion/ipal-kit/blocks + * + * The block library's Payload side — block configs and field builders, no React + * (safe in payload.config and collections). Components: '@intecion/ipal-kit/blocks/rsc'. + * Docs: docs/block-library.md. + * + * { name: 'layout', type: 'blocks', blocks: [...libraryBlocks({ hero: true, faq: true }), MyBlock] } + */ +export { buildContactBlock } from '../modules/block-library/blocks/contact/config.js' +export type { ContactOptions } from '../modules/block-library/blocks/contact/config.js' +export { buildCtaBlock } from '../modules/block-library/blocks/cta/config.js' +export { buildEntryListBlock } from '../modules/block-library/blocks/entryList/config.js' +export type { EntryListOptions } from '../modules/block-library/blocks/entryList/config.js' +export { buildFaqBlock } from '../modules/block-library/blocks/faq/config.js' +export { buildFeatureGridBlock } from '../modules/block-library/blocks/featureGrid/config.js' +export type { FeatureGridOptions } from '../modules/block-library/blocks/featureGrid/config.js' +export { buildGalleryBlock } from '../modules/block-library/blocks/gallery/config.js' +export { buildHeroBlock } from '../modules/block-library/blocks/hero/config.js' +export { buildLogosBlock } from '../modules/block-library/blocks/logos/config.js' +export { buildPricingBlock } from '../modules/block-library/blocks/pricing/config.js' +export { buildRichTextBlock } from '../modules/block-library/blocks/richText/config.js' +export { buildStatsBlock } from '../modules/block-library/blocks/stats/config.js' +export { buildStepsBlock } from '../modules/block-library/blocks/steps/config.js' +export { buildTeamBlock } from '../modules/block-library/blocks/team/config.js' +export { buildTestimonialsBlock } from '../modules/block-library/blocks/testimonials/config.js' +export type { TestimonialsOptions } from '../modules/block-library/blocks/testimonials/config.js' +export { buildTextMediaBlock } from '../modules/block-library/blocks/textMedia/config.js' +export { adminText, defineLibraryBlock, variantOption } from '../modules/block-library/define.js' +export type { LibraryBlockDefinition } from '../modules/block-library/define.js' +export { faqItemsFromLayout } from '../modules/block-library/faq.js' +export { buildContentField, buildIconField, buildItemsField, buildMediaField, buildVariantField } from '../modules/block-library/fields.js' +export type { IconFieldOptions, ItemsFieldOptions, MediaFieldOptions, VariantFieldOptions } from '../modules/block-library/fields.js' +export { LIBRARY_BLOCK_BUILDERS, LIBRARY_BLOCK_SLUGS, libraryBlocks, libraryBlockSlugs } from '../modules/block-library/library.js' +export type { LibraryBlocksOptions } from '../modules/block-library/library.js' +export { blockLibraryManifest, buildBlockLibraryManifest, fieldPaths } from '../modules/block-library/manifest.js' +export type { BlockLibraryManifest, ManifestBlock, ManifestField } from '../modules/block-library/manifest.js' +export { applyBlockOptions, isNamed, pickVariants, removeField, replaceField, stripLocalized } from '../modules/block-library/options.js' +export { COLUMNS, columnsField } from '../modules/block-library/shared.js' +export type { Columns } from '../modules/block-library/shared.js' +export { blockThumbnail } from '../modules/block-library/thumbnails.js' +export type { + BlockBuilder, + BlockLocalization, + BlockOptions, + LibraryBlockSetting, + LibraryBlockSlug, + LibraryBlocksShared, + VariantOption, +} from '../modules/block-library/types.js' diff --git a/src/exports/templates.ts b/src/exports/templates.ts new file mode 100644 index 0000000..c31ad3d --- /dev/null +++ b/src/exports/templates.ts @@ -0,0 +1,8 @@ +/** + * Entry point: @intecion/ipal-kit/templates + * + * Page templates made of library blocks — seed data for createSeeder ('@intecion/ipal-kit/seed'). + * Plain data, no React. Docs: docs/block-library.md "Page templates". + */ +export { pageTemplates, systemPageRefs } from '../modules/block-library/templates/index.js' +export type { TemplateBlock, TemplateOptions, TemplatePage, TemplateValue } from '../modules/block-library/templates/index.js' diff --git a/src/modules/block-library/blocks/contact/Component.tsx b/src/modules/block-library/blocks/contact/Component.tsx new file mode 100644 index 0000000..f124b37 --- /dev/null +++ b/src/modules/block-library/blocks/contact/Component.tsx @@ -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) { + 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 = ( +
+ +
+ ) + const aside = withDetails && (content || details.length) ? ( +
+ {content ? : null} + {details.length ? ( +
+ {details.map((d) => ( +
+
{d.label}
+
{d.href ? {d.value} : d.value}
+
+ ))} +
+ ) : null} +
+ ) : null + return ( + + + {aside ? ( +
+ {aside} + {formEl} +
+ ) : ( + formEl + )} +
+ ) +} diff --git a/src/modules/block-library/blocks/contact/config.ts b/src/modules/block-library/blocks/contact/config.ts new file mode 100644 index 0000000..6c0b666 --- /dev/null +++ b/src/modules/block-library/blocks/contact/config.ts @@ -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({ + 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, +}) diff --git a/src/modules/block-library/blocks/cta/Component.tsx b/src/modules/block-library/blocks/cta/Component.tsx new file mode 100644 index 0000000..ba2d53c --- /dev/null +++ b/src/modules/block-library/blocks/cta/Component.tsx @@ -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) { + 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 ( + +
+ + +
+
+ ) + } + return ( + +
+
+ + {v === 'split' ? : null} +
+ {v === 'split' ? ( + + ) : ( + + )} +
+
+ ) +} diff --git a/src/modules/block-library/blocks/cta/config.ts b/src/modules/block-library/blocks/cta/config.ts new file mode 100644 index 0000000..14a5907 --- /dev/null +++ b/src/modules/block-library/blocks/cta/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/entryList/Component.tsx b/src/modules/block-library/blocks/entryList/Component.tsx new file mode 100644 index 0000000..0b873fa --- /dev/null +++ b/src/modules/block-library/blocks/entryList/Component.tsx @@ -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): 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 } + +/** The latest entries of a collection, or entries chosen by hand; each card links to its entry. */ +export async function EntryListBlock(props: LibraryBlockProps) { + 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 }[] = [] + if (mode === 'selected') { + docs = (entries ?? []).flatMap((e) => (e?.value && typeof e.value === 'object' ? [{ collection: e.relationTo, doc: e.value as Record }] : [])) + } 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 ( + + +
    + {rows.map(({ card, collection: from, doc }, i) => ( +
  • + + {variant === 'list' ? null : } +
    + {card.date ? : null} +

    + + {card.title} + +

    + {card.text ?

    {card.text}

    : null} +
    +
    +
  • + ))} +
+ +
+ ) +} diff --git a/src/modules/block-library/blocks/entryList/config.ts b/src/modules/block-library/blocks/entryList/config.ts new file mode 100644 index 0000000..5578ba8 --- /dev/null +++ b/src/modules/block-library/blocks/entryList/config.ts @@ -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({ + 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, +}) diff --git a/src/modules/block-library/blocks/faq/Component.tsx b/src/modules/block-library/blocks/faq/Component.tsx new file mode 100644 index 0000000..890fd5d --- /dev/null +++ b/src/modules/block-library/blocks/faq/Component.tsx @@ -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
: keyboard and screen readers work with no script. */ +export function FaqBlock(props: LibraryBlockProps) { + 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 ( + + +
+ {shown.map((item, i) => ( +
+ + {item.question} + + + +

{item.answer}

+
+ ))} +
+ +
+ ) +} diff --git a/src/modules/block-library/blocks/faq/config.ts b/src/modules/block-library/blocks/faq/config.ts new file mode 100644 index 0000000..5ceb9c7 --- /dev/null +++ b/src/modules/block-library/blocks/faq/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/featureGrid/Component.tsx b/src/modules/block-library/blocks/featureGrid/Component.tsx new file mode 100644 index 0000000..cc1f54c --- /dev/null +++ b/src/modules/block-library/blocks/featureGrid/Component.tsx @@ -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) { + 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 ( + + + + {items.map((item, i) => ( +
  • + +
  • + ))} +
    + +
    + ) +} + +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 ? ( + + {item.heading} + + ) : ( + item.heading + ) + const body = ( + <> + {index ? {String(index).padStart(2, '0')} : null} + {Icon ? : null} + +

    {heading}

    + {item.text ?

    {item.text}

    : null} + + ) + if (plain) {return
    {body}
    } + return ( + + {body} + + ) +} diff --git a/src/modules/block-library/blocks/featureGrid/config.ts b/src/modules/block-library/blocks/featureGrid/config.ts new file mode 100644 index 0000000..3a43d75 --- /dev/null +++ b/src/modules/block-library/blocks/featureGrid/config.ts @@ -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({ + 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, +}) diff --git a/src/modules/block-library/blocks/gallery/Component.tsx b/src/modules/block-library/blocks/gallery/Component.tsx new file mode 100644 index 0000000..b19718c --- /dev/null +++ b/src/modules/block-library/blocks/gallery/Component.tsx @@ -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) { + 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 ( + + +
      + {shown.map((item, i) => { + const image = + const large = ctx.lightbox ? lightboxImage(item.media, item.caption ? { caption: item.caption } : {}) : null + return ( +
    • +
      + {large ? ( + + {image} + + ) : ( + image + )} + {item.caption ?
      {item.caption}
      : null} +
      +
    • + ) + })} +
    + +
    + ) +} diff --git a/src/modules/block-library/blocks/gallery/config.ts b/src/modules/block-library/blocks/gallery/config.ts new file mode 100644 index 0000000..a6233c7 --- /dev/null +++ b/src/modules/block-library/blocks/gallery/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/hero/Component.tsx b/src/modules/block-library/blocks/hero/Component.tsx new file mode 100644 index 0000000..bd2fd27 --- /dev/null +++ b/src/modules/block-library/blocks/hero/Component.tsx @@ -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) { + 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 = + const buttons = + + if (v === 'background') { + return ( + + + +
    + {title} + {buttons} +
    +
    + ) + } + const withMedia = v === 'split' && media + return ( + +
    +
    + {title} + {buttons} +
    + {withMedia ? : null} +
    +
    + ) +} diff --git a/src/modules/block-library/blocks/hero/config.ts b/src/modules/block-library/blocks/hero/config.ts new file mode 100644 index 0000000..50109a7 --- /dev/null +++ b/src/modules/block-library/blocks/hero/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/logos/Component.tsx b/src/modules/block-library/blocks/logos/Component.tsx new file mode 100644 index 0000000..256723f --- /dev/null +++ b/src/modules/block-library/blocks/logos/Component.tsx @@ -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) { + 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 ( + + +
      + {shown.map((item, i) => { + const logo = + return ( +
    • + {item.link ? ( + + {logo} + + ) : ( + logo + )} +
    • + ) + })} +
    +
    + ) +} diff --git a/src/modules/block-library/blocks/logos/config.ts b/src/modules/block-library/blocks/logos/config.ts new file mode 100644 index 0000000..248757a --- /dev/null +++ b/src/modules/block-library/blocks/logos/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/pricing/Component.tsx b/src/modules/block-library/blocks/pricing/Component.tsx new file mode 100644 index 0000000..875008d --- /dev/null +++ b/src/modules/block-library/blocks/pricing/Component.tsx @@ -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) { + 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 ( + + +
      + {items.map((plan, i) => ( +
    • + +
    • + ))} +
    + {note ?

    {note}

    : null} +
    + ) +} + +function Plan({ c, highlightLabel, locale, plan, ui }: { c: typeof PRICING_PARTS; highlightLabel?: null | string; locale: string; plan: PricingPlan; ui: BlockUi }) { + return ( + + {plan.highlighted && highlightLabel ?

    {highlightLabel}

    : null} +

    {plan.heading}

    +

    + {plan.price} {plan.period ? {plan.period} : null} +

    + {plan.text ?

    {plan.text}

    : null} + {plan.features?.length ? ( +
      + {plan.features.map((f, i) => ( +
    • {f.text}
    • + ))} +
    + ) : null} + {plan.link ?
    : null} +
    + ) +} diff --git a/src/modules/block-library/blocks/pricing/config.ts b/src/modules/block-library/blocks/pricing/config.ts new file mode 100644 index 0000000..4949635 --- /dev/null +++ b/src/modules/block-library/blocks/pricing/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/richText/Component.tsx b/src/modules/block-library/blocks/richText/Component.tsx new file mode 100644 index 0000000..bd98733 --- /dev/null +++ b/src/modules/block-library/blocks/richText/Component.tsx @@ -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) { + 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 = 0} /> + return ( + + + {toc.length ? ( +
    +
    + +
    +
    {text}
    +
    + ) : ( + text + )} +
    + ) +} diff --git a/src/modules/block-library/blocks/richText/config.ts b/src/modules/block-library/blocks/richText/config.ts new file mode 100644 index 0000000..147d0a1 --- /dev/null +++ b/src/modules/block-library/blocks/richText/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/stats/Component.tsx b/src/modules/block-library/blocks/stats/Component.tsx new file mode 100644 index 0000000..68cd7d2 --- /dev/null +++ b/src/modules/block-library/blocks/stats/Component.tsx @@ -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) { + 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 ( + + +
    + {shown.map((s, i) => ( +
    +
    + {s.heading} + {s.text ? {s.text} : null} +
    +
    {s.value}
    +
    + ))} +
    +
    + ) +} diff --git a/src/modules/block-library/blocks/stats/config.ts b/src/modules/block-library/blocks/stats/config.ts new file mode 100644 index 0000000..2ec6c71 --- /dev/null +++ b/src/modules/block-library/blocks/stats/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/steps/Component.tsx b/src/modules/block-library/blocks/steps/Component.tsx new file mode 100644 index 0000000..3a3c54f --- /dev/null +++ b/src/modules/block-library/blocks/steps/Component.tsx @@ -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) { + 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 ( + + +
      + {items.map((s, i) => ( +
    1. + {i + 1} +
      +

      + {fillText(texts.step, i + 1)}: + {s.heading} +

      + {s.text ?

      {s.text}

      : null} + +
      +
    2. + ))} +
    + +
    + ) +} diff --git a/src/modules/block-library/blocks/steps/config.ts b/src/modules/block-library/blocks/steps/config.ts new file mode 100644 index 0000000..2f01de8 --- /dev/null +++ b/src/modules/block-library/blocks/steps/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/team/Component.tsx b/src/modules/block-library/blocks/team/Component.tsx new file mode 100644 index 0000000..82c29e4 --- /dev/null +++ b/src/modules/block-library/blocks/team/Component.tsx @@ -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) { + 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 ( + + +
      + {items.map((m, i) => ( +
    • + +
      +

      + {m.heading} +

      + {m.text ?

      {m.text}

      : null} + {m.bio ?

      {m.bio}

      : null} +
      +
    • + ))} +
    + +
    + ) +} diff --git a/src/modules/block-library/blocks/team/config.ts b/src/modules/block-library/blocks/team/config.ts new file mode 100644 index 0000000..a36b99f --- /dev/null +++ b/src/modules/block-library/blocks/team/config.ts @@ -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, +}) diff --git a/src/modules/block-library/blocks/testimonials/Component.tsx b/src/modules/block-library/blocks/testimonials/Component.tsx new file mode 100644 index 0000000..64dba27 --- /dev/null +++ b/src/modules/block-library/blocks/testimonials/Component.tsx @@ -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): 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
    /
    /
    ; a rating has a text equivalent for screen readers. */ +export function TestimonialsBlock(props: LibraryBlockProps) { + 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)] : [])).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 ( + + +
      + {list.map((t, i) => ( +
    • + + {t.rating ? ( +

      + {'★'.repeat(Math.round(t.rating))} + {fillText(texts.rating, t.rating)} +

      + ) : null} +
      {t.quote}
      +
      + + + {t.heading} + {t.text ? {t.text} : null} + +
      +
      +
    • + ))} +
    + +
    + ) +} diff --git a/src/modules/block-library/blocks/testimonials/config.ts b/src/modules/block-library/blocks/testimonials/config.ts new file mode 100644 index 0000000..9c35adb --- /dev/null +++ b/src/modules/block-library/blocks/testimonials/config.ts @@ -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({ + 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, +}) diff --git a/src/modules/block-library/blocks/textMedia/Component.tsx b/src/modules/block-library/blocks/textMedia/Component.tsx new file mode 100644 index 0000000..8c897ce --- /dev/null +++ b/src/modules/block-library/blocks/textMedia/Component.tsx @@ -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) { + 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 ( + +
    +
    + + {content ? : null} + +
    + {media ? ( +
    + +
    + ) : null} +
    +
    + ) +} diff --git a/src/modules/block-library/blocks/textMedia/config.ts b/src/modules/block-library/blocks/textMedia/config.ts new file mode 100644 index 0000000..03db8b0 --- /dev/null +++ b/src/modules/block-library/blocks/textMedia/config.ts @@ -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, +}) diff --git a/src/modules/block-library/context.ts b/src/modules/block-library/context.ts new file mode 100644 index 0000000..418dece --- /dev/null +++ b/src/modules/block-library/context.ts @@ -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 + CMSLink: (props: CMSLinkProps) => Promise | ReactNode + Container: ComponentType + Media: ComponentType + Section: ComponentType + SectionHeader: ComponentType +} + +/** 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 + getFormTexts?: (locale: string) => Promise + getLinkOptions?: (locale: string) => Promise + 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 + content: BlockContent + /** Turns a collection document into an entry card. Default: title, excerpt/description, media/image, publishedAt. */ + entryCard?: (doc: Record, collection: string) => EntryCard | null + formClassNames?: BuilderFormClassNames + /** The project's icon components by name (the names of buildFeatureGridBlock({ icons })). */ + icons?: Record> + /** next/image — optimized images with blur-up. Without it: a plain . */ + Image?: ImageComponent + /** Lightbox triggers on gallery images. Default true (needs ). */ + lightbox: boolean + /** next/link — client-side navigation for internal links. Without it: a plain . */ + Link?: LinkComponent + /** Turns a testimonials-collection document into an item. Default: quote, heading/author/name, text/role, media, rating. */ + mapTestimonial?: (doc: Record) => null | TestimonialItem + richText?: { className?: string } + /** The project's sendForm server action (createSubmitAction) — the contact block needs it. */ + sendForm?: SendFormAction + texts?: Partial>> +} + +/** Props of every library block component: its data + locale + what the registry binds. */ +export type LibraryBlockProps = { + classNames?: PartClasses + ctx: BlockContext + isFirst?: boolean + locale: string + ui: BlockUi +} & D diff --git a/src/modules/block-library/data.ts b/src/modules/block-library/data.ts new file mode 100644 index 0000000..51a1f98 --- /dev/null +++ b/src/modules/block-library/data.ts @@ -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 | 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 | undefined diff --git a/src/modules/block-library/define.ts b/src/modules/block-library/define.ts new file mode 100644 index 0000000..754d159 --- /dev/null +++ b/src/modules/block-library/define.ts @@ -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 = { + /** 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(def: LibraryBlockDefinition): BlockBuilder { + 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 }) diff --git a/src/modules/block-library/faq.ts b/src/modules/block-library/faq.ts new file mode 100644 index 0000000..69a9e5a --- /dev/null +++ b/src/modules/block-library/faq.ts @@ -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, { 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() })) +} diff --git a/src/modules/block-library/fields.ts b/src/modules/block-library/fields.ts new file mode 100644 index 0000000..0286007 --- /dev/null +++ b/src/modules/block-library/fields.ts @@ -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 ". */ + 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 } : {}) } +} diff --git a/src/modules/block-library/library.ts b/src/modules/block-library/library.ts new file mode 100644 index 0000000..21abe71 --- /dev/null +++ b/src/modules/block-library/library.ts @@ -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> + +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 + cta?: LibraryBlockSetting + entryList?: LibraryBlockSetting + faq?: LibraryBlockSetting + featureGrid?: LibraryBlockSetting + gallery?: LibraryBlockSetting + hero?: LibraryBlockSetting + logos?: LibraryBlockSetting + pricing?: LibraryBlockSetting + richText?: LibraryBlockSetting + stats?: LibraryBlockSetting + steps?: LibraryBlockSetting + team?: LibraryBlockSetting + testimonials?: LibraryBlockSetting + 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> { + const out: Partial> = {} + 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 +} diff --git a/src/modules/block-library/manifest.ts b/src/modules/block-library/manifest.ts new file mode 100644 index 0000000..e5b973e --- /dev/null +++ b/src/modules/block-library/manifest.ts @@ -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() diff --git a/src/modules/block-library/options.ts b/src/modules/block-library/options.ts new file mode 100644 index 0000000..34dd432 --- /dev/null +++ b/src/modules/block-library/options.ts @@ -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[] { + 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 +} diff --git a/src/modules/block-library/registry.tsx b/src/modules/block-library/registry.tsx new file mode 100644 index 0000000..6e1ae4c --- /dev/null +++ b/src/modules/block-library/registry.tsx @@ -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 + /** Classes per block part, replacing that part's defaults: `{ faq: { item: 'border-b border-border' } }`. */ + classNames?: Partial> + /** Replace a block's component. It gets the same props (data, locale, isFirst, ui, ctx, classNames). */ + components?: Partial>> + /** 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> + /** Swap UI primitives for every library block (e.g. the project's own Media). */ + ui?: Partial +} & Omit & Partial> + +/** + * 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> + const bound = (props: Record) => + 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, backgrounds?: Record): BlockUi { + const buttons = own.buttonClass ?? buttonClass + const sectionBackgrounds = { ...SECTION_BACKGROUNDS, ...backgrounds } + const BoundLink = (props: CMSLinkProps) => + const BoundMedia = (props: MediaProps) => + const BoundSection = (props: SectionProps) =>
    + 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, + } +} diff --git a/src/modules/block-library/shared.ts b/src/modules/block-library/shared.ts new file mode 100644 index 0000000..8fdf8f0 --- /dev/null +++ b/src/modules/block-library/shared.ts @@ -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' }, + ], + } +} diff --git a/src/modules/block-library/templates/build.ts b/src/modules/block-library/templates/build.ts new file mode 100644 index 0000000..66ddbf9 --- /dev/null +++ b/src/modules/block-library/templates/build.ts @@ -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 + +/** One block of a template: its library slug and its seed data. */ +export type TemplateBlock = { blockType: LibraryBlockSlug } & Record + +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> + /** 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> + /** Data merged over a block's template data, by library slug: `{ hero: { header: { heading: { pl, en } } } }`. */ + overrides?: Partial>> + /** 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[]; 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 + 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, intro?: Record, eyebrow?: Record) => ({ + ...(eyebrow ? { eyebrow } : {}), + heading, + ...(intro ? { intro } : {}), +}) + +/** A rich text value with one paragraph per locale. */ +export function richText(text: Record): Record { + 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 { + 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 } +} diff --git a/src/modules/block-library/templates/index.ts b/src/modules/block-library/templates/index.ts new file mode 100644 index 0000000..a01abc9 --- /dev/null +++ b/src/modules/block-library/templates/index.ts @@ -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 { + return Object.fromEntries(Object.entries(roles).flatMap(([role, slug]) => (slug ? [[role, { $page: slug }]] : []))) +} + +export type { TemplateBlock, TemplateOptions, TemplatePage, TemplateValue } from './build.js' diff --git a/src/modules/block-library/templates/pages.ts b/src/modules/block-library/templates/pages.ts new file mode 100644 index 0000000..b229e10 --- /dev/null +++ b/src/modules/block-library/templates/pages.ts @@ -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, page: { $page: string }, appearance = 'primary') => ({ + link: { type: 'internal', appearance, label, page }, +}) + +const pageHero = (heading: Record, intro?: Record) => ({ 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) => 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) +} diff --git a/src/modules/block-library/texts.ts b/src/modules/block-library/texts.ts new file mode 100644 index 0000000..8db6968 --- /dev/null +++ b/src/modules/block-library/texts.ts @@ -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>>): 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)) diff --git a/src/modules/block-library/thumbnails.ts b/src/modules/block-library/thumbnails.ts new file mode 100644 index 0000000..825e603 --- /dev/null +++ b/src/modules/block-library/thumbnails.ts @@ -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 = { + 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]) => ``).join('') + const svg = `${rects}` + return `data:image/svg+xml,${encodeURIComponent(svg)}` +} diff --git a/src/modules/block-library/types.ts b/src/modules/block-library/types.ts new file mode 100644 index 0000000..78a8d28 --- /dev/null +++ b/src/modules/block-library/types.ts @@ -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 + /** 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 `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 = (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 = ((block: Block) => Block) | boolean | O + +/** Shared defaults for every block passed to `libraryBlocks`. */ +export type LibraryBlocksShared = Pick diff --git a/src/modules/block-library/ui/Anchor.tsx b/src/modules/block-library/ui/Anchor.tsx new file mode 100644 index 0000000..8f4cd04 --- /dev/null +++ b/src/modules/block-library/ui/Anchor.tsx @@ -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 . */ +export function Anchor({ children, className, href, internal, Link, targetProps }: { children: ReactNode; className?: string; href: string; internal: boolean; Link?: LinkComponent; targetProps: Record }) { + if (internal && Link) { + return ( + + {children} + + ) + } + return ( + + {children} + + ) +} diff --git a/src/modules/block-library/ui/Button.ts b/src/modules/block-library/ui/Button.ts new file mode 100644 index 0000000..51275f0 --- /dev/null +++ b/src/modules/block-library/ui/Button.ts @@ -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 = { + 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 +} diff --git a/src/modules/block-library/ui/Buttons.tsx b/src/modules/block-library/ui/Buttons.tsx new file mode 100644 index 0000000..680d8ce --- /dev/null +++ b/src/modules/block-library/ui/Buttons.tsx @@ -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 ( +
    + {rows.map((row, i) => ( + + ))} +
    + ) +} + +/** 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 = { + four: 'sm:grid-cols-2 lg:grid-cols-4', + three: 'sm:grid-cols-2 lg:grid-cols-3', + two: 'sm:grid-cols-2', +} diff --git a/src/modules/block-library/ui/CMSLink.tsx b/src/modules/block-library/ui/CMSLink.tsx new file mode 100644 index 0000000..2e60836 --- /dev/null +++ b/src/modules/block-library/ui/CMSLink.tsx @@ -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 | 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 ( + + {content} + + ) +} diff --git a/src/modules/block-library/ui/Card.tsx b/src/modules/block-library/ui/Card.tsx new file mode 100644 index 0000000..9ab564b --- /dev/null +++ b/src/modules/block-library/ui/Card.tsx @@ -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 {children} +} diff --git a/src/modules/block-library/ui/Container.tsx b/src/modules/block-library/ui/Container.tsx new file mode 100644 index 0000000..9bc3468 --- /dev/null +++ b/src/modules/block-library/ui/Container.tsx @@ -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 = { + 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
    {children}
    +} diff --git a/src/modules/block-library/ui/Media.tsx b/src/modules/block-library/ui/Media.tsx new file mode 100644 index 0000000..b69fd75 --- /dev/null +++ b/src/modules/block-library/ui/Media.tsx @@ -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 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