Docs for 1.9.2: import instead of code; docs↔code consistency test; audit accepts one-line routes
- AGENT.md: §7 full capability catalog (need → import), §0b/§3/§6 on RenderForm, SiteProviders, createPageRoute, re-exported routes, plugin section fields, resolveLink/resolveNav - PROGRAMISTA §2.4, §2.7–2.8 rewritten; §6 items 28–33 (28: FormRenderer leaked the Emails tab) - forms, links, blocks, pages, consent, turnstile, notifications, seo, mcp, i18n, deployment docs - ipal-form: RenderForm block, formClasses, CustomForm example (FormRenderer template removed), seed template handles steps and option labels per language - ipal-nav, ipal-block, ipal-setup, ipal-upgrade, ipal-seo-check, ipal-consent-check, vibe.md - ipal-audit: re-export routes and SiteProviders satisfy the mandatory set; flags form-engine copies, project section fields / navigation, server entries in client components - test/docsConsistency: docs imports exist in code; every public export is documented - CHANGELOG 1.9.2 Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -216,31 +216,31 @@ APP=$(dirs src/app)
|
||||
|
||||
if [ -n "$APP" ]; then
|
||||
# SEO
|
||||
need ERROR '' "page metadata" "generatePageMetadata (lib/content) in generateMetadata of the page routes" 'generatePageMetadata|createPageMetadata|createMetadataGenerator' src/app
|
||||
need ERROR '' "page metadata" "generatePageMetadata (lib/content) in generateMetadata of the page routes" 'generatePageMetadata|createPageMetadata|createMetadataGenerator|createPageRoute' src/app
|
||||
need ERROR '' "sitemap.xml route" "src/app/sitemap.xml/route.ts → sitemapRoute" 'sitemapRoute|createSitemapRouteHandler|buildSitemapEntries|sitemap' src/app/sitemap.xml src/app/sitemap.ts
|
||||
need ERROR '' "robots" "src/app/robots.ts → robots from lib/content" 'robots|buildRobots' src/app/robots.ts
|
||||
need ERROR '' "manifest" "src/app/manifest.ts → createManifestHandler" 'createManifestHandler|buildManifest' src/app/manifest.ts
|
||||
need ERROR '' "manifest" "src/app/manifest.ts → export { manifest as default } from '@/lib/content'" 'manifest|createManifestHandler|buildManifest' src/app/manifest.ts
|
||||
need ERROR '' "htmlLimitedBots" "next.config.ts — metadata must reach crawlers in <head>" 'htmlLimitedBots' next.config.ts next.config.mjs next.config.js
|
||||
need ERROR jsonld "structured data" "<JsonLdGraph> with WebSite + Organization/LocalBusiness in [locale]/layout.tsx" 'JsonLdGraph' src
|
||||
need ERROR jsonld "structured data" "<SiteProviders shell={await getSiteShell(locale)}> (WebSite + Organization) or <JsonLdGraph> in [locale]/layout.tsx" 'JsonLdGraph|SiteProviders' src
|
||||
# GEO
|
||||
need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → createLlmsTxtRoute" 'createLlmsTxtRoute|buildLlmsTxt' src/app
|
||||
need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → createLlmsTxtRoute({ full: true })" 'full: *true' src/app/llms-full.txt
|
||||
need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts → createMarkdownRoute" 'createMarkdownRoute|createMarkdownRenderer' src/app
|
||||
need WARNING jsonld "page structured data" "[[...slug]]/page.tsx → <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />" 'getPageJsonLd|buildWebPageJsonLd|buildBreadcrumbJsonLd' src/app
|
||||
need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → export { llmsRoute as GET } from '@/lib/content'" 'llmsRoute|createLlmsTxtRoute|buildLlmsTxt' src/app
|
||||
need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → export { llmsFullRoute as GET } from '@/lib/content'" 'llmsFullRoute|full: *true' src/app/llms-full.txt
|
||||
need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts → export { markdownRoute as GET } from '@/lib/content'" 'markdownRoute|createMarkdownRoute|createMarkdownRenderer' src/app
|
||||
need WARNING jsonld "page structured data" "[[...slug]]/page.tsx → createPageRoute (adds getPageJsonLd) or <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />" 'createPageRoute|getPageJsonLd|buildWebPageJsonLd|buildBreadcrumbJsonLd' src/app
|
||||
need ERROR markdown "Markdown in proxy" "proxy.ts → createProxy(i18nConfig, { NextResponse, markdown: true }) — without it /md/… is redirected to /<locale>/md/…" 'markdown: *(true|['"'"'"])|prefersMarkdown' src/proxy.ts proxy.ts
|
||||
need WARNING markdown "Markdown alternate link" "createContentHelpers({ markdownAlternate: true }) or markdownHref in metadata" 'markdownAlternate|markdownHref' src
|
||||
need ERROR mcp "MCP server" "src/app/api/mcp/route.ts → createMcpRoute (public: AI browses the site)" 'createMcpRoute' src/app
|
||||
need WARNING '' "AI summary field" "buildSummaryField() in Pages + summaryField: 'aiSummary' in llms/MCP routes" 'buildSummaryField' src
|
||||
need ERROR mcp "MCP server" "src/app/api/mcp/route.ts → export { mcpGET as GET, mcpPOST as POST } from '@/lib/content' (public: AI browses the site)" 'mcpPOST|createMcpRoute' src/app
|
||||
need WARNING '' "AI summary field" "buildSummaryField() in Pages + createContentHelpers({ summaryField: 'aiSummary' })" 'buildSummaryField' src
|
||||
# Ops
|
||||
need ERROR '' "health route" "src/app/api/health/route.ts → createHealthRoute" 'createHealthRoute' src/app
|
||||
need ERROR '' "health route" "src/app/api/health/route.ts → export { healthRoute as GET } from '@/lib/content'" 'healthRoute|createHealthRoute' src/app
|
||||
need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(ipalEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts
|
||||
need ERROR '' "security headers" "next.config.ts → buildSecurityHeaders" 'buildSecurityHeaders' next.config.ts next.config.mjs next.config.js
|
||||
# Consent, analytics, Turnstile (layout)
|
||||
need ERROR '' "cookie consent" "ConsentProvider + CookieBanner + CookieButton in [locale]/layout.tsx" 'CookieBanner' src/app
|
||||
need ERROR analytics "analytics" "<Analytics> inside ConsentProvider (IDs from the panel)" '<Analytics' src/app
|
||||
need ERROR turnstile "Turnstile provider" "<TurnstileProvider siteKey> in [locale]/layout.tsx — always, it hides itself without keys" 'TurnstileProvider' src
|
||||
need WARNING turnstile "getTurnstileConfig" "siteKey from getTurnstileConfig(payload) — off unless BOTH keys are set" 'getTurnstileConfig' src
|
||||
need WARNING '' "MediaPreconnect" "<MediaPreconnect/> in the layout (R2 CDN preconnect from env)" 'MediaPreconnect' src/app
|
||||
need ERROR '' "cookie consent" "<SiteProviders> (or ConsentProvider + CookieBanner + CookieButton) in [locale]/layout.tsx" 'SiteProviders|CookieBanner' src/app
|
||||
need ERROR analytics "analytics" "<SiteProviders> (loads Analytics) or <Analytics> inside ConsentProvider" 'SiteProviders|<Analytics' src/app
|
||||
need ERROR turnstile "Turnstile provider" "<SiteProviders> or <TurnstileProvider siteKey> in [locale]/layout.tsx — always, it hides itself without keys" 'SiteProviders|TurnstileProvider' src
|
||||
need WARNING turnstile "Turnstile site key" "getSiteShell(locale) (or getTurnstileConfig(payload)) — off unless BOTH keys are set" 'getSiteShell|getTurnstileConfig' src
|
||||
need WARNING '' "MediaPreconnect" "<SiteProviders> (adds it) or <MediaPreconnect/> in the layout" 'SiteProviders|MediaPreconnect' src/app
|
||||
# Forms
|
||||
need ERROR '' "form submission via the plugin" "actions.ts → export const sendForm = createSubmitAction({ getCachedPayload, headers }) (ipal-form)" 'createSubmitAction|submitForm' src
|
||||
need WARNING '' "upload sandbox headers" "next.config.ts → ...buildUploadSecurityHeaders() (uploaded SVG can't run script)" 'buildUploadSecurityHeaders' next.config.ts next.config.mjs next.config.js
|
||||
@@ -271,9 +271,21 @@ report ERROR "hand-written JSON-LD script" "§0b — <JsonLdGraph> escapes and w
|
||||
"$(g 'application/ld\+json' src --include=*.tsx | grep -v 'JsonLdGraph')"
|
||||
report ERROR "static SEO files in public/" "§0b — sitemap, robots and llms are generated from the panel" \
|
||||
"$(ls public/sitemap.xml public/robots.txt public/llms.txt public/llms-full.txt 2>/dev/null)"
|
||||
report WARNING "<form> outside the form renderer" "§0b — forms render from the panel via FormRenderer (a search box is fine)" \
|
||||
report WARNING "<form> outside the form renderer" "§0b — panel forms render via <RenderForm> (a search box is fine)" \
|
||||
"$(g '<form[ >]' src --include=*.tsx | grep -v 'components/forms/')"
|
||||
|
||||
# Project copies of what the plugin now ships (import instead of code)
|
||||
report WARNING "own form engine" "ipal-form §3 — <RenderForm> / useBuilderForm (steps, choices, Turnstile, honeypot; Emails tab never reaches the browser)" \
|
||||
"$(g 'buildValidator|useForm\(' src --include=*.tsx | grep -v 'useBuilderForm')"
|
||||
report WARNING "project copy of section fields / navigation" "blocks.md, links.md — buildSectionHeaderField, buildSectionSettingsField, resolveNav (lib/content)" \
|
||||
"$(ls src/fields/sectionHeader.ts src/fields/sectionSettings.ts src/lib/navigation.ts 2>/dev/null)"
|
||||
if [ -n "$UI" ]; then
|
||||
for c in $(grep -rlE "^['\"]use client['\"]" $UI 2>/dev/null); do
|
||||
report ERROR "server entry in client component" "§6.9 '@intecion/ipal-kit' (root), '/rsc', '/server' pull Payload into the browser — client code imports '/client' (types: import type)" \
|
||||
"$(grep -nE "from '@intecion/ipal-kit(/rsc|/server)?'" "$c" | grep -v 'import type' | sed "s|^|$c:|")"
|
||||
done
|
||||
fi
|
||||
|
||||
# --- Compile & build ---
|
||||
if [ "$QUICK" -eq 0 ]; then
|
||||
echo
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: ipal-block
|
||||
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short English labels, no empty spare fields), 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.
|
||||
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short English labels, no empty spare fields), shared fields from the plugin (buildSectionHeaderField, buildLinksField, buildLinkField, buildSectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
|
||||
---
|
||||
|
||||
# ipal-block
|
||||
@@ -9,9 +9,9 @@ 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/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.
|
||||
Sprawdź, czy istnieją: `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
|
||||
Stare `src/fields/sectionHeader.ts` / `sectionSettings.ts` → zamień na import z pluginu i usuń (blocks.md, bez migracji).
|
||||
Linki (`buildLinkField`, `buildLinksField`, `resolveLink`) i pola sekcji (`buildSectionHeaderField`, `buildSectionSettingsField`) 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.
|
||||
|
||||
@@ -27,7 +27,7 @@ Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
|
||||
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 = `buildLinksField()`, nigdy pola `cta*`/`button*`.
|
||||
zawsze `buildSectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
|
||||
Plik do pobrania = link typu `file`. **Panel wg AGENT.md §6.5a:**
|
||||
- powtarzalne → tablica z `labels: { singular, plural }` + `admin: { initCollapsed: true, components: rowLabel('heading', '<Singular>') }`, `maxRows` z designu;
|
||||
- zero numerowanych pól (`cta1`, `feature2Title`, `image3`) i pól „na zapas”;
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
> 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.
|
||||
> `resolveLink`), pola sekcji (`buildSectionHeaderField`, `buildSectionSettingsField`) i menu
|
||||
> (`resolveNav`) są w pluginie — nie twórz ich kopii.
|
||||
|
||||
## Warstwa 1 — wspólne pola
|
||||
|
||||
@@ -29,53 +30,17 @@ 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`:
|
||||
**Nagłówek i ustawienia sekcji — z pluginu, nie kopiuj kodu** (`docs/blocks.md`):
|
||||
|
||||
```ts
|
||||
import type { GroupField } from 'payload'
|
||||
import { buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
|
||||
|
||||
export function sectionHeaderField(name = 'header'): GroupField {
|
||||
return {
|
||||
name,
|
||||
type: 'group',
|
||||
interfaceName: 'SectionHeaderData',
|
||||
fields: [
|
||||
{ name: 'eyebrow', type: 'text', localized: true, admin: { description: 'Small line above the heading. Optional.' } },
|
||||
{ name: 'heading', type: 'text', localized: true },
|
||||
{ name: 'intro', type: 'textarea', localized: true, admin: { rows: 3 } },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
export function sectionSettingsField(): GroupField {
|
||||
return {
|
||||
name: 'settings',
|
||||
type: 'group',
|
||||
label: 'Section settings',
|
||||
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: [
|
||||
{ label: 'Default', value: 'default' },
|
||||
{ label: 'Muted', value: 'muted' },
|
||||
{ label: 'Inverted (dark)', value: 'inverted' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
buildSectionHeaderField() // grupa `header`: eyebrow, heading, intro (localized) — typ SectionHeaderData
|
||||
buildSectionSettingsField() // sidebar `settings`: anchor, background (default/muted/inverted) — typ SectionSettings
|
||||
buildSectionSettingsField({ backgrounds: [{ label: 'Default', value: 'default' }, { label: 'Brand', value: 'brand' }] })
|
||||
```
|
||||
|
||||
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
|
||||
Każda sekcja ma `buildSectionSettingsField()` — żadnych `bgColor`, `darkMode`,
|
||||
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
|
||||
|
||||
## Warstwa 2 — prymitywy UI
|
||||
@@ -85,11 +50,10 @@ Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
|
||||
```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 { resolveLink } from '@/lib/content'
|
||||
import { buttonClass } from './Button'
|
||||
import type { LinkAppearance } from '@intecion/ipal-kit'
|
||||
|
||||
type Props = {
|
||||
link: CmsLink | null | undefined
|
||||
@@ -99,25 +63,15 @@ type Props = {
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
// href, new tab, rel, internal/external — from the plugin. Here: the element and the classes.
|
||||
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>
|
||||
const l = await resolveLink(link, locale)
|
||||
const content = children ?? l?.label
|
||||
if (!l || !content) return null
|
||||
const cls = [l.appearance ? buttonClass(l.appearance as LinkAppearance) : '', 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>
|
||||
}
|
||||
```
|
||||
|
||||
@@ -225,18 +179,17 @@ const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> w la
|
||||
// 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'
|
||||
import { buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
|
||||
|
||||
export const HeroBlock: Block = {
|
||||
slug: 'hero',
|
||||
interfaceName: 'HeroBlock',
|
||||
labels: { singular: 'Hero', plural: 'Heroes' },
|
||||
fields: [
|
||||
sectionHeaderField(),
|
||||
buildSectionHeaderField(),
|
||||
{ name: 'media', type: 'upload', relationTo: 'media' },
|
||||
buildLinksField(),
|
||||
sectionSettingsField(),
|
||||
buildSectionSettingsField(),
|
||||
],
|
||||
}
|
||||
```
|
||||
@@ -272,7 +225,7 @@ Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
|
||||
|
||||
```ts
|
||||
// src/blocks/FeatureGrid/config.ts (fields) — import { buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
|
||||
sectionHeaderField(),
|
||||
buildSectionHeaderField(),
|
||||
{
|
||||
name: 'items',
|
||||
type: 'array',
|
||||
@@ -289,7 +242,7 @@ sectionHeaderField(),
|
||||
],
|
||||
},
|
||||
buildLinksField({ maxRows: 1 }),
|
||||
sectionSettingsField(),
|
||||
buildSectionSettingsField(),
|
||||
```
|
||||
|
||||
```tsx
|
||||
|
||||
@@ -26,7 +26,7 @@ się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ci
|
||||
|---|---|
|
||||
| piksel loaded without consent | skrypt wpięty ręcznie / skopiowany `Analytics` → ID w Site Integrations, `<Analytics>` z pluginu (analytics.md) |
|
||||
| tracking cookie set without consent | to samo; albo GTM odpala tag bez warunku `ad_storage` (analytics.md → GTM) |
|
||||
| GA hit with consent GRANTED | `setDefaultConsent` nie przed tagiem — `<Analytics>` musi być wewnątrz `<ConsentProvider>` |
|
||||
| GA hit with consent GRANTED | `setDefaultConsent` nie przed tagiem — `<Analytics>` musi być wewnątrz `<ConsentProvider>` (`SiteProviders` robi to sam) |
|
||||
| YouTube / Maps before consent (warning) | `ConsentScript` (consent.md), `youtube-nocookie.com` albo „kliknij, aby załadować” |
|
||||
|
||||
4. Sekcja „after accept” mówi, co startuje po zgodzie — porównaj z ID w Site
|
||||
|
||||
@@ -5,8 +5,8 @@ description: Wires forms the ipal-kit way — forms built by the editor in the p
|
||||
|
||||
# ipal-form
|
||||
|
||||
**Formularz buduje redaktor w panelu. Ty piszesz raz: renderer + akcję.** Każdy
|
||||
kolejny formularz to tylko panel. Ręcznie wpisane pola/etykiety w JSX = błąd
|
||||
**Formularz buduje redaktor w panelu. Projekt ma akcję, blok z `<RenderForm>` i klasy.** Każdy
|
||||
kolejny formularz — także krokowy, z listami wyboru — to tylko panel. Ręcznie wpisane pola/etykiety w JSX = błąd
|
||||
(ipal-audit to złapie). Szczegóły API: `docs/forms.md`, `turnstile.md`, `notifications.md`, `email.md`.
|
||||
|
||||
## 1. Config (raz na projekt)
|
||||
@@ -29,42 +29,60 @@ export default buildConfig({
|
||||
`generate:importmap`, restart.
|
||||
|
||||
## 2. Layout — Turnstile raz
|
||||
`<TurnstileProvider siteKey={(await getTurnstileConfig(payload)).siteKey}>` w
|
||||
`[locale]/layout.tsx` (turnstile.md) — **zawsze**, nie warunkuj providera ani widgetu.
|
||||
`<SiteProviders shell={await getSiteShell(locale)}>` w `[locale]/layout.tsx` (PROGRAMISTA §2.8)
|
||||
wpina `TurnstileProvider` z kluczem z panelu — **zawsze**, nie warunkuj providera ani widgetu.
|
||||
Własny layout bez SiteProviders: `<TurnstileProvider siteKey={shell.turnstileSiteKey}>` (turnstile.md).
|
||||
Zachowanie z pluginu: **oba klucze** (panel lub env) → widget widoczny, a `submitForm`
|
||||
**wymaga** tokenu (bot nie ominie, nie wysyłając go); brak kluczy → widgetu nie ma,
|
||||
weryfikacji nie ma, formularz działa; jeden klucz → wyłączony + alert na dashboardzie.
|
||||
|
||||
## 3. Kod (skopiuj z `resources/`, dostosuj tylko klasy)
|
||||
## 3. Kod — import, nie kopia
|
||||
Renderer, kroki, walidacja, Turnstile, honeypot, przekierowanie i zdarzenie GTM są w
|
||||
pluginie. W projekcie zostają **trzy krótkie pliki**:
|
||||
|
||||
| Plik | Do projektu | Rola |
|
||||
|---|---|---|
|
||||
| `actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | `export const sendForm = createSubmitAction({ getCachedPayload, headers })` — honeypot → IP → `submitForm` → tekst z Notifications |
|
||||
| `seed-form.template.ts` | `scripts/seed-form-<nazwa>.ts` | formularz w bazie: pola, potwierdzenie, mail do firmy + do klienta, każdy język |
|
||||
| `FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | serwer: RichText (potwierdzenie, pola „message”), bind akcji |
|
||||
| `FormRenderer.tsx` | `src/components/forms/FormRenderer.tsx` | klient: dowolny formularz z panelu przez `useForm` |
|
||||
| `resources/actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | `export const sendForm = createSubmitAction({ getCachedPayload, headers })` |
|
||||
| `resources/FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | `<RenderForm>` z `/rsc` + klasy projektu, w `<Section>`/`<SectionHeader>` |
|
||||
| `resources/formClasses.ts` | `src/components/forms/formClasses.ts` | **jedyne** miejsce wyglądu formularzy (klasy z DESIGN.md) |
|
||||
| `resources/seed-form.template.ts` | `scripts/seed-form-<nazwa>.ts` | formularz w bazie: pola, potwierdzenie, mail do firmy + do klienta, każdy język |
|
||||
|
||||
Renderer obsługuje typy buildera `text, email, textarea, number, select, checkbox,
|
||||
message` (`country/state` jako tekst), `width` ≤ 50 → pół szerokości, `required`,
|
||||
potwierdzenie albo redirect, a11y (`label for`, `aria-invalid`, `role="alert"`),
|
||||
honeypot, Turnstile, zdarzenie GTM z panelu. Nie dopisuj własnej walidacji
|
||||
„na sztywno” — reguły wynikają z definicji pola.
|
||||
`RenderForm` (serwer) renderuje bloki „message” i potwierdzenie przez `RenderRichText`,
|
||||
wiąże akcję z formularzem i językiem, rozwiązuje redirect i **wysyła do przeglądarki tylko
|
||||
publiczną część formularza** (zakładka Emails z adresami firmy nigdy nie trafia do HTML).
|
||||
Pod spodem `BuilderForm` (klient) — czysty, dostępny HTML **bez stylów**: wygląd = `classNames`
|
||||
(+ atrybuty `data-ipal`, `data-type`, `data-width`, `data-step`).
|
||||
|
||||
## 4. Strona — dane do bloku przez enhanceProps (bloki nie importują `lib/*`)
|
||||
**Typy pól w panelu:** text, email, textarea, number, **date**, select, **radio** (jeden wybór),
|
||||
checkbox, **Checkbox group** (wiele wyborów, min/max), message, **Step** (podział na kroki).
|
||||
- **Formularz krokowy:** redaktor wstawia blok **Step** (tytuł, opis) — pola pod nim to jeden
|
||||
ekran. Przyciski Dalej/Wstecz i „Krok 1 z 3” z **Notifications → Form messages** (next, back,
|
||||
stepOf). Dalej waliduje tylko bieżący krok; błąd z serwera wraca na krok z polem; fokus
|
||||
przechodzi na nowy krok. Bez Step = jeden ekran.
|
||||
- `width` ≤ 50 → klasa `fieldHalf`, inaczej `fieldFull`.
|
||||
|
||||
**Formularz nietypowy** (karty do wyboru zamiast radio, podsumowanie przed wysłaniem,
|
||||
własny typ pola, suwak): nie kopiuj silnika — w kolejności:
|
||||
1. `renderField` w `BuilderForm` (plik `'use client'`): podmieniasz wybrane pola, reszta domyślna
|
||||
(`defaultRender()` daje oryginał do owinięcia);
|
||||
2. własny komponent na `useBuilderForm` — pełna kontrola nad markupem, ta sama logika
|
||||
(`resources/CustomForm.example.tsx`): `steps`, `step`, `next/back/goTo`, `submit`,
|
||||
`getInputProps / getTextareaProps / getSelectProps / getOptionProps`, `errors`, `TurnstileWidget`.
|
||||
Własny typ pola w panelu: `forms.fields: { mojTyp: { slug, fields } }` (blok form-buildera)
|
||||
+ `renderField`; serwer przyjmie go jako tekst — potrzebujesz innej walidacji → **ipal-plugin-gap**.
|
||||
|
||||
## 4. Strona — dane do bloku raz (bloki nie importują `lib/*`)
|
||||
Z `createPageRoute` (PROGRAMISTA §2.8):
|
||||
```tsx
|
||||
// [locale]/[[...slug]]/page.tsx
|
||||
import { getNotificationTexts } from '@intecion/ipal-kit'
|
||||
import { sendForm } from '../actions'
|
||||
const formTexts = doc.layout?.some((b) => b.blockType === 'formBlock')
|
||||
? (await getNotificationTexts({ payload: await getCachedPayload(), locale })).form
|
||||
: undefined
|
||||
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
|
||||
locale,
|
||||
...(block.blockType === 'formBlock' ? { formTexts, sendForm } : {}),
|
||||
const route = createPageRoute(content, {
|
||||
blocks: blockRegistry, notFound, permanentRedirect,
|
||||
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
|
||||
})
|
||||
```
|
||||
Własna strona: to samo w `enhanceProps` (`formTexts` z `getFormTexts(locale)`, `sendForm` z `actions.ts`).
|
||||
Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków:
|
||||
`formBlock: FormBlock`. Formularz poza blokiem (stopka, modal) = ten sam
|
||||
`FormRenderer` z formularzem pobranym po ID z globalu (relacja w Footer), nigdy kopia.
|
||||
`formBlock: FormBlock`. Formularz poza blokiem (stopka, modal) = ten sam `<RenderForm>`
|
||||
z formularzem z relacji w globalu, nigdy kopia.
|
||||
|
||||
## 5. Formularz w bazie — ZAWSZE seedem (`resources/seed-form.template.ts`)
|
||||
Każdy formularz z briefu powstaje skryptem, nie ręcznie: wtedy jest powtarzalny (dev → produkcja),
|
||||
@@ -108,7 +126,8 @@ Szczegóły, które seed już spełnia, a które sprawdzasz po każdej ręcznej
|
||||
- [ ] Turnstile bez kluczy → brak widgetu, formularz przechodzi;
|
||||
- [ ] drugi język → etykiety i komunikaty w tym języku;
|
||||
- [ ] GTM Preview → zdarzenie z nazwą z panelu po sukcesie;
|
||||
- [ ] `ipal-audit --quick` → zero hardkodów w FormRenderer/FormBlock;
|
||||
- [ ] formularz krokowy: Dalej z pustym krokiem → błędy, krok zostaje; Wstecz zachowuje wpisane wartości;
|
||||
- [ ] `ipal-audit --quick` → zero hardkodów w FormBlock, brak kopii silnika formularza;
|
||||
- [ ] `ipal-consent-check` → nadal 0 naruszeń (Turnstile to niezbędny, nie śledzący).
|
||||
|
||||
## Diagnostyka
|
||||
@@ -116,14 +135,10 @@ Szczegóły, które seed już spełnia, a które sprawdzasz po każdej ręcznej
|
||||
|---|---|
|
||||
| brak kolekcji Forms w panelu | rozjazd wersji form-buildera vs payload → ta sama wersja, `pnpm.overrides` |
|
||||
| blok renderuje nic | `form` to ID (za małe `depth`) albo brak `formTexts`/`sendForm` w enhanceProps |
|
||||
| `reason: 'validation'`, `kind: 'unknown_fields'` | front wysyła pole, którego formularz nie ma (honeypot nieusunięty w akcji, literówka w `name`) |
|
||||
| `reason: 'validation'`, `kind: 'unknown_fields'` | front wysyła pole, którego formularz nie ma (własny renderer z dodatkowym polem, literówka w `name`) |
|
||||
| przyciski „Next/Back” po angielsku | puste Notifications → Form messages → next / back / stepOf w tym języku |
|
||||
| `reason: 'not_found'` | `formId` z innej bazy (seed na dev, prod inny ID) — relacja z panelu, nie stałe ID w kodzie |
|
||||
| zgłoszenie jest, maila brak | brak `email: mailAdapter()`, pusta zakładka Emails, transport w panelu; logi serwera |
|
||||
| zawsze `turnstile` | token jednorazowy — `ts.reset()` po błędzie (jest w rendererze); zła para kluczy / domena w Cloudflare |
|
||||
| zawsze `turnstile` | zła para kluczy / domena w Cloudflare (reset tokenu po błędzie robi BuilderForm) |
|
||||
| strona stała się dynamiczna (`ƒ`) | `headers()` w komponencie zamiast w akcji |
|
||||
| komunikaty po angielsku | puste Notifications w tym języku |
|
||||
|
||||
## Znane ograniczenie pluginu
|
||||
`useForm` trzyma własny stan tokenu, `useTurnstile` swój — renderer synchronizuje je
|
||||
`useEffect`em. Jeśli w kolejnym projekcie to przeszkadza, zgłoś przez **ipal-plugin-gap**
|
||||
(propozycja: `useForm` czyta token z `TurnstileProvider`, gdy jest w drzewie).
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// Only for a form that looks or behaves unlike the default (option cards, a
|
||||
// summary step, a custom field type). Same engine as BuilderForm — you write the
|
||||
// markup only. Ordinary forms: RenderForm in FormBlock, no file like this.
|
||||
//
|
||||
// Lighter option first: <BuilderForm renderField={…}> replaces chosen fields only.
|
||||
'use client'
|
||||
import { honeypotInputProps, useBuilderForm, type UseBuilderFormOptions } from '@intecion/ipal-kit/client'
|
||||
|
||||
export function QuoteCardsForm(props: UseBuilderFormOptions) {
|
||||
const f = useBuilderForm(props)
|
||||
if (f.isSuccess) return <div role="status">{f.resultMessage}</div>
|
||||
|
||||
return (
|
||||
<form onSubmit={f.submit} noValidate>
|
||||
<input {...honeypotInputProps()} />
|
||||
{f.total > 1 && <p aria-live="polite">{props.texts.stepOf?.replace('{current}', String(f.stepIndex + 1)).replace('{total}', String(f.total))}</p>}
|
||||
|
||||
{f.step.fields.map(({ field }) => {
|
||||
if (!field.name) return null
|
||||
if (field.blockType === 'radio') {
|
||||
// options as clickable cards — still a real radio group (keyboard, screen readers)
|
||||
return (
|
||||
<fieldset key={field.name} id={f.fieldId(field)} aria-invalid={f.getFieldProps(field)['aria-invalid']} aria-describedby={f.getFieldProps(field)['aria-describedby']}>
|
||||
<legend>{field.label}</legend>
|
||||
{(field.options ?? []).map((o, i) => (
|
||||
<label key={o.value} className="card">
|
||||
<input {...f.getOptionProps(field, o, i)} className="sr-only" />
|
||||
{o.label}
|
||||
</label>
|
||||
))}
|
||||
{f.errors[field.name] && <p id={f.errorId(field)}>{f.errors[field.name]}</p>}
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div key={field.name}>
|
||||
<label htmlFor={f.fieldId(field)}>{field.label}</label>
|
||||
{field.blockType === 'textarea' ? <textarea {...f.getTextareaProps(field)} /> : <input {...f.getInputProps(field)} />}
|
||||
{f.errors[field.name] && <p id={f.errorId(field)}>{f.errors[field.name]}</p>}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{f.isLast && <f.TurnstileWidget />}
|
||||
{f.errorMessage && <p role="alert">{f.errorMessage}</p>}
|
||||
{!f.isFirst && <button type="button" onClick={f.back}>{props.texts.back}</button>}
|
||||
<button type="submit" disabled={f.isSubmitting}>{f.isLast ? props.form.submitButtonLabel : props.texts.next}</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,39 +1,26 @@
|
||||
// src/blocks/FormBlock/Component.tsx — SERVER part: rich text from the panel + bound action.
|
||||
// src/blocks/FormBlock/Component.tsx — a panel form inside a section. Logic, steps,
|
||||
// validation, Turnstile, honeypot and rich text come from ipal-kit; the look is
|
||||
// formClasses (one file for every form on the site).
|
||||
// Block config (src/blocks/FormBlock/config.ts): slug 'formBlock', fields
|
||||
// { name: 'form', type: 'relationship', relationTo: 'forms', required: true } + the
|
||||
// shared section fields (eyebrow/heading/intro, anchor, background) — ipal-block.
|
||||
// Page query depth ≥ 1, otherwise `form` is just an ID. Wrap the output in the
|
||||
// project's <Section>/<SectionHeader> like every other block.
|
||||
// Blocks never import lib/* or app/* (AGENT.md §4.10) — texts and the server action
|
||||
// come in through enhanceProps from the page route (SKILL.md, step 4).
|
||||
import type { ReactNode } from 'react'
|
||||
// buildSectionHeaderField(), { name: 'form', type: 'relationship', relationTo: 'forms', required: true },
|
||||
// buildSectionSettingsField()
|
||||
// Page query depth ≥ 1, otherwise `form` is just an ID (RenderForm renders nothing).
|
||||
// `formTexts` and `sendForm` arrive via createPageRoute blockProps (ipal-form SKILL §4).
|
||||
import type { FormNotificationTexts } from '@intecion/ipal-kit'
|
||||
import { RichText } from '@/components/RichText'
|
||||
import { FormRenderer, type BuilderForm, type FormAction } from '@/components/forms/FormRenderer'
|
||||
import { RenderForm, type SendFormAction } from '@intecion/ipal-kit/rsc'
|
||||
import type { FormBlock as FormBlockData } from '@/payload-types'
|
||||
import { formClasses } from '@/components/forms/formClasses'
|
||||
import { Section } from '@/components/ui/Section'
|
||||
import { SectionHeader } from '@/components/ui/SectionHeader'
|
||||
|
||||
type Props = {
|
||||
form?: BuilderForm | string | number | null
|
||||
locale: string
|
||||
formTexts?: FormNotificationTexts
|
||||
sendForm?: (formId: string, locale: string, values: Record<string, unknown>, token?: string) => ReturnType<FormAction>
|
||||
}
|
||||
|
||||
export function FormBlock({ form, locale, formTexts, sendForm }: Props) {
|
||||
if (!form || typeof form !== 'object' || !formTexts || !sendForm) return null // never a fake/hardcoded form
|
||||
|
||||
const messages: Record<number, ReactNode> = {}
|
||||
form.fields?.forEach((f, i) => {
|
||||
if (f.blockType === 'message' && f.message) messages[i] = <RichText data={f.message as never} />
|
||||
})
|
||||
const confirmation = form.confirmationMessage ? <RichText data={form.confirmationMessage as never} /> : null
|
||||
type Props = FormBlockData & { locale: string; formTexts?: FormNotificationTexts; sendForm?: SendFormAction }
|
||||
|
||||
export function FormBlock({ form, header, settings, locale, formTexts, sendForm }: Props) {
|
||||
if (!formTexts || !sendForm) return null // never a fake/hardcoded form
|
||||
return (
|
||||
<FormRenderer
|
||||
form={form}
|
||||
messages={messages}
|
||||
confirmation={confirmation}
|
||||
validationText={formTexts.validation}
|
||||
action={sendForm.bind(null, String(form.id), locale)}
|
||||
/>
|
||||
<Section settings={settings}>
|
||||
<SectionHeader header={header} />
|
||||
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
// src/components/forms/FormRenderer.tsx — CLIENT part: renders ANY form built in the panel.
|
||||
// Logic from ipal-kit, markup + classes are the project's (restyle freely, keep the wiring).
|
||||
'use client'
|
||||
import { useEffect, useMemo, type ReactNode } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
useForm, buildValidator, required, email, checked, honeypotInputProps,
|
||||
useTurnstile, formAnalyticsOnSuccess, type FormAnalyticsConfig,
|
||||
} from '@intecion/ipal-kit/client'
|
||||
|
||||
type Option = { label?: string | null; value: string }
|
||||
export type BuilderField = {
|
||||
blockType: 'text' | 'textarea' | 'email' | 'number' | 'select' | 'checkbox' | 'country' | 'state' | 'message' | string
|
||||
name?: string | null
|
||||
label?: string | null
|
||||
required?: boolean | null
|
||||
width?: number | null
|
||||
defaultValue?: unknown
|
||||
options?: Option[] | null
|
||||
message?: unknown
|
||||
}
|
||||
export type BuilderForm = {
|
||||
id: string | number
|
||||
fields?: BuilderField[] | null
|
||||
submitButtonLabel?: string | null
|
||||
confirmationType?: 'message' | 'redirect' | null
|
||||
confirmationMessage?: unknown
|
||||
redirect?: { url?: string | null } | null
|
||||
analytics?: FormAnalyticsConfig
|
||||
}
|
||||
export type FormAction = (values: Record<string, unknown>, turnstileToken?: string) => Promise<{ success: boolean; message?: string }>
|
||||
type Props = {
|
||||
form: BuilderForm
|
||||
action: FormAction
|
||||
messages: Record<number, ReactNode>
|
||||
confirmation: ReactNode
|
||||
/** Notifications → form.validation, may contain {field}. */
|
||||
validationText: string
|
||||
}
|
||||
|
||||
export function FormRenderer({ form, action, messages, confirmation, validationText }: Props) {
|
||||
const router = useRouter()
|
||||
const ts = useTurnstile() // needs <TurnstileProvider> in the layout (siteKey may be empty → disabled)
|
||||
const fields = (form.fields ?? []).filter((f) => f.blockType !== 'message' && f.name)
|
||||
const msg = (f: BuilderField) => validationText.replace('{field}', f.label || f.name || '')
|
||||
|
||||
const initialValues = useMemo(
|
||||
() => Object.fromEntries(fields.map((f) => [f.name as string, f.blockType === 'checkbox' ? Boolean(f.defaultValue) : (f.defaultValue as string) ?? ''])),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[form.id],
|
||||
)
|
||||
const validate = useMemo(
|
||||
() =>
|
||||
buildValidator<Record<string, unknown>>(
|
||||
Object.fromEntries(
|
||||
fields.map((f) => {
|
||||
const rules = []
|
||||
if (f.required) rules.push(f.blockType === 'checkbox' ? checked(msg(f)) : required(msg(f)))
|
||||
if (f.blockType === 'email') rules.push(email(msg(f)))
|
||||
return [f.name as string, rules]
|
||||
}),
|
||||
),
|
||||
),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[form.id, validationText],
|
||||
)
|
||||
|
||||
const f = useForm({
|
||||
initialValues,
|
||||
validate,
|
||||
submitAction: action,
|
||||
requireTurnstile: ts.enabled,
|
||||
onSuccess: (result, values) => {
|
||||
formAnalyticsOnSuccess(form.analytics)(result, values)
|
||||
if (form.confirmationType === 'redirect' && form.redirect?.url) router.push(form.redirect.url)
|
||||
},
|
||||
})
|
||||
// Turnstile token lives in the provider; the form engine needs it too.
|
||||
useEffect(() => f.setTurnstileToken(ts.token), [ts.token]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => { if (f.errorMessage) ts.reset() }, [f.errorMessage]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
if (f.isSuccess && form.confirmationType !== 'redirect') return <div role="status">{confirmation}</div>
|
||||
|
||||
return (
|
||||
<form onSubmit={f.handleSubmit} noValidate className="grid grid-cols-12 gap-4">
|
||||
<input {...honeypotInputProps()} />
|
||||
{(form.fields ?? []).map((field, i) => {
|
||||
if (field.blockType === 'message') return <div key={i} className="col-span-12">{messages[i]}</div>
|
||||
const name = field.name as string
|
||||
const id = `f-${String(form.id)}-${name}`
|
||||
const error = f.errors[name]
|
||||
const span = field.width && field.width <= 50 ? 'col-span-12 md:col-span-6' : 'col-span-12'
|
||||
const common = {
|
||||
id, name, required: Boolean(field.required),
|
||||
'aria-invalid': Boolean(error) || undefined,
|
||||
'aria-describedby': error ? `${id}-err` : undefined,
|
||||
}
|
||||
const value = f.values[name]
|
||||
return (
|
||||
<div key={name} className={span}>
|
||||
{field.blockType === 'checkbox' ? (
|
||||
<label htmlFor={id} className="flex items-start gap-2">
|
||||
<input type="checkbox" {...common} checked={Boolean(value)} onChange={(e) => f.setField(name, e.target.checked)} />
|
||||
<span>{field.label}</span>
|
||||
</label>
|
||||
) : (
|
||||
<>
|
||||
<label htmlFor={id} className="mb-1 block">{field.label}</label>
|
||||
{field.blockType === 'textarea' ? (
|
||||
<textarea {...common} rows={5} value={String(value ?? '')} onChange={(e) => f.setField(name, e.target.value)} />
|
||||
) : field.blockType === 'select' ? (
|
||||
<select {...common} value={String(value ?? '')} onChange={(e) => f.setField(name, e.target.value)}>
|
||||
<option value="" />
|
||||
{(field.options ?? []).map((o) => <option key={o.value} value={o.value}>{o.label ?? o.value}</option>)}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
{...common}
|
||||
type={field.blockType === 'email' ? 'email' : field.blockType === 'number' ? 'number' : 'text'}
|
||||
autoComplete={field.blockType === 'email' ? 'email' : undefined}
|
||||
value={String(value ?? '')}
|
||||
onChange={(e) => f.setField(name, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{error && <p id={`${id}-err`} className="mt-1 text-sm text-red-600">{error}</p>}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<div className="col-span-12"><ts.TurnstileWidget /></div>
|
||||
{f.errorMessage && <p role="alert" className="col-span-12 text-red-600">{f.errorMessage}</p>}
|
||||
<div className="col-span-12">
|
||||
<button type="submit" disabled={f.isSubmitting}>{form.submitButtonLabel}</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// src/components/forms/formClasses.ts — the ONLY place forms are styled. Every
|
||||
// panel form (RenderForm / BuilderForm) uses it. Values = the project's design
|
||||
// tokens (DESIGN.md); the plugin ships no styles. Delete keys you don't need.
|
||||
import type { BuilderFormClassNames } from '@intecion/ipal-kit/client'
|
||||
|
||||
export const formClasses: BuilderFormClassNames = {
|
||||
form: 'grid gap-6',
|
||||
progress: 'text-sm text-muted', // "Krok 1 z 3"
|
||||
step: 'grid gap-4',
|
||||
stepTitle: 'text-h3 font-semibold',
|
||||
stepDescription: 'text-muted',
|
||||
fields: 'grid grid-cols-12 gap-4',
|
||||
field: 'col-span-12',
|
||||
fieldHalf: 'md:col-span-6', // width ≤ 50 in the panel
|
||||
label: 'mb-1 block font-medium',
|
||||
input: 'w-full rounded-md border border-border px-3 py-2',
|
||||
textarea: 'w-full rounded-md border border-border px-3 py-2',
|
||||
select: 'w-full rounded-md border border-border px-3 py-2',
|
||||
checkboxLabel: 'flex items-start gap-2',
|
||||
choices: 'grid gap-2', // radio / checkbox group <fieldset>
|
||||
legend: 'mb-1 font-medium',
|
||||
choice: 'flex items-center gap-2',
|
||||
error: 'mt-1 text-sm text-danger',
|
||||
formError: 'text-danger',
|
||||
actions: 'flex gap-3',
|
||||
back: 'btn btn-secondary', // same classes as Button.tsx variants
|
||||
submit: 'btn btn-primary',
|
||||
success: 'rounded-md bg-surface p-6',
|
||||
}
|
||||
@@ -27,6 +27,13 @@ const FORM = {
|
||||
{ blockType: 'email', name: 'email', required: true, width: 50, label: { pl: 'E-mail', en: 'E-mail' } },
|
||||
{ blockType: 'text', name: 'phone', required: false, width: 50, label: { pl: 'Telefon', en: 'Phone' } },
|
||||
{ blockType: 'textarea', name: 'message', required: true, width: 100, label: { pl: 'Wiadomość', en: 'Message' } },
|
||||
// Step-by-step form: a `step` block starts a new screen (title/description per language).
|
||||
// { blockType: 'step', title: { pl: 'Projekt', en: 'Project' } },
|
||||
// Choice lists (option labels per language, values stay the same):
|
||||
// { blockType: 'radio', name: 'budget', required: true, label: { pl: 'Budżet', en: 'Budget' },
|
||||
// options: [{ value: 's', label: { pl: 'do 10 tys.', en: 'up to 10k' } }, …] },
|
||||
// { blockType: 'checkboxGroup', name: 'services', maxSelected: 3, label: {…}, options: [ …same shape… ] },
|
||||
// { blockType: 'date', name: 'deadline', label: { pl: 'Termin', en: 'Deadline' } },
|
||||
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
|
||||
{
|
||||
blockType: 'checkbox',
|
||||
@@ -112,6 +119,20 @@ if (!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(notifyTo)) {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
/** A field with every per-language text ({ pl, en }) resolved: label, step title/description, option labels. */
|
||||
function localizeField(field: Record<string, unknown>, locale: string): Record<string, unknown> {
|
||||
const text = (v: unknown) => (v && typeof v === 'object' ? pick(v as Localized, locale) : v)
|
||||
return {
|
||||
...field,
|
||||
...('label' in field ? { label: text(field.label) } : {}),
|
||||
...('title' in field ? { title: text(field.title) } : {}),
|
||||
...('description' in field ? { description: text(field.description) } : {}),
|
||||
...(Array.isArray(field.options)
|
||||
? { options: (field.options as Record<string, unknown>[]).map((o) => ({ ...o, label: text(o.label) })) }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Form data in one locale (localized fields resolved for it). */
|
||||
function dataFor(locale: string) {
|
||||
return {
|
||||
@@ -131,7 +152,7 @@ function dataFor(locale: string) {
|
||||
subject: pick(FORM.confirmationEmail.subject, locale),
|
||||
},
|
||||
],
|
||||
fields: FORM.fields.map(({ label, ...field }) => ({ ...field, label: pick(label, locale) })),
|
||||
fields: FORM.fields.map((field) => localizeField(field as Record<string, unknown>, locale)),
|
||||
submitButtonLabel: pick(FORM.submitButtonLabel, locale),
|
||||
title: FORM.title,
|
||||
}
|
||||
@@ -155,7 +176,7 @@ if (!id) {
|
||||
for (const locale of locales.filter((l) => l !== defaultLocale)) {
|
||||
const doc = (await payload.findByID({ collection: 'forms' as never, depth: 0, id, locale: locale as never })) as {
|
||||
emails?: { id?: string }[]
|
||||
fields?: { id?: string }[]
|
||||
fields?: { id?: string; options?: { id?: string }[] }[]
|
||||
}
|
||||
const d = dataFor(locale)
|
||||
await payload.update({
|
||||
@@ -163,7 +184,14 @@ for (const locale of locales.filter((l) => l !== defaultLocale)) {
|
||||
data: {
|
||||
...d,
|
||||
emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })),
|
||||
fields: d.fields.map((f, i) => ({ ...f, id: doc.fields?.[i]?.id })),
|
||||
// Keep row ids (fields and their options) — new ids would wipe the other languages' texts.
|
||||
fields: d.fields.map((f, i) => ({
|
||||
...f,
|
||||
id: doc.fields?.[i]?.id,
|
||||
...(Array.isArray(f.options)
|
||||
? { options: (f.options as Record<string, unknown>[]).map((o, j) => ({ ...o, id: doc.fields?.[i]?.options?.[j]?.id })) }
|
||||
: {}),
|
||||
})),
|
||||
} as never,
|
||||
id,
|
||||
locale: locale as never,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: ipal-nav
|
||||
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.
|
||||
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 from the plugin), 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
|
||||
@@ -19,10 +19,11 @@ Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-blo
|
||||
(teksty localized), `access.read: () => true`.
|
||||
2. Hook `afterChange` na każdym globalu: `revalidatePath('/', 'layout')`
|
||||
(wstrzyknięty z `next/cache`, hooks.md).
|
||||
3. `src/lib/navigation.ts` (`resolveNav`) — linki rozwiązane na serwerze do
|
||||
`{ href, label, newTab, subItems }`.
|
||||
3. Menu: `await resolveNav(header.navItems, locale)` z `lib/content` (plugin) — linki
|
||||
rozwiązane na serwerze do `{ href, label, internal, newTab, targetProps, children }`.
|
||||
Nie twórz `lib/navigation.ts`.
|
||||
4. `src/components/layout/Header.tsx`, `Footer.tsx` (serwer), `MobileNav.tsx`
|
||||
(`'use client'`, tylko stan otwarcia, dane przez props, `import type` z lib).
|
||||
(`'use client'`, tylko stan otwarcia, dane przez props, `import type { NavItem } from '@intecion/ipal-kit'`).
|
||||
5. **Linki prawne w stopce** z ról System Pages (`getSystemPagePath` + tytuł
|
||||
strony) — nie jako ręczne pozycje. Rok w copyright z kodu, nazwa z `Company`.
|
||||
6. Logo z Site Settings przez `<Media>` — nie duplikuj pola w Header.
|
||||
|
||||
@@ -86,49 +86,16 @@ export const Footer: GlobalConfig = {
|
||||
- **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).
|
||||
Menu z globala rozwiązuje plugin: `await resolveNav(header.navItems, locale)` z `lib/content`
|
||||
→ `{ href, label, internal, newTab, targetProps, children }[]` (martwe linki pominięte, dowolna
|
||||
głębokość). To zwykłe dane — idą wprost do klienckiego `MobileNav`. Nie twórz `lib/navigation.ts`.
|
||||
|
||||
```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 { resolveNav } from '@/lib/content'
|
||||
import { CMSLink } from '@/components/ui/CMSLink'
|
||||
import { MobileNav } from './MobileNav'
|
||||
|
||||
@@ -141,9 +108,7 @@ export async function Header({ header, locale }: { header: HeaderData; locale: s
|
||||
<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>
|
||||
<Link href={item.href} {...item.targetProps}>{item.label}</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -160,7 +125,7 @@ export async function Header({ header, locale }: { header: HeaderData; locale: s
|
||||
'use client'
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import type { NavItem } from '@/lib/navigation' // import TYPU — nie ciągnie kodu serwera
|
||||
import type { NavItem } from '@intecion/ipal-kit' // import TYPU — nie ciągnie kodu serwera
|
||||
|
||||
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
@@ -28,8 +28,8 @@ Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Goo
|
||||
| unknown URL returns 200 | brak `notFound()` w catch-all |
|
||||
| sitemap URLs not 200 | w sitemapie adresy z przekierowaniem (stare slugi) |
|
||||
| robots.txt points to localhost | `NEXT_PUBLIC_SERVER_URL` nieustawione w buildzie |
|
||||
| no JSON-LD structured data | brak `<JsonLdGraph>` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings |
|
||||
| `/llms.txt` / `/llms-full.txt` → 404 | brak trasy `createLlmsTxtRoute` (drugiej z `full: true`) |
|
||||
| no JSON-LD structured data | brak `<SiteProviders>` / `<JsonLdGraph>` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings |
|
||||
| `/llms.txt` / `/llms-full.txt` → 404 | brak trasy (`export { llmsRoute as GET }` / `llmsFullRoute` z `lib/content`) |
|
||||
| Markdown version `/md/…` → 404 | brak `src/app/md/[locale]/[[...slug]]/route.ts`; strona noindex/draft |
|
||||
| MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) |
|
||||
|
||||
|
||||
@@ -38,19 +38,19 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
|
||||
Impeccable albo załóż neutralne tokeny), `fluid.css` lub `fluid-wide.css` (AGENT §6.11a), fonty
|
||||
przez `next/font` z `latin-ext`, `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
|
||||
6. **Routing** — `proxy.ts` (`createProxy(i18nConfig, { NextResponse, markdown: true })`), `lib/content.ts`
|
||||
(`markdownAlternate: true`), layout bez `<head>` z `JsonLdGraph`, `TurnstileProvider`
|
||||
(`getTurnstileConfig`), consent (`equalChoice`, `logEndpoint`) i `Analytics` (PROGRAMISTA §2.8),
|
||||
catch-all z ISR + `generateStaticParams` + `resolveRedirect` + `getPageJsonLd`,
|
||||
`not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md).
|
||||
7. **SEO i bezpieczeństwo** — sitemap (`sitemap.xml/route.ts` = `sitemapRoute`, bez CSS w `public/`), robots, manifest, health
|
||||
(z `force-dynamic`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`,
|
||||
(`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7),
|
||||
layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`,
|
||||
catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`,
|
||||
`not-found.tsx`: `createNotFoundPage(content, { blocks })` (PROGRAMISTA §2.6–2.8, pages.md).
|
||||
7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, health jako re-eksporty z `lib/content`
|
||||
(`sitemapRoute`, `robots`, `manifest`, `healthRoute`; z `force-dynamic` poza robots; bez CSS w `public/`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`,
|
||||
`images: buildImagesConfig()`,
|
||||
`instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` z `@intecion/ipal-kit/env` (PROGRAMISTA §2.8–2.9, env.md).
|
||||
8. **GEO (obowiązkowe)** — `llms.txt`, `llms-full.txt` (`full: true`), `md/[locale]/[[...slug]]/route.ts`
|
||||
(`createMarkdownRoute`), `api/mcp/route.ts` (publiczny), `indexnow-key.txt/route.ts`,
|
||||
`summaryField: 'aiSummary'` w trasach AI; robots
|
||||
8. **GEO (obowiązkowe)** — re-eksporty z `lib/content`: `llms.txt` (`llmsRoute`), `llms-full.txt`
|
||||
(`llmsFullRoute`), `md/[locale]/[[...slug]]/route.ts` (`markdownRoute`), `api/mcp/route.ts`
|
||||
(`mcpGET`/`mcpPOST`, publiczny), `indexnow-key.txt/route.ts` (`indexNowKeyRoute`); robots
|
||||
wpuszcza boty AI (PROGRAMISTA §2.8, AGENT.md §0b.5–8).
|
||||
9. **Formularze** — skill **ipal-form**: renderer + `createSubmitAction` raz, każdy formularz z seeda
|
||||
9. **Formularze** — skill **ipal-form**: blok z `<RenderForm>`, `formClasses.ts`, `createSubmitAction` raz, każdy formularz z seeda
|
||||
(mail do firmy + potwierdzenie do klienta). Cookies: skan + import (ipal-consent-check), `<CookieTable>`
|
||||
na stronie polityki cookies.
|
||||
10. **Nawigacja** — skill **ipal-nav**.
|
||||
|
||||
@@ -30,6 +30,14 @@ nie dodatek. Pomijasz tylko z decyzją klienta w `AGENTS.md` (`ipal-audit-skip:`
|
||||
wymagany — sprawdź, że każdy formularz ma widget); `clientIp(await headers())` w
|
||||
akcji formularza + `IPAL_IP_HEADER` w env produkcji; `buildR2Storage` wpięty.
|
||||
|
||||
**→ 1.9.2 (PROGRAMISTA §6, poz. 28–33) — import zamiast kodu, zacznij od poz. 28 (bezpieczeństwo):**
|
||||
własny `FormRenderer` przekazywał do HTML zakładkę Emails (adresy firmy) → blok z `<RenderForm>` +
|
||||
`formClasses.ts`, usuń renderer. Potem: layout → `SiteProviders`, strona i 404 → `createPageRoute` /
|
||||
`createNotFoundPage`, trasy GEO → re-eksporty z `lib/content`, `src/fields/section*.ts` i
|
||||
`lib/navigation.ts` → `buildSection*Field`, `resolveNav`, `resolveLink`. Każdą pozycję sprawdź w
|
||||
przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres: `migrate:create`
|
||||
(nowe typy pól formularza i teksty w Notifications).
|
||||
|
||||
## 2. Inwentaryzacja (bez zmian w kodzie)
|
||||
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
|
||||
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
|
||||
|
||||
Reference in New Issue
Block a user