Files
ipal-kit/docs/links.md
T
Radosław SmolińskiandClaude Opus 5.5 f809526f1d Page-filled form fields, links to entries, entry JSON-LD, R2-optional dev
Forms: `values` on RenderForm / BuilderForm / useBuilderForm fills fields the
page knows (chosen product variant, category) — read-only <output>, in the
SSR HTML, sent and validated like any field. prepareBuilderForm (/rsc) is the
server half of RenderForm for client components whose values change in the
browser; publicForm is exported so projects stop copying it.

Links: buildLinkField({ relationTo: ['pages', 'categories', …] }) — a
polymorphic relation; resolveLinkHref builds /{locale}/{archive}/{entry} from
`archives`, which getLinkOptions in createContentHelpers fills from Site
Settings.

SEO: pageJsonLd.entries — the main JSON-LD node per content collection
instead of BlogPosting; buildProductJsonLd emits an Offer only for a real
price from the panel.

Pages: createPageRoute / createNotFoundPage pass isFirst to blocks, so the
first section carries the page's only h1.

Fixes: ipalEnvRules({ storage: true }) requires R2_* in production only
(development: optional, all or none); buildImagesConfig allows the app's own
media on localhost outside production.

Docs, CHANGELOG, PROGRAMISTA §6 (34–37), ipal-form and ipal-upgrade skills.
Tests: builderForm, links, drafts (entries + archives), seo, media, env.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:38:28 +02:00

