Added module Links

This commit is contained in:
2026-10-13 18:04:37 +02:00
parent db05fe814b
commit 3d467d7350
57 changed files with 1786 additions and 777 deletions
+70 -626
View File
@@ -25,7 +25,7 @@
ląduje w `<body>` i SEO pada.
5. **Minimum kolekcji.** Users są wbudowane, dane firmy/nawigacja to globale,
FAQ/hero to bloki.
6. **Sekcja = kompozycja prymitywów.** `linksField()` + `<CMSLink>`, upload +
6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + `<CMSLink>`, upload +
`<Media>`, `<Section>` + `<SectionHeader>`. Zero pól `ctaLabel`/`pdfUrl`.
7. **Renderery z pluginu:** `RenderBlocks` (nie `switch`), `RenderRichText` (nie
własny parser Lexical), `useForm` (nie ręczna hydraulika formularza).
@@ -74,7 +74,7 @@ gatingiem zgody (plugin ma opcję `defer`).
|---|---|---|
| Tekst | tekst w JSX, `if (locale === 'pl')`, tablice tekstów w kodzie | pole `localized: true` z panelu |
| Obraz / plik | `import x from '@/assets/…'`, `src="/images/…"`, URL pliku w polu `text` | `upload → media` + `<Media>` / link typu `file` |
| Link | `href="/pl/kontakt"`, menu jako tablica, mapa `localizedRoutes` | `linkField()` + `<CMSLink>`, `getLocalizedSlugs`, `getSystemPagePath`, nawigacja jako relationship → pages |
| Link | `href="/pl/kontakt"`, menu jako tablica, mapa `localizedRoutes` | `buildLinkField()` + `<CMSLink>`, `getLocalizedSlugs`, `getSystemPagePath`, nawigacja jako relationship → pages |
| Konfiguracja | `locale as 'pl' \| 'en'`, zaszyty slug kolekcji, lista języków `['pl','en']` | `i18n.config.ts`, `locale as never`, lista z configu |
| Dane firmy | NIP, adres, telefon, nazwa w kodzie | global (`siteSettings` / `company`) |
| Infrastruktura | domena, klucz, bucket w kodzie | `.env` |
@@ -105,7 +105,7 @@ src/
sitemap.ts, robots.ts # z lib/content (+ force-dynamic na sitemap)
api/health/route.ts # createHealthRoute
instrumentation.ts # assertEnv(ipalEnvRules({...}))
fields/ # wspólne pola: link.ts, sectionHeader.ts, sectionSettings.ts
fields/ # sectionHeader.ts, sectionSettings.ts (linki: z pluginu)
components/
ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader
layout/ # Header, Footer, MobileNav (§6.8)
@@ -115,7 +115,6 @@ src/
collections/ # Pages.ts, Media.ts (+ treść tylko gdy wymagana)
globals/ # Header.ts, Footer.ts, Company.ts
lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada
lib/links.ts # resolveLinkHref
lib/navigation.ts # resolveNav → dane dla menu
i18n.config.ts # locale — jedno źródło
payload.config.ts
@@ -222,7 +221,8 @@ Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`,
### 6.1 Trzy warstwy
```
src/fields/ WARSTWA 1 — wspólne pola schematu (link, header, settings)
WARSTWA 1 — wspólne pola: linki z pluginu (buildLinkField, buildLinksField)
+ src/fields/ projektu (sectionHeader, sectionSettings)
src/components/ui/ WARSTWA 2 — prymitywy UI (CMSLink, Button, Media, Section, SectionHeader)
src/blocks/X/ WARSTWA 3 — sekcja = kompozycja warstw 1 i 2
```
@@ -231,364 +231,51 @@ musisz zmieniać 12 bloków, architektura jest zła.
### 6.2 Warstwa 1 — wspólne pola
`src/fields/link.ts` — **jedyny sposób na link/CTA**:
**Link / CTA — z pluginu** ([links.md](../links.md)), nigdy kopia w projekcie:
```ts
import type { ArrayField, Field, GroupField } from 'payload'
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
export type LinkAppearance = 'primary' | 'secondary' | 'link'
type LinkFieldOptions = {
name?: string
/** Which visual styles the editor may pick. false → no appearance select. */
appearances?: LinkAppearance[] | false
/** Label hidden for links that wrap something (a card, an image). */
disableLabel?: boolean
required?: boolean
}
const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/
export function linkField({
name = 'link',
appearances = ['primary', 'secondary', 'link'],
disableLabel = false,
required = false,
}: LinkFieldOptions = {}): GroupField {
const fields: Field[] = [
{
type: 'row',
fields: [
{
name: 'type',
type: 'radio',
defaultValue: 'internal',
options: [
{ label: 'Page', value: 'internal' },
{ label: 'URL', value: 'external' },
{ label: 'File', value: 'file' },
],
admin: { layout: 'horizontal', width: '50%' },
},
{
name: 'newTab',
type: 'checkbox',
label: 'Open in new tab',
admin: { width: '50%', style: { alignSelf: 'flex-end' } },
},
],
},
{
name: 'page',
type: 'relationship',
relationTo: 'pages',
required,
admin: { condition: (_, s) => s?.type === 'internal' },
},
{
name: 'url',
type: 'text',
required,
validate: (v: string | null | undefined) =>
!v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor',
admin: {
condition: (_, s) => s?.type === 'external',
description: 'Full URL (https://…), mailto:, tel: or #section-anchor.',
},
},
{
name: 'file',
type: 'upload',
relationTo: 'media',
required,
admin: {
condition: (_, s) => s?.type === 'file',
description: 'Upload a PDF / document / image. Never paste a file URL.',
},
},
]
if (!disableLabel) {
fields.push({ name: 'label', type: 'text', localized: true, required })
}
if (appearances && appearances.length) {
fields.push({
name: 'appearance',
type: 'select',
defaultValue: appearances[0],
options: appearances.map((a) => ({ label: a, value: a })),
})
}
return {
name,
type: 'group',
interfaceName: 'CmsLink', // → `CmsLink` type in payload-types.ts
admin: { hideGutter: true },
fields,
}
}
/** 0..N buttons. Use this for every "CTA(s)" in a section. */
export function linksField({
name = 'links',
maxRows = 2,
appearances,
}: { name?: string; maxRows?: number; appearances?: LinkAppearance[] } = {}): ArrayField {
return {
name,
type: 'array',
maxRows,
admin: { initCollapsed: true },
fields: [linkField({ appearances })],
}
}
buildLinksField() // pole `links`: 0–2 przyciski sekcji
buildLinkField() // pole `link`: pojedynczy link
buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała karta
```
Typ linku: strona / URL (też mailto, tel, #anchor) / **plik** (upload). Plik do
pobrania = link typu `file`, nigdy pole `pdfUrl`. W `payload-types.ts`: `CmsLink`.
Całe CTA w bloku to jedna linia: `linksField()`. Karta klikalna w całości:
`linkField({ disableLabel: true, appearances: false })`.
**Obraz / wideo:** `{ name: 'media', type: 'upload', relationTo: 'media' }`. Kolekcja
`media` dopuszcza PDF, ma `alt` (required, localized) i `normalizeFilenameHook`.
**Pliki i obrazy:** `{ name: 'media', type: 'upload', relationTo: 'media' }`.
Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf',
'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`.
„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`.
`src/fields/sectionHeader.ts` i `src/fields/sectionSettings.ts`:
```ts
import type { GroupField } from 'payload'
export function sectionHeaderField(name = 'header'): GroupField {
return {
name,
type: 'group',
interfaceName: 'SectionHeaderData',
fields: [
{ name: 'eyebrow', type: 'text', localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', localized: true },
],
}
}
export function sectionSettingsField(): GroupField {
return {
name: 'settings',
type: 'group',
interfaceName: 'SectionSettings',
admin: { position: 'sidebar' },
fields: [
{
name: 'anchor',
type: 'text',
admin: { description: 'Section id for #links and section nav, e.g. "pricing".' },
},
{
name: 'background',
type: 'select',
defaultValue: 'default',
options: ['default', 'muted', 'inverted'].map((v) => ({ label: v, value: v })),
},
],
}
}
```
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
**W projekcie (`src/fields/`)** — dwa małe helpery, kod w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md):
- `sectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized),
- `sectionSettingsField()` → grupa `settings` (sidebar): `anchor`, `background`.
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `sectionId` per blok.
Etykiety pól po angielsku (panel jest EN).
### 6.3 Warstwa 2 — prymitywy UI
`src/lib/links.ts` — jedyne miejsce, które zna typy linków:
Kod 1:1: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Każdy ma jedno zadanie:
```ts
import type { CmsLink } from '@/payload-types'
import { buildLocalizedPath } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
export function resolveLinkHref(
link: CmsLink | null | undefined,
locale: string,
homeSlug?: string,
): string | null {
if (!link) return null
if (link.type === 'external') return link.url || null
if (link.type === 'file') {
const file = link.file
return file && typeof file === 'object' && file.url ? file.url : null
}
// internal — `page` must be populated (block depth ≥ 2), not a bare ID
const page = link.page
if (!page || typeof page !== 'object' || typeof page.slug !== 'string') return null
return (
buildLocalizedPath({
slugs: { [locale]: page.slug },
locale,
config: i18nConfig,
...(homeSlug ? { homeSlug } : {}),
}) ?? null
)
}
```
`src/components/ui/CMSLink.tsx` — **każdy** link/przycisk z panelu:
```tsx
import Link from 'next/link'
import type { ReactNode } from 'react'
import type { CmsLink } from '@/payload-types'
import { resolveLinkHref } from '@/lib/links'
import { getSettings } from '@/lib/content'
import { buttonClass } from './Button'
type Props = {
link: CmsLink | null | undefined
locale: string
className?: string
/** For wrapping links (cards): content instead of link.label. */
children?: ReactNode
}
export async function CMSLink({ link, locale, className, children }: Props) {
const settings = await getSettings(locale) // react cache → one query per request
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
const href = resolveLinkHref(link, locale, homeSlug)
const content = children ?? link?.label
if (!link || !href || !content) return null
const cls = [link.appearance ? buttonClass(link.appearance) : '', className]
.filter(Boolean)
.join(' ')
const newTab = link.newTab || link.type === 'file'
const targetProps = newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {}
if (link.type === 'internal') {
return <Link href={href} className={cls} {...targetProps}>{content}</Link>
}
return <a href={href} className={cls} {...targetProps}>{content}</a>
}
```
`src/components/ui/Button.tsx` — warianty jako mapa, nie ternary:
```ts
import type { LinkAppearance } from '@/fields/link'
const VARIANTS: Record<LinkAppearance, string> = {
primary: 'btn btn-primary',
secondary: 'btn btn-secondary',
link: 'link-arrow',
}
export function buttonClass(appearance: LinkAppearance): string {
return VARIANTS[appearance]
}
```
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu:
```tsx
import Image from 'next/image'
import type { Media as MediaDoc } from '@/payload-types'
type Props = {
resource: MediaDoc | string | number | null | undefined
sizes?: string
priority?: boolean
className?: string
}
export function Media({ resource, sizes = '100vw', priority = false, className }: Props) {
if (!resource || typeof resource !== 'object' || !resource.url) return null
const { url, alt, width, height, mimeType } = resource
if (mimeType?.startsWith('video/')) {
return <video src={url} className={className} autoPlay muted loop playsInline />
}
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
return (
<Image src={url} alt={alt ?? ''} width={width} height={height}
sizes={sizes} priority={priority} className={className} />
)
}
```
`Section.tsx` i `SectionHeader.tsx`:
```tsx
// src/components/ui/Section.tsx
import type { ReactNode } from 'react'
import type { SectionSettings } from '@/payload-types'
const BACKGROUNDS: Record<NonNullable<SectionSettings['background']>, string> = {
default: 'bg-background',
muted: 'bg-muted',
inverted: 'bg-foreground text-background',
}
export function Section({ settings, children }: { settings?: SectionSettings | null; children: ReactNode }) {
return (
<section
id={settings?.anchor || undefined}
className={`py-16 md:py-24 ${BACKGROUNDS[settings?.background ?? 'default']}`}
>
<div className="container">{children}</div>
</section>
)
}
```
```tsx
// src/components/ui/SectionHeader.tsx
import type { SectionHeaderData } from '@/payload-types'
export function SectionHeader({ header, as: H = 'h2' }: { header?: SectionHeaderData | null; as?: 'h1' | 'h2' }) {
if (!header?.heading && !header?.eyebrow && !header?.intro) return null
return (
<header className="mb-10 max-w-2xl">
{header.eyebrow && <p className="eyebrow">{header.eyebrow}</p>}
{header.heading && <H className="heading">{header.heading}</H>}
{header.intro && <p className="lead">{header.intro}</p>}
</header>
)
}
```
**`locale` dla każdego bloku — raz, w trasie strony:**
| Prymityw | Robi | Zamiast |
|---|---|---|
| `CMSLink` (async, serwer) | każdy link z panelu: `resolveLinkHref` z pluginu + styl z `Button` + `newTab`/plik | `<a href>`, `<Link href>` w sekcjach |
| `Button.tsx` | `Record<LinkAppearance, string>` z klasami wariantów | łańcuchy ternary, style przycisków w sekcjach |
| `Media` | każdy obraz/wideo z panelu (`next/image`, alt z dokumentu) | `<img src={x.url}>` |
| `Section` | `id` z anchora, tło z mapy, kontener | ręczne `<section className=…>` |
| `SectionHeader` | eyebrow + nagłówek (`h1`/`h2`) + intro | luźne nagłówki w każdej sekcji |
**`locale` dla bloków — raz, w trasie strony** (nigdy `headers()` w komponentach):
```tsx
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}),
})
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
```
### 6.4 Warstwa 3 — sekcja = kompozycja
```ts
// src/blocks/Hero/config.ts
import type { Block } from 'payload'
import { linksField } from '@/fields/link'
import { sectionHeaderField } from '@/fields/sectionHeader'
import { sectionSettingsField } from '@/fields/sectionSettings'
export const HeroBlock: Block = {
slug: 'hero',
interfaceName: 'HeroBlock',
labels: { singular: 'Hero', plural: 'Heroes' },
fields: [
sectionHeaderField(),
{ name: 'media', type: 'upload', relationTo: 'media' },
linksField(),
sectionSettingsField(),
],
}
```
Wzorcowy kształt sekcji (cały komponent; schemat `config.ts` i przykład z
powtarzalnymi elementami — `FeatureGrid` + `FeatureCard` — w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md)):
```tsx
// src/blocks/Hero/Component.tsx — cały komponent
@@ -617,66 +304,17 @@ export function Hero({ header, media, links, settings, locale }: HeroBlock & { l
}
```
Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
```ts
// src/blocks/FeatureGrid/config.ts (fields)
sectionHeaderField(),
{
name: 'items',
type: 'array',
interfaceName: 'FeatureItem',
fields: [
{ name: 'media', type: 'upload', relationTo: 'media' },
{ name: 'heading', type: 'text', localized: true, required: true },
{ name: 'text', type: 'textarea', localized: true },
linkField({ appearances: ['link'] }),
],
},
linksField({ maxRows: 1 }),
sectionSettingsField(),
```
```tsx
// src/blocks/FeatureGrid/FeatureCard.tsx
export function FeatureCard({ item, locale }: { item: FeatureItem; locale: string }) {
return (
<article className="card">
<Media resource={item.media} sizes="(min-width: 1024px) 33vw, 100vw" />
<h3>{item.heading}</h3>
{item.text && <p>{item.text}</p>}
<CMSLink link={item.link} locale={locale} />
</article>
)
}
// src/blocks/FeatureGrid/Component.tsx
export function FeatureGrid({ header, items, links, settings, locale }: FeatureGridBlock & { locale: string }) {
return (
<Section settings={settings}>
<SectionHeader header={header} />
<div className="grid gap-6 md:grid-cols-3">
{items?.map((item) => <FeatureCard key={item.id} item={item} locale={locale} />)}
</div>
{links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} className="mt-10" />)}
</Section>
)
}
```
**Wydziel podkomponent, gdy którekolwiek jest prawdą:** ten sam JSX 2+ razy;
element `items[]` ma >5 linii markupu; `Component.tsx` >80 linii JSX; jest stan/
interakcja (accordion, slider, tabs → osobny `'use client'`). Podkomponent
jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
Ikony: upload albo `select` z mapą w `src/components/icons` — nigdy SVG wklejone
w sekcję.
element `items[]` ma >5 linii markupu (→ `<Nazwa>Card.tsx`); `Component.tsx` >80
linii JSX; jest stan/interakcja (→ osobny plik `'use client'`, §6.9).
Podkomponent jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
### 6.5 Stałe słownictwo pól
| Rzecz | Nazwa pola | ZAKAZANE |
|---|---|---|
| Przyciski / CTA sekcji | `links` (`linksField()`) | `cta`, `ctaLabel`, `ctaHref`, `ctaTarget`, `cta2…`, `buttons`, `buttonText`, `buttonUrl`, `primaryCta` |
| Pojedynczy link (karta, element) | `link` (`linkField()`) | `href`, `url`, `target`, `linkTo`, `readMoreUrl` |
| Przyciski / CTA sekcji | `links` (`buildLinksField()`) | `cta`, `ctaLabel`, `ctaHref`, `ctaTarget`, `cta2…`, `buttons`, `buttonText`, `buttonUrl`, `primaryCta` |
| Pojedynczy link (karta, element) | `link` (`buildLinkField()`) | `href`, `url`, `target`, `linkTo`, `readMoreUrl` |
| Obraz / wideo | `media` | `image`, `img`, `imageUrl`, `photo`, `bgImage`, `heroImage` |
| Plik do pobrania | `link` typu `file` | osobne `pdf`, `pdfUrl`, `file`, `download`, `attachment` |
| Nagłówek sekcji | `header` (`sectionHeaderField()`) | luźne `title`, `headline`, `sectionTitle`, `subheading`, `subtitle` |
@@ -697,7 +335,7 @@ Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli
{ name: 'secondaryCtaTarget', type: 'relationship', relationTo: 'pages' },
{ name: 'pdfUrl', type: 'text' },
// DOBRZE
linksField({ maxRows: 3 })
buildLinksField({ maxRows: 3 })
```
```tsx
// ŹLE — sekcja sama składa href i stylizuje przycisk
@@ -716,7 +354,7 @@ className={v === 'a' ? 'x' : v === 'b' ? 'y' : 'z'}
### 6.7 Refaktor sekcji-monolitu
1. Spisz, co sekcja wyświetla (nagłówek, obrazy, przyciski, powtórzenia).
2. Schemat wg §6.5; CTA → `linksField()`.
2. Schemat wg §6.5; CTA → `buildLinksField()`.
3. **Zmiana nazw pól gubi treść w bazie.** Projekt z treścią → najpierw migracja
(stare pole → nowe), potem usunięcie starych. Pusty projekt → sama zmiana.
4. Komponent: `<Section>`, `<SectionHeader>`, `<Media>`, `<CMSLink>`,
@@ -725,173 +363,19 @@ className={v === 'a' ? 'x' : v === 'b' ? 'y' : 'z'}
### 6.8 Header i Footer (globale nawigacji)
Nawigacja, stopka i dane firmy to **globale projektu** (model zależy od klienta
i kraju), budowane z tych samych wspólnych pól co sekcje. Logo i nazwa są w
Site Settings — nie duplikuj ich w Header.
Kod (globale, `resolveNav`, `Header`, `Footer`, `MobileNav`): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md).
Skill: **ipal-nav**.
```ts
// src/globals/Header.ts
import type { GlobalConfig } from 'payload'
import { linkField, linksField } from '@/fields/link'
export const Header: GlobalConfig = {
slug: 'header',
access: { read: () => true },
fields: [
{
name: 'navItems',
type: 'array',
maxRows: 8,
fields: [
linkField({ appearances: false }),
{
name: 'subItems', // jeden poziom podmenu — głębiej nie budujemy
type: 'array',
maxRows: 10,
fields: [linkField({ appearances: false })],
},
],
},
linksField({ maxRows: 1 }), // przycisk CTA w nagłówku
{
name: 'menuLabel',
type: 'text',
localized: true,
admin: { description: 'Accessible label of the mobile menu button, e.g. "Menu".' },
},
],
}
```
```ts
// src/globals/Footer.ts
import type { GlobalConfig } from 'payload'
import { linkField } from '@/fields/link'
export const Footer: GlobalConfig = {
slug: 'footer',
access: { read: () => true },
fields: [
{
name: 'columns',
type: 'array',
maxRows: 4,
fields: [
{ name: 'heading', type: 'text', localized: true },
{ name: 'items', type: 'array', fields: [linkField({ appearances: false })] },
],
},
{ name: 'note', type: 'textarea', localized: true }, // np. „Wszelkie prawa zastrzeżone”
],
}
```
- **Linki prawne w stopce** (polityka, cookies, regulamin) renderuj z ról System
Pages (`getSystemPagePath` + tytuł strony) — nie dodawaj ich ręcznie do `columns`.
- **Dane firmy** (nazwa, adres, NIP/ABN, telefon) — global `company` projektu;
stopka i JSON-LD czytają z niego. Rok w copyright licz w kodzie
(`new Date().getFullYear()`), nazwę bierz z globala.
- **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange`
z `revalidatePath('/', 'layout')` (hooks.md).
Linki rozwiązuj **na serwerze** do zwykłych danych, a do klienta (menu mobilne)
przekazuj tylko `{ href, label, newTab }` — komponent kliencki nie może wołać
`CMSLink` (to async server component).
```ts
// src/lib/navigation.ts
import type { CmsLink } from '@/payload-types'
import { resolveLinkHref } from '@/lib/links'
import { getSettings } from '@/lib/content'
export type NavItem = { href: string; label: string; newTab: boolean; subItems: NavItem[] }
type NavSource = { link?: CmsLink | null; subItems?: { link?: CmsLink | null }[] | null }
function toNavItem(link: CmsLink | null | undefined, locale: string, homeSlug?: string): NavItem | null {
const href = resolveLinkHref(link, locale, homeSlug)
if (!link || !href || !link.label) return null
return { href, label: link.label, newTab: Boolean(link.newTab), subItems: [] }
}
export async function resolveNav(items: NavSource[] | null | undefined, locale: string): Promise<NavItem[]> {
const settings = await getSettings(locale)
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
return (items ?? []).flatMap((item) => {
const node = toNavItem(item.link, locale, homeSlug)
if (!node) return []
node.subItems = (item.subItems ?? []).flatMap((sub) => {
const child = toNavItem(sub.link, locale, homeSlug)
return child ? [child] : []
})
return [node]
})
}
```
```tsx
// src/components/layout/Header.tsx — serwer
import Link from 'next/link'
import type { Header as HeaderData } from '@/payload-types'
import { resolveNav } from '@/lib/navigation'
import { CMSLink } from '@/components/ui/CMSLink'
import { MobileNav } from './MobileNav'
export async function Header({ header, locale }: { header: HeaderData; locale: string }) {
const items = await resolveNav(header.navItems, locale)
return (
<header className="border-b">
<nav className="container flex items-center justify-between py-4">
{/* logo: Site Settings → <Media> */}
<ul className="hidden gap-6 md:flex">
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} {...(item.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>
{item.label}
</Link>
</li>
))}
</ul>
{header.links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
<MobileNav items={items} menuLabel={header.menuLabel ?? ''} />
</nav>
</header>
)
}
```
```tsx
// src/components/layout/MobileNav.tsx — klient, tylko stan otwarcia
'use client'
import { useState } from 'react'
import Link from 'next/link'
import type { NavItem } from '@/lib/navigation' // import TYPU — nie ciągnie kodu serwera
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
const [open, setOpen] = useState(false)
return (
<div className="md:hidden">
<button type="button" aria-expanded={open} aria-label={menuLabel} onClick={() => setOpen(!open)}>
<span aria-hidden>☰</span>
</button>
{open && (
<ul>
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} onClick={() => setOpen(false)}>{item.label}</Link>
</li>
))}
</ul>
)}
</div>
)
}
```
Header/Footer pobierasz w `[locale]/layout.tsx` (przez cached getter w
`lib/`) i podajesz jako props — layout to jedyne miejsce, które je składa.
- Nawigacja, stopka, dane firmy = **globale projektu** (`header`, `footer`, `company`),
zbudowane z `buildLinkField` — model danych firmy zależy od kraju (NIP/ABN/EIN).
- Menu: jeden poziom podmenu, nie głębiej. CTA w nagłówku = `links`.
- Logo i nazwa z Site Settings — nie duplikuj pól w Header.
- **Linki prawne w stopce** z ról System Pages (`getSystemPagePath`), nie ręcznie.
- Linki rozwiązuj **na serwerze** (`resolveNav` → `{ href, label, newTab }`); do
komponentu klienckiego idą tylko proste dane — `CMSLink` jest serwerowy.
- Etykiety a11y (przycisk menu) — pola w panelu.
- Global zmieniany na każdej stronie → `afterChange` z `revalidatePath('/', 'layout')`.
- Globale pobiera tylko `[locale]/layout.tsx` i podaje jako props.
### 6.9 Komponenty klienckie (`'use client'`)
@@ -917,64 +401,21 @@ Header/Footer pobierasz w `[locale]/layout.tsx` (przez cached getter w
### 6.10 Ikony
Dwa źródła, nic pomiędzy:
- **Dowolna grafika od klienta** → upload do `media` + `<Media>` (także logo, ikony SVG marki).
- **Stały zestaw ikon UI** → pole `select` + mapa `lucide-react`:
```ts
// src/components/icons/names.ts — same nazwy, importowane przez config bloku
export const ICON_NAMES = ['phone', 'mail', 'mapPin', 'clock', 'check'] as const
export type IconName = (typeof ICON_NAMES)[number]
export const iconField = {
name: 'icon',
type: 'select',
options: ICON_NAMES.map((value) => ({ label: value, value })),
} as const
```
```tsx
// src/components/icons/Icon.tsx — mapa, importowana tylko przez komponenty
import { Check, Clock, Mail, MapPin, Phone, type LucideIcon } from 'lucide-react'
import type { IconName } from './names'
const ICONS: Record<IconName, LucideIcon> = { phone: Phone, mail: Mail, mapPin: MapPin, clock: Clock, check: Check }
export function Icon({ name, className }: { name?: IconName | null; className?: string }) {
if (!name) return null
const Component = ICONS[name]
return <Component className={className} aria-hidden />
}
```
Nazwy są osobno, żeby config bloku (`payload.config`) nie importował komponentów
React. **Nigdy** SVG wklejone w JSX sekcji.
Dwa źródła, nic pomiędzy: **grafika od klienta** (także logo, ikony marki) →
upload + `<Media>`; **stały zestaw ikon UI** → pole `select` z nazwami +
mapa `lucide-react` w `src/components/icons/` (nazwy w osobnym pliku, żeby config
bloku nie importował Reacta). Kod: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). **Nigdy** SVG wklejone w JSX sekcji.
### 6.11 Style
- **Tailwind w komponentach**, kolory i fonty jako **tokeny** w `styles.css`
(`@theme`) — źródłem jest `DESIGN.md` (Impeccable). W komponentach tylko nazwy
tokenów (`bg-primary`, `text-foreground`), **nigdy** `bg-[#ff6600]` ani hex.
- Tokeny pluginu mapuj na tokeny projektu — jeden kolor marki w jednym miejscu.
- Fonty przez `next/font` w layoucie, podpięte zmienną CSS do `@theme`.
- Tailwind w komponentach; kolory i fonty jako **tokeny** w `styles.css` (`@theme`)
ze źródła `DESIGN.md`. W komponentach tylko tokeny (`bg-primary`), **nigdy**
`bg-[#ff6600]` ani hex.
- Tokeny pluginu mapuj na projekt: `--ipal-primary: var(--color-primary)`.
- Fonty przez `next/font`, podpięte zmienną CSS do `@theme`.
- Bez CSS Modules i `style={{…}}` — wyjątek: wartość dynamiczna z danych.
- Warianty wizualne → `Record<Variant, string>` (§6.3), nie łańcuchy ternary.
```css
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
@theme {
--color-primary: oklch(0.62 0.19 45);
--color-background: oklch(0.99 0 0);
--color-foreground: oklch(0.2 0 0);
--color-muted: oklch(0.96 0 0);
--font-sans: var(--font-body); /* next/font: variable '--font-body' */
}
:root {
--ipal-primary: var(--color-primary); /* baner cookies, Turnstile = kolor marki */
--ipal-radius: 0.75rem;
}
```
- Warianty → `Record<Variant, string>`, nie łańcuchy ternary.
Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md).
### 6.12 Eksporty i importy
@@ -997,6 +438,7 @@ React. **Nigdy** SVG wklejone w JSX sekcji.
| Potrzeba | Użyj | Doc |
|---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField`, `resolveLinkHref` | links.md |
| Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md |
| Rich text | `RenderRichText` (`/rsc`), styl przez `converters` | richtext.md |
| Wartość zlokalizowana | `resolveLocalized(value, locale)` (nie `getSafeString`) | forms.md |
@@ -1011,10 +453,10 @@ React. **Nigdy** SVG wklejone w JSX sekcji.
| Stary slug → 308 | `trackSlugHistoryHook` + `resolveRedirect` | hooks.md |
| Obrazy między językami | `buildCrossLocaleFieldSync` (języki z configu) | hooks.md |
| Ochrona stron systemowych | `buildPreventDeleteSystemPage`, `buildValidateUniqueRole` | hooks.md |
| Metadata, sitemap, JSON-LD, llms.txt | `createPageMetadata`, `sitemap`, `build*JsonLd`, `createLlmsTxtRoute` | seo.md |
| Metadata, sitemap, JSON-LD, llms.txt | `generatePageMetadata` (z `createContentHelpers`), `sitemap`, `build*JsonLd`, `createLlmsTxtRoute` | seo.md |
| Consent, analytics, pixele | `ConsentProvider`, `CookieBanner`, `Analytics` (wewnątrz providera) | consent.md, analytics.md |
| Nagłówki, CSP, 2FA | `buildSecurityHeaders`, `buildCsp`, `twoFactor` (wstrzyknięty `payloadTotp`) | security.md |
| Media, R2 | `buildR2Storage`, `normalizeFilenameHook`, `MediaPreconnect` | storage.md |
| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `MediaPreconnect` | storage.md |
| Email | `email: mailAdapter()` | email.md |
| Walidacja env | `assertEnv(ipalEnvRules({...}))` | env.md |
@@ -1081,7 +523,7 @@ payloadTotp } })`, nigdy `twoFactor: false` bez decyzji klienta). CSP: najpierw
| favicon renderowany ręcznie | Google go nie pokazuje | `buildIconsMetadata` |
| skopiowany `Analytics` w projekcie | pixele bez zgody (RODO) | opcje pluginu (`defer`) |
| `import('@payload-config')` przez zmienną | `Cannot find module` w buildzie | wstrzyknięcie / props |
| `ctaLabel`, `buttonUrl`, `pdfUrl` w blokach | zoo pól, brak spójności | `linksField()` |
| `ctaLabel`, `buttonUrl`, `pdfUrl` w blokach | zoo pól, brak spójności | `buildLinksField()` |
| brak `@source` na plugin w CSS | komponenty pluginu bez stylów | `@source` |
| kolekcja `users`/`settings`/`faq` | duplikat Payloada / zły byt | §5.3 |
@@ -1156,6 +598,7 @@ Cokolwiek wymaga dewelopera → przenieś do panelu.
| Formularze, useForm, honeypot | [forms.md](../forms.md) |
| Hooki | [hooks.md](../hooks.md) |
| i18n, proxy, przełącznik języka | [i18n.md](../i18n.md) |
| Linki / CTA (pola + href) | [links.md](../links.md) |
| Serwer MCP strony | [mcp.md](../mcp.md) |
| Komunikaty formularzy | [notifications.md](../notifications.md) |
| Strony systemowe, 404, generateStaticParams | [pages.md](../pages.md) |
@@ -1215,12 +658,13 @@ zadanie pasuje — ręcznie: `/<nazwa>`.
`package.json` projektu:
```json
"scripts": {
"ipal:skills": "mkdir -p .agents/skills && cp -R node_modules/@intecion/ipal-kit/docs/agent/skills/. .agents/skills/"
"ipal:skills": "ipal-skills"
}
```
```bash
pnpm ipal:skills
```
Commituj `.agents/skills/ipal-*` do repo projektu (agent ma je bez instalacji).
Własne skille projektu nazywaj bez prefiksu `ipal-` — kopiowanie nadpisuje tylko
skille pluginu.
`ipal-skills` (komenda z pakietu) kopiuje tylko foldery `ipal-*`: dodaje nowe,
nadpisuje zmienione, usuwa wycofane. Własne skille projektu nazywaj **bez**
prefiksu `ipal-` — zostaną nietknięte. Opcje: `--dry-run`, `--dest .claude/skills`
(Claude Code). Commituj `.agents/skills/ipal-*` do repo projektu.
@@ -130,6 +130,8 @@ report ERROR "own block renderer switch" "§7 use RenderBlocks + registry" \
"$(g 'switch *\(.*blockType' src --include=*.tsx --include=*.ts)"
report WARNING "files that usually duplicate the plugin" "§3 plugin has resolveRoute / getConfiguredLocales" \
"$(ls src/lib/pages.ts src/lib/locales.ts 2>/dev/null)"
report ERROR "project copy of link fields" "links.md — use buildLinkField / buildLinksField / resolveLinkHref from the plugin" \
"$(ls src/fields/link.ts src/lib/links.ts 2>/dev/null; g "from '@/fields/link'|from '@/lib/links'" src --include=*.ts --include=*.tsx)"
report ERROR "manual Lexical rendering" "§7 use RenderRichText" \
"$(g 'node\.type *===|dangerouslySetInnerHTML' src --include=*.tsx)"
+8 -5
View File
@@ -1,6 +1,6 @@
---
name: ipal-block
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — shared fields (sectionHeaderField, linksField, linkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
---
# ipal-block
@@ -9,9 +9,10 @@ Jedna sekcja na jedno użycie skilla. Szczegóły i gotowy kod:
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.
## 0. Warunki wstępne
Sprawdź, czy istnieją: `src/fields/link.ts`, `sectionHeader.ts`,
`sectionSettings.ts`, `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`,
`src/lib/links.ts`. Brakuje → najpierw utwórz je 1:1 z AGENT.md §6.2–6.3
Sprawdź, czy istnieją: `src/fields/sectionHeader.ts`,
`sectionSettings.ts`, `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
Linki (`buildLinkField`, `buildLinksField`, `resolveLinkHref`) są w pluginie — nie twórz ich w projekcie.
Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
(i powiedz o tym użytkownikowi). Nie pisz własnych wersji.
## 1. Plan (pokaż i czekaj na OK)
@@ -23,8 +24,10 @@ Sprawdź, czy istnieją: `src/fields/link.ts`, `sectionHeader.ts`,
- czy sekcja to wariant istniejącego bloku (wtedy pole `variant: select`, nie nowy blok).
## 2. Kod
Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`.
1. `src/blocks/<Nazwa>/config.ts` — `interfaceName: '<Nazwa>Block'`, pola z planu,
zawsze `sectionSettingsField()`. CTA = `linksField()`, nigdy pola `cta*`/`button*`.
zawsze `sectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
Plik do pobrania = link typu `file`. Etykiety i opisy pól po angielsku.
2. `src/blocks/<Nazwa>/Component.tsx` — nazwany eksport, typ z `@/payload-types`
(`<Nazwa>Block & { locale: string }`), struktura:
@@ -0,0 +1,378 @@
# Kod sekcji — gotowe pliki dla projektu
> Zasoby skilla **ipal-block**. Reguły (dlaczego tak, czego nie robić) są w
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — ten plik to tylko kod
> do utworzenia w projekcie **1:1**. Linki (`buildLinkField`, `buildLinksField`,
> `resolveLinkHref`) są w pluginie — nie twórz ich kopii.
## Warstwa 1 — wspólne pola
**Link / CTA — z pluginu, nie kopiuj kodu** (`docs/links.md`):
```ts
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
buildLinksField() // 0–2 przyciski sekcji → pole `links`
buildLinksField({ maxRows: 3, appearances: ['primary', 'secondary'] })
buildLinkField() // pojedynczy link → pole `link`
buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała karta
```
Jeden kształt linku: typ (`internal` strona / `external` URL, mailto, tel, #anchor /
`file` upload), `label` (localized), `newTab`, `appearance`. W `payload-types.ts`
powstaje typ `CmsLink`. Opcje: `relationTo` (domyślnie `'pages'`), `uploadTo`
(domyślnie `'media'`), `required`.
**Pliki i obrazy:** `{ name: 'media', type: 'upload', relationTo: 'media' }`.
Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf',
'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`.
„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`.
`src/fields/sectionHeader.ts` i `src/fields/sectionSettings.ts`:
```ts
import type { GroupField } from 'payload'
export function sectionHeaderField(name = 'header'): GroupField {
return {
name,
type: 'group',
interfaceName: 'SectionHeaderData',
fields: [
{ name: 'eyebrow', type: 'text', localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', localized: true },
],
}
}
export function sectionSettingsField(): GroupField {
return {
name: 'settings',
type: 'group',
interfaceName: 'SectionSettings',
admin: { position: 'sidebar' },
fields: [
{
name: 'anchor',
type: 'text',
admin: { description: 'Section id for #links and section nav, e.g. "pricing".' },
},
{
name: 'background',
type: 'select',
defaultValue: 'default',
options: ['default', 'muted', 'inverted'].map((v) => ({ label: v, value: v })),
},
],
}
}
```
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
## Warstwa 2 — prymitywy UI
`src/components/ui/CMSLink.tsx` — **każdy** link/przycisk z panelu:
```tsx
import Link from 'next/link'
import type { ReactNode } from 'react'
import { resolveLinkHref } from '@intecion/ipal-kit'
import type { CmsLink } from '@/payload-types'
import { i18nConfig } from '@/i18n.config'
import { getSettings } from '@/lib/content'
import { buttonClass } from './Button'
type Props = {
link: CmsLink | null | undefined
locale: string
className?: string
/** For wrapping links (cards): content instead of link.label. */
children?: ReactNode
}
export async function CMSLink({ link, locale, className, children }: Props) {
const settings = await getSettings(locale) // react cache → one query per request
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
const content = children ?? link?.label
if (!link || !href || !content) return null
const cls = [link.appearance ? buttonClass(link.appearance) : '', className]
.filter(Boolean)
.join(' ')
const newTab = link.newTab || link.type === 'file'
const targetProps = newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {}
if (link.type === 'internal') {
return <Link href={href} className={cls} {...targetProps}>{content}</Link>
}
return <a href={href} className={cls} {...targetProps}>{content}</a>
}
```
`src/components/ui/Button.tsx` — warianty jako mapa, nie ternary:
```ts
import type { LinkAppearance } from '@intecion/ipal-kit'
const VARIANTS: Record<LinkAppearance, string> = {
primary: 'btn btn-primary',
secondary: 'btn btn-secondary',
link: 'link-arrow',
}
export function buttonClass(appearance: LinkAppearance): string {
return VARIANTS[appearance]
}
```
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu:
```tsx
import Image from 'next/image'
import type { Media as MediaDoc } from '@/payload-types'
type Props = {
resource: MediaDoc | string | number | null | undefined
sizes?: string
priority?: boolean
className?: string
}
export function Media({ resource, sizes = '100vw', priority = false, className }: Props) {
if (!resource || typeof resource !== 'object' || !resource.url) return null
const { url, alt, width, height, mimeType } = resource
if (mimeType?.startsWith('video/')) {
return <video src={url} className={className} autoPlay muted loop playsInline />
}
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
return (
<Image src={url} alt={alt ?? ''} width={width} height={height}
sizes={sizes} priority={priority} className={className} />
)
}
```
`Section.tsx` i `SectionHeader.tsx`:
```tsx
// src/components/ui/Section.tsx
import type { ReactNode } from 'react'
import type { SectionSettings } from '@/payload-types'
const BACKGROUNDS: Record<NonNullable<SectionSettings['background']>, string> = {
default: 'bg-background',
muted: 'bg-muted',
inverted: 'bg-foreground text-background',
}
export function Section({ settings, children }: { settings?: SectionSettings | null; children: ReactNode }) {
return (
<section
id={settings?.anchor || undefined}
className={`py-16 md:py-24 ${BACKGROUNDS[settings?.background ?? 'default']}`}
>
<div className="container">{children}</div>
</section>
)
}
```
```tsx
// src/components/ui/SectionHeader.tsx
import type { SectionHeaderData } from '@/payload-types'
export function SectionHeader({ header, as: H = 'h2' }: { header?: SectionHeaderData | null; as?: 'h1' | 'h2' }) {
if (!header?.heading && !header?.eyebrow && !header?.intro) return null
return (
<header className="mb-10 max-w-2xl">
{header.eyebrow && <p className="eyebrow">{header.eyebrow}</p>}
{header.heading && <H className="heading">{header.heading}</H>}
{header.intro && <p className="lead">{header.intro}</p>}
</header>
)
}
```
**`locale` dla każdego bloku — raz, w trasie strony:**
```tsx
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}),
})
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
```
## Warstwa 3 — sekcja = kompozycja
```ts
// src/blocks/Hero/config.ts
import type { Block } from 'payload'
import { buildLinksField } from '@intecion/ipal-kit'
import { sectionHeaderField } from '@/fields/sectionHeader'
import { sectionSettingsField } from '@/fields/sectionSettings'
export const HeroBlock: Block = {
slug: 'hero',
interfaceName: 'HeroBlock',
labels: { singular: 'Hero', plural: 'Heroes' },
fields: [
sectionHeaderField(),
{ name: 'media', type: 'upload', relationTo: 'media' },
buildLinksField(),
sectionSettingsField(),
],
}
```
```tsx
// src/blocks/Hero/Component.tsx — cały komponent
import type { HeroBlock } from '@/payload-types'
import { Section } from '@/components/ui/Section'
import { SectionHeader } from '@/components/ui/SectionHeader'
import { Media } from '@/components/ui/Media'
import { CMSLink } from '@/components/ui/CMSLink'
export function Hero({ header, media, links, settings, locale }: HeroBlock & { locale: string }) {
return (
<Section settings={settings}>
<div className="grid items-center gap-10 md:grid-cols-2">
<div>
<SectionHeader header={header} as="h1" />
{links?.length ? (
<div className="flex flex-wrap gap-3">
{links.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
</div>
) : null}
</div>
<Media resource={media} priority sizes="(min-width: 768px) 50vw, 100vw" />
</div>
</Section>
)
}
```
Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
```ts
// src/blocks/FeatureGrid/config.ts (fields)
sectionHeaderField(),
{
name: 'items',
type: 'array',
interfaceName: 'FeatureItem',
fields: [
{ name: 'media', type: 'upload', relationTo: 'media' },
{ name: 'heading', type: 'text', localized: true, required: true },
{ name: 'text', type: 'textarea', localized: true },
buildLinkField({ appearances: ['link'] }),
],
},
buildLinksField({ maxRows: 1 }),
sectionSettingsField(),
```
```tsx
// src/blocks/FeatureGrid/FeatureCard.tsx
export function FeatureCard({ item, locale }: { item: FeatureItem; locale: string }) {
return (
<article className="card">
<Media resource={item.media} sizes="(min-width: 1024px) 33vw, 100vw" />
<h3>{item.heading}</h3>
{item.text && <p>{item.text}</p>}
<CMSLink link={item.link} locale={locale} />
</article>
)
}
// src/blocks/FeatureGrid/Component.tsx
export function FeatureGrid({ header, items, links, settings, locale }: FeatureGridBlock & { locale: string }) {
return (
<Section settings={settings}>
<SectionHeader header={header} />
<div className="grid gap-6 md:grid-cols-3">
{items?.map((item) => <FeatureCard key={item.id} item={item} locale={locale} />)}
</div>
{links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} className="mt-10" />)}
</Section>
)
}
```
**Wydziel podkomponent, gdy którekolwiek jest prawdą:** ten sam JSX 2+ razy;
element `items[]` ma >5 linii markupu; `Component.tsx` >80 linii JSX; jest stan/
interakcja (accordion, slider, tabs → osobny `'use client'`). Podkomponent
jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
Ikony: upload albo `select` z mapą w `src/components/icons` — nigdy SVG wklejone
w sekcję.
## Ikony
Dwa źródła, nic pomiędzy:
- **Dowolna grafika od klienta** → upload do `media` + `<Media>` (także logo, ikony SVG marki).
- **Stały zestaw ikon UI** → pole `select` + mapa `lucide-react`:
```ts
// src/components/icons/names.ts — same nazwy, importowane przez config bloku
export const ICON_NAMES = ['phone', 'mail', 'mapPin', 'clock', 'check'] as const
export type IconName = (typeof ICON_NAMES)[number]
export const iconField = {
name: 'icon',
type: 'select',
options: ICON_NAMES.map((value) => ({ label: value, value })),
} as const
```
```tsx
// src/components/icons/Icon.tsx — mapa, importowana tylko przez komponenty
import { Check, Clock, Mail, MapPin, Phone, type LucideIcon } from 'lucide-react'
import type { IconName } from './names'
const ICONS: Record<IconName, LucideIcon> = { phone: Phone, mail: Mail, mapPin: MapPin, clock: Clock, check: Check }
export function Icon({ name, className }: { name?: IconName | null; className?: string }) {
if (!name) return null
const Component = ICONS[name]
return <Component className={className} aria-hidden />
}
```
Nazwy są osobno, żeby config bloku (`payload.config`) nie importował komponentów
React. **Nigdy** SVG wklejone w JSX sekcji.
## Style
- **Tailwind w komponentach**, kolory i fonty jako **tokeny** w `styles.css`
(`@theme`) — źródłem jest `DESIGN.md` (Impeccable). W komponentach tylko nazwy
tokenów (`bg-primary`, `text-foreground`), **nigdy** `bg-[#ff6600]` ani hex.
- Tokeny pluginu mapuj na tokeny projektu — jeden kolor marki w jednym miejscu.
- Fonty przez `next/font` w layoucie, podpięte zmienną CSS do `@theme`.
- Bez CSS Modules i `style={{…}}` — wyjątek: wartość dynamiczna z danych.
- Warianty wizualne → `Record<Variant, string>` (§6.3), nie łańcuchy ternary.
```css
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
@theme {
--color-primary: oklch(0.62 0.19 45);
--color-background: oklch(0.99 0 0);
--color-foreground: oklch(0.2 0 0);
--color-muted: oklch(0.96 0 0);
--font-sans: var(--font-body); /* next/font: variable '--font-body' */
}
:root {
--ipal-primary: var(--color-primary); /* baner cookies, Turnstile = kolor marki */
--ipal-radius: 0.75rem;
}
```
+1 -1
View File
@@ -30,7 +30,7 @@ slug (camelCase, l.mn.), pola, relacje, czy ma URL-e (archiwum), JSON-LD.
1. `src/collections/<Nazwa>.ts`: `title` (localized), `buildSlugField({ from: 'title' })`,
tab SEO (plugin-seo), `buildNoindexField()`, `trackSlugHistoryHook`,
`buildRevalidateHook`, `setPublishedAtHook` (wpisy z datą), upload przez
`media`, linki przez `linkField()`. Nazwy pól wg AGENT.md §6.5.
`media`, linki przez `buildLinkField()`. Nazwy pól wg AGENT.md §6.5.
2. Z URL-ami: dopisz do `content.config.ts` → `{ slug, perPage }`.
**Prefiks URL nie w kodzie** — redaktor przypisuje stronę-archiwum w
Site Settings (`<slug>Archive`). Plugin robi routing, sitemap,
+3 -3
View File
@@ -1,12 +1,12 @@
---
name: ipal-nav
description: Builds the site header, footer, mobile menu and company data in an ipal-kit project — Header/Footer/Company globals with linkField, server-side link resolution (resolveNav), a small client MobileNav, legal links from System Pages, revalidation on change. Use when creating or changing navigation, menu, header, footer, contact details, social links or the company global.
description: Builds the site header, footer, mobile menu and company data in an ipal-kit project — Header/Footer/Company globals with buildLinkField from the plugin, server-side link resolution (resolveNav), a small client MobileNav, legal links from System Pages, revalidation on change. Use when creating or changing navigation, menu, header, footer, contact details, social links or the company global.
---
# ipal-nav
Gotowy kod: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.8.
Wymaga prymitywów z §6.2–6.3 (jak skill ipal-block, krok 0).
Gotowy kod: `resources/kod-nawigacji.md` (ten skill). Reguły: AGENT.md §6.8.
Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-block, krok 0).
## Plan (pokaż i czekaj na OK)
- pozycje menu (jeden poziom podmenu, nie głębiej), CTA w nagłówku (`links`),
@@ -0,0 +1,176 @@
# Kod nawigacji — Header, Footer, menu mobilne
> Zasoby skilla **ipal-nav**. Reguły: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.8.
> Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (CMSLink, Media).
## Header i Footer (globale nawigacji)
Nawigacja, stopka i dane firmy to **globale projektu** (model zależy od klienta
i kraju), budowane z tych samych wspólnych pól co sekcje. Logo i nazwa są w
Site Settings — nie duplikuj ich w Header.
```ts
// src/globals/Header.ts
import type { GlobalConfig } from 'payload'
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
export const Header: GlobalConfig = {
slug: 'header',
access: { read: () => true },
fields: [
{
name: 'navItems',
type: 'array',
maxRows: 8,
fields: [
buildLinkField({ appearances: false }),
{
name: 'subItems', // jeden poziom podmenu — głębiej nie budujemy
type: 'array',
maxRows: 10,
fields: [buildLinkField({ appearances: false })],
},
],
},
buildLinksField({ maxRows: 1 }), // przycisk CTA w nagłówku
{
name: 'menuLabel',
type: 'text',
localized: true,
admin: { description: 'Accessible label of the mobile menu button, e.g. "Menu".' },
},
],
}
```
```ts
// src/globals/Footer.ts
import type { GlobalConfig } from 'payload'
import { buildLinkField } from '@intecion/ipal-kit'
export const Footer: GlobalConfig = {
slug: 'footer',
access: { read: () => true },
fields: [
{
name: 'columns',
type: 'array',
maxRows: 4,
fields: [
{ name: 'heading', type: 'text', localized: true },
{ name: 'items', type: 'array', fields: [buildLinkField({ appearances: false })] },
],
},
{ name: 'note', type: 'textarea', localized: true }, // np. „Wszelkie prawa zastrzeżone”
],
}
```
- **Linki prawne w stopce** (polityka, cookies, regulamin) renderuj z ról System
Pages (`getSystemPagePath` + tytuł strony) — nie dodawaj ich ręcznie do `columns`.
- **Dane firmy** (nazwa, adres, NIP/ABN, telefon) — global `company` projektu;
stopka i JSON-LD czytają z niego. Rok w copyright licz w kodzie
(`new Date().getFullYear()`), nazwę bierz z globala.
- **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange`
z `revalidatePath('/', 'layout')` (hooks.md).
Linki rozwiązuj **na serwerze** do zwykłych danych, a do klienta (menu mobilne)
przekazuj tylko `{ href, label, newTab }` — komponent kliencki nie może wołać
`CMSLink` (to async server component).
```ts
// src/lib/navigation.ts
import { resolveLinkHref } from '@intecion/ipal-kit'
import type { CmsLink } from '@/payload-types'
import { i18nConfig } from '@/i18n.config'
import { getSettings } from '@/lib/content'
export type NavItem = { href: string; label: string; newTab: boolean; subItems: NavItem[] }
type NavSource = { link?: CmsLink | null; subItems?: { link?: CmsLink | null }[] | null }
function toNavItem(link: CmsLink | null | undefined, locale: string, homeSlug?: string): NavItem | null {
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
if (!link || !href || !link.label) return null
return { href, label: link.label, newTab: Boolean(link.newTab), subItems: [] }
}
export async function resolveNav(items: NavSource[] | null | undefined, locale: string): Promise<NavItem[]> {
const settings = await getSettings(locale)
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
return (items ?? []).flatMap((item) => {
const node = toNavItem(item.link, locale, homeSlug)
if (!node) return []
node.subItems = (item.subItems ?? []).flatMap((sub) => {
const child = toNavItem(sub.link, locale, homeSlug)
return child ? [child] : []
})
return [node]
})
}
```
```tsx
// src/components/layout/Header.tsx — serwer
import Link from 'next/link'
import type { Header as HeaderData } from '@/payload-types'
import { resolveNav } from '@/lib/navigation'
import { CMSLink } from '@/components/ui/CMSLink'
import { MobileNav } from './MobileNav'
export async function Header({ header, locale }: { header: HeaderData; locale: string }) {
const items = await resolveNav(header.navItems, locale)
return (
<header className="border-b">
<nav className="container flex items-center justify-between py-4">
{/* logo: Site Settings → <Media> */}
<ul className="hidden gap-6 md:flex">
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} {...(item.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>
{item.label}
</Link>
</li>
))}
</ul>
{header.links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
<MobileNav items={items} menuLabel={header.menuLabel ?? ''} />
</nav>
</header>
)
}
```
```tsx
// src/components/layout/MobileNav.tsx — klient, tylko stan otwarcia
'use client'
import { useState } from 'react'
import Link from 'next/link'
import type { NavItem } from '@/lib/navigation' // import TYPU — nie ciągnie kodu serwera
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
const [open, setOpen] = useState(false)
return (
<div className="md:hidden">
<button type="button" aria-expanded={open} aria-label={menuLabel} onClick={() => setOpen(!open)}>
<span aria-hidden>☰</span>
</button>
{open && (
<ul>
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} onClick={() => setOpen(false)}>{item.label}</Link>
</li>
))}
</ul>
)}
</div>
)
}
```
Header/Footer pobierasz w `[locale]/layout.tsx` (przez cached getter w
`lib/`) i podajesz jako props — layout to jedyne miejsce, które je składa.
+2 -2
View File
@@ -21,10 +21,10 @@ poniżej i doczytaj po `pnpm add`). Reguły: `docs/agent/AGENT.md`.
3. **Konfiguracja** — `src/i18n.config.ts` (`as const satisfies I18nConfig`),
`payload.config.ts` wg PROGRAMISTA §2.3: `twoFactor` z **wstrzykniętym**
`payloadTotp`, `whiteLabel: true`, `email: mailAdapter()`.
4. **Rdzeń** — wspólne pola i prymitywy (AGENT.md §6.2–6.3), `Pages`, `Media`
4. **Rdzeń** — wspólne pola i prymitywy (`../ipal-block/resources/kod-sekcji.md`), `Pages`, `Media`
(PROGRAMISTA §2.4). Żadnych innych kolekcji.
5. **Style** — `styles.css` z `@theme` z `DESIGN.md` (jeśli brak — zapytaj o
Impeccable albo załóż neutralne tokeny), `@source` na plugin (AGENT.md §6.11).
Impeccable albo załóż neutralne tokeny), `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
6. **Routing** — `proxy.ts` (`createProxy`), `lib/content.ts`, layout bez
`<head>`, catch-all z ISR + `generateStaticParams` + `resolveRedirect`,
`not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md).