161 lines
8.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# links
Jeden kształt linku dla całego projektu — przyciski CTA, linki w kartach,
pliki do pobrania. Pole schematu + funkcja zamieniająca wartość na `href`.
Wygląd (komponent `CMSLink`, warianty przycisków) zostaje w projekcie.
## Pola
```ts
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
fields: [
buildLinksField(), // `links`: 0–2 przyciski sekcji
buildLinksField({ maxRows: 3, appearances: ['primary', 'secondary'] }),
buildLinkField(), // `link`: pojedynczy link
buildLinkField({ disableLabel: true, appearances: false }), // klikalna cała karta
]
```
| Opcja | Domyślnie | Co robi |
|---|---|---|
| `name` | `'link'` / `'links'` | nazwa pola |
| `relationTo` | `'pages'` | kolekcja dla typu „Page” |
| `uploadTo` | `'media'` | kolekcja dla typu „File” (PDF, dokumenty) |
| `appearances` | `['primary','secondary','link']` | style do wyboru — **dowolne nazwy projektu**, np. `['primary', { label: 'Highlighted', value: 'highlight' }]` (menu z wyróżnioną pozycją, przycisk w kolorze marki); `false` = bez pola |
| `disableLabel` | `false` | bez etykiety (link owija kartę / obraz) — tylko `buildLinkField` |
| `required` | `false` | wymagane pola celu i etykiety |
| `maxRows` | `2` | tylko `buildLinksField` |
| `labels` | `{ singular: 'Button', plural: 'Buttons' }` | tylko `buildLinksField` — panel: „Add Button”; lista linków: `{ singular: 'Link', plural: 'Links' }` |
`buildLinksField` ma wbudowany `rowLabel`: zwinięty wiersz pokazuje etykietę
przycisku („Contact us”), nie „Button 01”. Wymaga wpisu w importMap —
`pnpm payload generate:importmap` po aktualizacji pluginu.
## Czytelne wiersze w innych tablicach — `rowLabel`
```ts
import { rowLabel } from '@intecion/ipal-kit'
{
name: 'items',
type: 'array',
labels: { singular: 'Feature', plural: 'Features' }, // „+ Add Feature”
admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') },
fields: [/* … */],
}
```
`rowLabel(fields, fallback)` — ścieżki w wierszu (np. `'heading'`, `['name', 'link.label']`),
pierwsza niepusta wygrywa (relacja/upload → `title`/`name`/`alt`/`filename`); wszystkie
puste → „Feature 02”. Komponent: `@intecion/ipal-kit/admin#RowLabel`. Zasady panelu: AGENT.md §6.5a.
Wartość linku: `type` (`internal` strona · `external` URL, `mailto:`, `tel:`,
`#anchor` · `file` upload), `page`, `url`, `file`, `label` (localized), `newTab`,
`appearance`. W `payload-types.ts` powstaje typ **`CmsLink`**.
Plik do pobrania to link typu `file` — **nie** osobne pole `pdfUrl`.
## Linki do wpisów kolekcji (1.11.0)
Strona, kategoria, produkt — jedno pole: `buildLinkField({ relationTo: ['pages', 'categories', 'products'] })`
(polimorficzna relacja; jedna kolekcja = jak dotąd). Wpis kolekcji z `content` rozwiązuje się do
`/{locale}/{strona-archiwum}/{wpis}` — `resolveLink` / `resolveNav` / `getLinkOptions` z `lib/content`
same biorą archiwa z Site Settings (`archives: { categories: 'kategorie' }`). Bez lib/content:
`resolveLinkHref(link, { config, locale, archives, pagesSlug })`. Wpis bez przypisanego archiwum → `null`
(link się nie renderuje). Zmiana `relationTo` na tablicę zmienia kształt danych (`page` → `{ relationTo, value }`):
istniejące linki trzeba przenieść (ipal-migrate-fields).
## href
```ts
import { resolveLinkHref } from '@intecion/ipal-kit'
resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
// internal → '/en/about' (strona główna → '/en') · external → URL · file → URL pliku
// null → pusty link, brak strony w tym języku, strona niezpopulowana (sam ID), brak pliku
```
Linki wewnętrzne wymagają **zpopulowanej** strony (`depth ≥ 2` w bloku).
`homeSlug` — slug strony głównej (string albo mapa per język, np. z
`SiteSettings.homepage`), żeby zwinąć ją do `/{locale}`.
## Link gotowy do renderu — `resolveLink`
```ts
// w komponencie serwerowym, z lib/content (locale → homeSlug i i18n same):
const l = await resolveLink(link, locale)
// bez lib/content: resolveLink(link, { locale, config: i18nConfig, homeSlug })
// → { href, label, internal, newTab, targetProps, appearance } | null
```
- `internal` → `next/link`, inaczej `<a>` (URL, plik, mailto, tel),
- `targetProps` → `{ target: '_blank', rel: 'noopener noreferrer' }` przy nowej karcie (plik zawsze),
- `appearance` → klucz wariantu w `Button.tsx` projektu,
- `null` → link prowadzi donikąd w tym języku (brak strony, pliku, niebezpieczny URL) — nic nie renderuj.
`CMSLink` zostaje w projekcie (element i klasy to wygląd), ale nie liczy niczego sam:
```tsx
// src/components/ui/CMSLink.tsx
import Link from 'next/link'
import type { ReactNode } from 'react'
import type { CmsLink } from '@/payload-types'
import { resolveLink } from '@/lib/content'
import { buttonClass } from './Button'
export async function CMSLink({ link, locale, className, children }: { link: CmsLink | null | undefined; locale: string; className?: string; children?: ReactNode }) {
const l = await resolveLink(link, locale)
const content = children ?? l?.label
if (!l || !content) return null
const cls = [l.appearance ? buttonClass(l.appearance as never) : '', className].filter(Boolean).join(' ') || undefined
return l.internal
? <Link href={l.href} className={cls} {...l.targetProps}>{content}</Link>
: <a href={l.href} className={cls} {...l.targetProps}>{content}</a>
}
```
**Nie pisz własnej wersji** (`resolveHref`, `getHref`, `` `/${slug}` ``, `slug === 'home'`): gubi prefiks
języka, stronę główną z Site Settings, filtr `javascript:` i martwe linki. `ipal-audit` zgłasza to jako
ERROR. Pole w innym kształcie (np. `page` + `url`) mapujesz na kształt pluginu zamiast liczyć href:
`resolveLink(url?.trim() ? { type: 'external', url } : { type: 'internal', page }, locale)`.
Wyróżnienie, kolor, wariant pozycji = **styl z panelu** (`appearances`), mapowany na klasy w projekcie
(`l.appearance === 'highlight'` → klasa). Nigdy logika po treści (`label === 'Tesla'`) — redaktor zmieni
nazwę i styl zniknie; `ipal-audit` zgłasza to jako ERROR.
## Linki prawne — `getSystemLinks`
```ts
const legal = await getSystemLinks(locale) // z lib/content
// [{ role: 'privacyPolicy', href: '/pl/polityka-prywatnosci', label: 'Polityka prywatności', internal, targetProps }, …]
await getSystemLinks(locale, ['privacyPolicy', 'termsOfService']) // wybrane role
// bez lib/content: resolveSystemLinks(settings, { locale, config: i18nConfig, homeSlug, roles })
```
Strony przypisane w Site Settings → System Pages; **etykieta to tytuł strony** w danym języku, więc w kodzie
nie ma tekstów („Polityka prywatności” na sztywno psuje wersję EN). Nieprzypisana rola → pominięta.
## Menu — `resolveNav`
```ts
const items = await resolveNav(header.navItems, locale) // z lib/content
// resolveNav(items, { locale, config: i18nConfig, homeSlug, linkField: 'link', childrenField: 'subItems' })
// → NavItem[]: { href, label, internal, newTab, targetProps, appearance?, children: NavItem[] }
```
Dowolna głębokość, kształt pozycji konfigurowalny (`linkField`, `childrenField`), pozycje z martwym
linkiem albo bez etykiety pominięte (zamiast `href="#"`). Wynik to zwykłe dane — idzie wprost do
klienckiego `MobileNav`. Markup menu (Header, Footer, MobileNav) zostaje w projekcie:
[kod-nawigacji.md](./agent/skills/ipal-nav/resources/kod-nawigacji.md).
`homeSlugFrom(settings)` — slug strony głównej z `SiteSettings.homepage` (lib/content: `getHomeSlug(locale)`,
a komplet opcji linków: `getLinkOptions(locale)` — też dla `RenderForm linkOptions`).
## Migracja z `src/fields/link.ts`
Projekty sprzed 1.8.x mają kopię w `src/fields/link.ts` i `src/lib/links.ts`.
Kształt danych jest identyczny (`interfaceName: 'CmsLink'`), więc **migracja
bazy nie jest potrzebna**:
1. importy `linkField` / `linksField` z `@/fields/link` → `buildLinkField` /
`buildLinksField` z `@intecion/ipal-kit`,
2. `resolveLinkHref(link, locale, homeSlug)` z `@/lib/links` →
`resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })` z pluginu,
3. usuń `src/fields/link.ts` i `src/lib/links.ts`, `pnpm generate:types`.
4. `lib/navigation.ts` z własnym `resolveNav` → `resolveNav` z `lib/content` (te same dane +
`internal`, `targetProps`; `subItems` nazywa się teraz `children`).